From b2f8f932832a53392fa31d5f56f7c7ae24160e88 Mon Sep 17 00:00:00 2001 From: Brian Taylor Date: Tue, 1 Dec 2026 15:56:01 -0500 Subject: [PATCH] Release v0.3.4 Upgrading - Goldens and worktrees made with v0.3.3 keep working. - Windows: keep ReFS dedup off on the volume that holds the project and its worktrees, and run doctor to see how many more worktrees fit. seed, new and hydrate can now fail with exit 2 and reason clone_copied where they used to report success after a byte copy (see Fixes). A script that branches on reason should handle it. Added - .uwt-keep: a committed file at the root of the repo or workspace listing untracked paths that new keeps instead of cleaning, such as build output (AssetBundles, Assets/StreamingAssets/aa) that a warmup would otherwise rebuild in every worktree. One plain path per line, no globs. new reads the copy committed on the branch it checks out, so a branch can keep less; an untracked .uwt-keep is ignored. new names what it kept, and new --json reports it as kept. Kept files can be stale on a branch that changes what they are built from. Works for git and Plastic. - doctor on Windows estimates how many more worktrees fit under ReFS's limit of 8,176 references per block, from the reference counts of the golden's 32 largest Library files. It warns under 50 and fails at none. - measure reports compressed extents. On ReFS, extents left by dedup or compression have no physical address; they are now listed per tree as compressed (logical size) and kept out of allocated, private and shared, instead of being reported as unmapped. On btrfs, --json gains inline_bytes and encoded_extents. Existing keys are unchanged. Fixes - Windows: a clone that robocopy turned into a byte copy is now refused. robocopy copies a file ReFS will not clone and still reports success. ReFS stops cloning a block at 8,176 references, and with dedup on, which spends most of them inside a single file, that came at the seventh worktree of a mid-size project: whole-file copies of its DataStore and ArtifactDB, reported as ready. seed, new and hydrate now read the reference counts of the 32 largest files each clone wrote, and if any was copied they fail with exit 2, reason clone_copied, and roll back. Cost: a few ms per file. - measure on btrfs: compressed extents were counted at their uncompressed length, which inflated allocated and could make a group larger than its whole tree, and files stored inline in metadata counted 4 KiB each. Compressed extent sizes are now estimated (an upper bound, within 1.4% of compsize when tested), inline files count their size, and the block size is read from the volume. Each byte counts once per tree, in one group, so the groups add up to the tree. - measure on Windows without --json failed under Windows PowerShell 5.1, i.e. on any machine without pwsh. Under PowerShell 7 it never printed the unmapped line. - The scripts ship executable. unity-worktree-cow.sh and measure.py were mode 644, so running them directly on macOS or Linux failed with Permission denied. - Troubleshooting no longer says to re-seed after ReFS error 347. A re-seed shares the source's blocks and does not reset the count. --- .github/workflows/tests.yml | 45 +++- README.md | 3 +- skills/unity-worktree-cow/SKILL.md | 93 ++++++- skills/unity-worktree-cow/scripts/measure.ps1 | 117 ++++++--- skills/unity-worktree-cow/scripts/measure.py | 119 +++++++-- .../scripts/unity-worktree-cow.sh | 214 ++++++++++++++- tests/README.md | 18 +- tests/run-tests.sh | 243 +++++++++++++++++- 8 files changed, 750 insertions(+), 102 deletions(-) mode change 100644 => 100755 skills/unity-worktree-cow/scripts/measure.py mode change 100644 => 100755 skills/unity-worktree-cow/scripts/unity-worktree-cow.sh mode change 100644 => 100755 tests/run-tests.sh diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 69cbaa0..1566480 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,8 +4,8 @@ name: tests # GitHub-hosted runners in seconds. ubuntu (ext4) and windows (NTFS) cannot # block-clone, so they exercise the REFUSAL paths; macOS (APFS) can. The # linux-cow job runs the clone paths on Linux, on loopback btrfs, XFS and ZFS -# volumes. Harnesses that need Unity are instruments, not gates, and are -# deliberately not here. +# volumes; windows-refs runs them on a ReFS VHDX. Harnesses that need Unity are +# instruments, not gates, and are deliberately not here. on: pull_request: @@ -75,3 +75,44 @@ jobs: - name: Run the suite shell: bash run: bash tests/run-tests.sh /mnt/cow + + # robocopy block-clones on ReFS from Windows 11 24H2 / Server 2025, so 2025 + # runs the clone paths and 2022 the refusal paths on the same filesystem. + # Hosted runners are elevated and users usually are not, so a clone path + # that only works as admin would still pass here. + windows-refs: + name: bash (${{ matrix.os }}, ReFS) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: windows-2025 + clones: "yes" + - os: windows-2022 + clones: "no" + steps: + - uses: actions/checkout@v7 + - name: Make a ReFS VHDX + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + New-VHD -Path "$env:RUNNER_TEMP\cow.vhdx" -SizeBytes 8GB -Dynamic | + Mount-VHD -Passthru | + Initialize-Disk -PartitionStyle GPT -Passthru | + New-Partition -DriveLetter R -UseMaximumSize | + Format-Volume -FileSystem ReFS -NewFileSystemLabel cow -Confirm:$false -Force + New-Item -ItemType Directory R:\cow | Out-Null + [Environment]::OSVersion.Version + fsutil fsinfo refsinfo R: + - name: Run the suite + shell: bash + run: | + set -o pipefail + bash tests/run-tests.sh R:/cow 2>&1 | tee "$RUNNER_TEMP/suite.log" + # A suite that passes on the wrong side of cloning has not tested what this job is for. + clones="$(sed -n 's/^fixture:.*block-cloning: \(yes\|no\).*/\1/p' "$RUNNER_TEMP/suite.log" | head -n 1)" + if [ "$clones" != "${{ matrix.clones }}" ]; then + echo "::error::block-cloning was '$clones', expected '${{ matrix.clones }}' on ${{ matrix.os }}" + exit 1 + fi diff --git a/README.md b/README.md index 514b282..47c5cd5 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,8 @@ an editor is using the project. A filesystem that block-clones, with the repo and the worktrees on the same volume: -- **Windows**: ReFS (Dev Drive) on Windows 11 24H2 or later. NTFS cannot. +- **Windows**: ReFS (Dev Drive) on Windows 11 24H2 or later, with ReFS dedup + off on that volume. NTFS cannot. - **macOS**: APFS. - **Linux**: btrfs, XFS with `reflink=1`, or ZFS ≥ 2.2. ext4 cannot. diff --git a/skills/unity-worktree-cow/SKILL.md b/skills/unity-worktree-cow/SKILL.md index 6a249d6..168607b 100644 --- a/skills/unity-worktree-cow/SKILL.md +++ b/skills/unity-worktree-cow/SKILL.md @@ -128,6 +128,7 @@ outcomes apart: | Editor has the project open | `error`, exit 3, `reason` = `editor_busy` | | Volume cannot clone | `error`, exit 2, `reason` = `unsupported_volume` | | Worktree and golden on different volumes | `error`, exit 2, `reason` = `different_volume` | +| ReFS copied files instead of cloning them (Troubleshooting) | `error`, exit 2, `reason` = `clone_copied` | ### A `Library/` copied in by hand @@ -151,9 +152,9 @@ The fix is to delete `Library/Bee`, `BurstCache`, `BuildCache` and | command | what it does | |---|---| -| `doctor [PATH]` | Proves this volume block-clones by doing one and reading the refcount back. Checks the golden and cache root are on the project's volume, which open-file check the interlock will use, whether an editor is live, and the golden's state. Warns on Windows when long paths are off, and when the `Library/` holds build state made in another checkout. | +| `doctor [PATH]` | Proves this volume block-clones by doing one and reading the refcount back. Checks the golden and cache root are on the project's volume, which open-file check the interlock will use, whether an editor is live, and the golden's state. Warns on Windows when long paths are off, and when the `Library/` holds build state made in another checkout. On Windows, estimates how many more worktrees fit under ReFS's per-block reference limit, and fails at none. | | `seed [PATH] [--force]` | Snapshots the working tree and `Library/` (minus the deny list) plus the git index. Refuses while an editor or Data Store has the project open. Cheap; re-run after editor upgrades. | -| `new BRANCH [--path DIR] [--base REF] [--inherit-untracked] [--init-submodules] [--verify] [--json]` | `git worktree add --no-checkout`, clone the snapshot, hand git the snapshot's index, `reset --hard` to the branch, verify zero tracked differences, clean inherited untracked files, hydrate `Library/`. Refuses before registering anything if the volume cannot clone, or if it folds case and the branch has paths that collide by case. Rolls back on failure. | +| `new BRANCH [--path DIR] [--base REF] [--inherit-untracked] [--init-submodules] [--verify] [--json]` | `git worktree add --no-checkout`, clone the snapshot, hand git the snapshot's index, `reset --hard` to the branch, verify zero tracked differences, clean inherited untracked files except those `.uwt-keep` lists, hydrate `Library/`. Refuses before registering anything if the volume cannot clone, or if it folds case and the branch has paths that collide by case. Rolls back on failure. | | `hydrate [PATH] [--force] [--json]` | Gives an existing worktree a `Library/` cloned from the golden. One that already has a `Library/` is left alone (exit 0), with a warning if it holds build state made in another checkout; `--force` replaces it, and keeps the old one until the new one is in place. | | `list [PATH] [--json]` | Every worktree of the repo, including ones uwt did not create, with its branch, lock state, and whether its `Library/` came from uwt (`uwt`), from an editor (`other`), or is absent (`none`), and a `foreign-build-state` tag where it applies. | | `measure [PATH...] [--by N] [--json]` | Private disk of each worktree and the golden against all the others, by physical-block overlap, with the largest private groups. Read-only. See "Measuring it yourself". | @@ -173,11 +174,13 @@ stderr and stdout carries exactly one record, either `{"status":"ok","command":"new","value":{...}}` or `{"status":"error","exit":2,"reason":"no_golden","message":"..."}`. `reason` is there when the failure is one a script can act on: `no_golden`, -`editor_busy`, `unsupported_volume`, `different_volume`, `other_project`. +`editor_busy`, `unsupported_volume`, `different_volume`, `other_project`, +`clone_copied`. `hydrate`'s value has `project`, `action`, `library`, `build_target`, `foreign_build_state` and `seconds`. `new`'s value has `path`, `project`, `uwt` (this script's absolute path), `branch`, `head`, `seconds`, -`verified` and `submodules_uninitialized`; `remove`'s has `path`, `branch` and +`verified`, `submodules_uninitialized` and `kept` (the `.uwt-keep` paths it +kept); `remove`'s has `path`, `branch` and `branch_deleted`. A project in a subdirectory of its repo (a monorepo) works: `seed` records @@ -190,7 +193,18 @@ small. One golden per repo, so one Unity project per repo. A filesystem that block-clones, with golden and worktrees on **one volume**: - **Windows**: ReFS (Dev Drive) on Windows 11 24H2 or later. Runs under Git - Bash and clones with robocopy. NTFS cannot clone. + Bash and clones with robocopy. NTFS cannot clone. Keep ReFS dedup off on + that volume (`Get-ReFSDedupStatus`, as administrator). Dedup folds repeated + blocks inside a file, so one block can already carry a thousand references + before any clone, and each clone of the file adds as many again. ReFS stops + cloning a block at 8,176 references, and on a deduplicated volume that came + at the seventh worktree of a mid-size project. `doctor` estimates how many + more worktrees fit, and `seed`, `new` and `hydrate` fail with + `clone_copied` once none do (see Troubleshooting). Turning dedup off does + not undo the blocks it already folded or compressed. `measure` cannot + locate compressed extents, which dedup and ReFS compression both make, so + it reports them as `compressed` and leaves them out of `allocated`, + `private` and `shared`. - **macOS**: APFS. `new` re-reads every tracked byte once there, so on a large LFS project it takes about a minute (see Troubleshooting). - **Linux**: btrfs, XFS with `reflink=1`, ZFS ≥ 2.2 (`measure` excepted). ext4 @@ -252,8 +266,8 @@ and ~10 s, and opened with 0 assets imported. `cm workspace create` into an empty directory (its own name and GUID), clone the snapshot, place the snapshot's wktree and selector (never `plastic.workspace`), `cm undo -r` to the snapshot's changeset, `cm switch`, - require zero pending or local changes, delete private and ignored files, - hydrate. The workspace is named after its directory, which must be unused + require zero pending or local changes, delete private and ignored files + except those a checked-in `.uwt-keep` lists, hydrate. The workspace is named after its directory, which must be unused as a workspace name on the machine. Rolls back on failure, branch included. - **`seed` refuses pending changes** (checkouts, adds, moves, deletes, merges): the wktree would carry them, and any exclusive lock a checkout @@ -314,7 +328,7 @@ switches branches) but the reimport lands as private disk. `hydrate` warns when the golden's version differs from the worktree's. **Never clone worktree-to-worktree, only from the golden.** ReFS caps a -region at 8175 references; chaining multiplies them. uwt only ever clones the +block at 8,176 references; chaining multiplies them. uwt only ever clones the golden. **Keep Windows worktree roots short** unless `LongPathsEnabled=1`: @@ -390,6 +404,20 @@ checkout, full of absolute paths) are left out of the snapshot. Untracked files that are in the snapshot are removed from a new worktree unless you pass `--inherit-untracked`. +To keep some of them, such as build output a first open or a CI warmup would +otherwise rebuild, commit a `.uwt-keep` at the root of the repo or workspace: + +``` +# one path per line, relative to the root; no globs +AssetBundles +Assets/StreamingAssets/aa +``` + +`new` reads the copy committed on the branch it checks out, so a branch can +keep less, and names what it kept (`kept` in `--json`). Kept files were built +from the snapshot's commit; on a branch that changes what they are built from +they are stale, and the project has to rebuild them. + The deny list is measured, not argued. Grafting a whole `Bee` into a worktree and building a player there (Unity 6000.7.0b1, ReFS): the build succeeded but took 33 s *longer* than without the graft, kept the donor's player DAG and stripper response file, read the donor's link @@ -402,6 +430,9 @@ artifacts by absolute path. 1. `git worktree add --no-checkout` registers the worktree and writes no files. 2. The snapshot (minus `Library`) is cloned in, one directory-level clone. + robocopy copies a file ReFS will not clone and still reports success, so + on Windows this and every other clone then reads the reference counts of + the 32 largest files it wrote and rolls back if any was copied. 3. The snapshot's git index is copied into the worktree's git dir. git decides "unchanged" from the stat data cached in the index, and the clone preserves mtimes, so every file that matches is skipped. @@ -424,7 +455,8 @@ artifacts by absolute path. tracked byte once. On macOS and Linux the status has already done exactly that, so `--verify` says so and skips a second pass (about a minute on the 23.5 GB LFS project). -6. `git clean -xdf`, then `Library/` is cloned from the golden. +6. `git clean -xdf`, sparing what `.uwt-keep` lists, then `Library/` is + cloned from the golden. ## Cost model @@ -439,6 +471,8 @@ there is to save, not what a worktree costs. Two corrections when predicting from a histogram: identical trees can store a different number of files inline (a golden 50,370, a fresh worktree of it 57,111), and every inline file is a private cluster, so allow a few percent. +On btrfs, files up to 2 KiB (the default `max_inline`) live inside its +metadata instead: a clone copies them, and `measure` counts each at its size. ## Measuring it yourself @@ -452,8 +486,11 @@ A block is private to a worktree when no other tree (the main checkout and its `.git`, the golden, sibling worktrees) maps the same physical block. `measure` reads physical extents directly: `FSCTL_GET_RETRIEVAL_POINTERS` on Windows (through PowerShell and inline C#), FIEMAP on Linux and `F_LOG2PHYS_EXT` on -macOS (through `python3`). Files stored inline count as one private cluster -each. Data still in the write cache has no blocks yet, and a cached overwrite +macOS (through `python3`). Each block counts once per tree, so the groups add +up to the tree. Files stored resident on ReFS count as one private cluster +each; files stored inline on btrfs count their size, which is data in btrfs +metadata (stored twice on a single-device volume, which `measure` does not +count, as it does not count RAID copies of data). Data still in the write cache has no blocks yet, and a cached overwrite of a clone still maps to the shared ones, so `measure` flushes every file written in the last 30 minutes before reading it; it is safe to run right after work, with the editor closed. On ReFS it takes 30 s for a 41.5k-file project with four worktrees and @@ -461,6 +498,25 @@ the golden, ~50k files each, and gives the same answer every run. ZFS clones blocks but does not report physical extents, so `measure` refuses there (exit 2). +On compressed btrfs (`compress`, `compress-force`, `chattr +c`) the kernel +reports where a compressed extent starts but not how long it is on disk, only +its uncompressed length. `measure` still tells shared from private exactly, +since every reference to an extent reports the same start, but it estimates +each one's size from the gap to the next extent, capped at 128 KiB, and says +how many it estimated. The estimate is an upper bound, close when the data was +written in one pass: on a `compress-force=zstd:3` volume holding a 41k-file +project, two worktrees and the golden, `allocated` came within 1.4% of +`compsize` for every tree. Inline files are counted uncompressed, which there +overstated each tree's private by about 28 MiB. `compsize` (run as root) reads +the exact sizes. + +On ReFS, dedup and compression leave compressed extents with no physical +address at all, so neither their size on disk nor who shares them can be +read. `measure` lists them per tree as `compressed` (logical size) and leaves +them out of `allocated`, `private` and `shared%`. Where they are a large part +of a tree, its figures say little: on a deduplicated volume, the +`Library/DataStore` of a project with 39k tracked files held 4.7 GiB of them. + What not to use: - **Free space and `du`.** Free space updates lazily on ReFS and APFS, and @@ -509,10 +565,18 @@ not the bare project name: Unity bakes `productName` into `app.info` and `Get-Volume`). - `doctor` says cloning does not work on Linux: ext4 cannot; XFS must have been created with `-m reflink=1` (`xfs_info | grep reflink`). -- ReFS error 347 / `0xC000048C` (too many clones): a region hit the 8175 - reference cap. Re-seed to reset the count. - The disk fills up after a successful `new`: cloned blocks diverge lazily, when Unity writes. Budget as above. +- `seed`, `new` or `hydrate` fails with "ReFS copied N of the largest files + instead of cloning them" (`clone_copied`): ReFS refused to clone those + files (error 347, a block at its 8,176-reference limit) and robocopy copied + them instead, reporting success; uwt checks and rolls back. The usual cause + is ReFS dedup on the volume (see Requirements): `Get-ReFSDedupStatus` as + administrator. `doctor` names the file that fills first and estimates how + many more worktrees fit. Re-seeding does not help, since the golden shares the + source's blocks. Removing worktrees does, about 15 s after the delete, when + ReFS releases their references. Turn dedup off for that volume so it stops + creating more. - `new` reports tracked differences after reset and rolls back: the snapshot's index did not match its files (mtimes not preserved). Re-seed and retry. - Every fresh worktree spends minutes importing: the golden is from another @@ -526,7 +590,8 @@ not the bare project name: Unity bakes `productName` into `app.info` and `git status` re-hashing the tracked content, LFS included, because every cloned file has a new inode. It scales with tracked bytes (URP, 0.95 GB: 8 s for the whole `new`). Measured on macOS: 65.5 s of a 78 s `new` - for 23.5 GB of LFS content; the reset itself took 0.4 s. It is paid once per + for 23.5 GB of LFS content; the reset itself took 0.4 s. On Linux btrfs: + 12 s of a 13 s `new` for 41k tracked files, 5.3 GB with LFS. It is paid once per worktree. Skipping it would only move it to the first `git status` anyone runs there. `GIT_TRACE2_PERF=/tmp/t.txt` on the `new` shows it as the `refresh` region. diff --git a/skills/unity-worktree-cow/scripts/measure.ps1 b/skills/unity-worktree-cow/scripts/measure.ps1 index 1949354..79ef0b3 100644 --- a/skills/unity-worktree-cow/scripts/measure.ps1 +++ b/skills/unity-worktree-cow/scripts/measure.ps1 @@ -18,6 +18,11 @@ Files with data but no extents are stored inline in ReFS metadata; each counts as one private cluster. Free space and du are not valid measures. + ReFS dedup and compression store compressed extents with no physical + location (LCN -1), so whether another tree shares them cannot be told. + They are reported as `compressed` and left out of allocated, private and + shared. + Called by `uwt measure`; usable on its own. #> [CmdletBinding(PositionalBinding = $false)] @@ -56,9 +61,12 @@ public static class UwtLcn { return (long)spc * bps; } - // Appends [lcn, lcn+len) runs to runs (pairs). Returns false if the file - // could not be opened. Holes (Lcn -1) are skipped. - static bool Extents(string path, List runs) { + // Appends [lcn, lcn+len) runs to runs (pairs) and counts the clusters of + // runs with no LCN in noLcn. Returns false if the file could not be opened. + // No LCN is a hole in a sparse file, data still in the write cache, or a + // compressed extent. + static bool Extents(string path, List runs, out long noLcn) { + noLcn = 0; // FILE_READ_ATTRIBUTES is enough, and opens files an editor holds exclusively. using (var h = CreateFileW(@"\\?\" + path, 0x80, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) { if (h.IsInvalid) return false; @@ -76,6 +84,7 @@ public static class UwtLcn { long next = BitConverter.ToInt64(buf, 16 + i * 16); long lcn = BitConverter.ToInt64(buf, 24 + i * 16); if (lcn >= 0) { runs.Add(lcn); runs.Add(lcn + (next - prev)); } + else noLcn += next - prev; prev = next; } if (ok || n == 0) return true; @@ -105,7 +114,7 @@ public static class UwtLcn { public class TreeResult { public string Root; - public long Files, Logical, Inline, Unreadable, Allocated, Private, Flushed, Unmapped; + public long Files, Logical, Inline, Unreadable, Allocated, Private, Flushed, Unmapped, Compressed; public Dictionary Groups = new Dictionary(); // files, logical, private clusters internal long[] Runs; // merged [lo, hi) pairs } @@ -138,18 +147,27 @@ public static class UwtLcn { int before = fileRuns.Count; // Recently written data may still be cached, and a cached overwrite of a // clone still maps to the shared clusters it will replace: flush first. - if ((DateTime.UtcNow - fsi.LastWriteTimeUtc).TotalMinutes < RecentMinutes && Flush(fsi.FullName)) t.Flushed++; - if (!Extents(fsi.FullName, fileRuns)) { t.Unreadable++; continue; } + bool recent = (DateTime.UtcNow - fsi.LastWriteTimeUtc).TotalMinutes < RecentMinutes; + bool settled = !recent || Flush(fsi.FullName); + if (recent && settled) t.Flushed++; + long noLcn; + if (!Extents(fsi.FullName, fileRuns, out noLcn)) { t.Unreadable++; continue; } long need = (len + Cluster - 1) / Cluster, have = Covered(fileRuns, before); bool sparse = (fsi.Attributes & FileAttributes.SparseFile) != 0; // A file of one cluster or less with no extents is resident (inline); // anything else short of clusters is unallocated cache: flush, ask again. - if (have < need && !sparse && !(have == 0 && len <= Cluster)) { + if (have + noLcn < need && !sparse && !(have == 0 && noLcn == 0 && len <= Cluster)) { fileRuns.RemoveRange(before, fileRuns.Count - before); - if (Flush(fsi.FullName)) t.Flushed++; - if (!Extents(fsi.FullName, fileRuns)) { t.Unreadable++; continue; } + settled = Flush(fsi.FullName); + if (settled) t.Flushed++; + if (!Extents(fsi.FullName, fileRuns, out noLcn)) { t.Unreadable++; continue; } have = Covered(fileRuns, before); - if (have < need) t.Unmapped += (need - have) * Cluster; + if (have + noLcn < need) t.Unmapped += (need - have - noLcn) * Cluster; + } + // No LCN in a flushed, non-sparse file is a compressed extent. In a + // file that could not be flushed it may still be cache: unmapped. + if (noLcn > 0 && !sparse) { + if (settled) t.Compressed += noLcn * Cluster; else t.Unmapped += noLcn * Cluster; } if (fileRuns.Count == before && len > 0 && len <= Cluster) { t.Inline++; g[2]++; // resident: one cluster, owned by nobody else @@ -185,9 +203,14 @@ public static class UwtLcn { return (b - a) - covered; } - public static TreeResult[] Measure(string[] roots, bool[] report, int by) { - int n = roots.Length; - Cluster = ClusterBytes(roots[0]); + public static TreeResult[] Measure(string[] given, bool[] report, int by) { + int n = given.Length; + Cluster = ClusterBytes(given[0]); + // Roots spelled as .NET spells the files under them: it expands 8.3 + // names (BRIAN~1.TAY), so a root as given may not prefix its own files, + // and a nested tree would not be skipped. + var roots = new string[n]; + for (int k = 0; k < n; k++) roots[k] = new DirectoryInfo(given[k]).FullName; var skip = new HashSet(); foreach (var r in roots) skip.Add(r.TrimEnd('\\').ToLowerInvariant()); var res = new TreeResult[n]; @@ -217,6 +240,17 @@ public static class UwtLcn { } return res; } + + // Largest private first, ties by name. Ordinal, and here rather than in + // Sort-Object: 5.1 sorts unstably and by NLS, 7 stably and by ICU. + public static string[] SortedGroups(TreeResult t) { + var keys = new List(t.Groups.Keys); + keys.Sort((a, b) => { + int c = t.Groups[b][2].CompareTo(t.Groups[a][2]); + return c != 0 ? c : string.CompareOrdinal(a, b); + }); + return keys.ToArray(); + } } '@ @@ -242,37 +276,50 @@ for ($k = 0; $k -lt $res.Count; $k++) { $row = [ordered]@{ name = $names[$k]; path = $r.Root; reported = $report[$k] files = $r.Files; logical = $r.Logical; inline_files = $r.Inline; unreadable = $r.Unreadable - flushed = $r.Flushed; unmapped = $r.Unmapped; allocated = $r.Allocated * $cl + flushed = $r.Flushed; unmapped = $r.Unmapped; compressed = $r.Compressed; allocated = $r.Allocated * $cl } if ($report[$k]) { $row.private = $r.Private * $cl $row.shared = ($r.Allocated - $r.Private) * $cl $row.groups = [ordered]@{} # Every group, largest private first: JSON consumers sum them, so none are dropped. - foreach ($g in ($r.Groups.GetEnumerator() | Sort-Object { -$_.Value[2] })) { - $row.groups[$g.Key] = [ordered]@{ files = $g.Value[0]; logical = $g.Value[1]; private = $g.Value[2] * $cl } + foreach ($key in [UwtLcn]::SortedGroups($r)) { + $g = $r.Groups[$key] + $row.groups[$key] = [ordered]@{ files = $g[0]; logical = $g[1]; private = $g[2] * $cl } } } $out.trees += $row } -if ($Json) { $out | ConvertTo-Json -Depth 6 -Compress; exit 0 } +# The console's code page (437, 1252, ...) would turn non-ASCII paths into +# other bytes or '?'. The console may be the caller's, so put it back. +$enc0 = [Console]::OutputEncoding +[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) +try { + if ($Json) { $out | ConvertTo-Json -Depth 6 -Compress; exit 0 } -$MB = 1048576.0 -'{0,-12} {1,9} {2,12} {3,12} {4,12} {5,8}' -f 'tree', 'files', 'logical', 'allocated', 'private', 'shared%' -foreach ($t in $out.trees) { - if (-not $t.reported) { continue } - $pct = if ($t.allocated) { 100.0 * $t.shared / $t.allocated } else { 0 } - '{0,-12} {1,9:N0} {2,8:N0} MiB {3,8:N0} MiB {4,8:N0} MiB {5,7:N1}%' -f $t.name, $t.files, ($t.logical / $MB), ($t.allocated / $MB), ($t.private / $MB), $pct -} -foreach ($t in $out.trees) { - if (-not $t.reported) { continue } - $top = @($t.groups.Keys | Where-Object { $t.groups[$_].private -gt 0 } | Select-Object -First 10) - if ($top.Count -eq 0) { continue } - ''; "largest private in $($t.name):" - foreach ($k in $top) { - ' {0,10:N1} MiB {1,8:N0} files {2}' -f ($t.groups[$k].private / $MB), $t.groups[$k].files, $k + $MB = 1048576.0 + '{0,-12} {1,9} {2,12} {3,12} {4,12} {5,8}' -f 'tree', 'files', 'logical', 'allocated', 'private', 'shared%' + foreach ($t in $out.trees) { + if (-not $t.reported) { continue } + $pct = if ($t.allocated) { 100.0 * $t.shared / $t.allocated } else { 0 } + '{0,-12} {1,9:N0} {2,8:N0} MiB {3,8:N0} MiB {4,8:N0} MiB {5,7:N1}%' -f $t.name, $t.files, ($t.logical / $MB), ($t.allocated / $MB), ($t.private / $MB), $pct } -} -$um = ($out.trees | Measure-Object unmapped -Sum).Sum -if ($um) { ''; 'unmapped {0:N1} MiB: still not allocated after a flush (a file held open without write sharing); counted neither way' -f ($um / $MB) } -"($($res.Count) trees, $secs s, $cl-byte clusters; inline files count one cluster each)" + foreach ($t in $out.trees) { + if (-not $t.reported) { continue } + $top = @($t.groups.Keys | Where-Object { $t.groups[$_].private -gt 0 } | Select-Object -First 10) + if ($top.Count -eq 0) { continue } + ''; "largest private in $($t.name):" + foreach ($k in $top) { + ' {0,10:N1} MiB {1,8:N0} files {2}' -f ($t.groups[$k].private / $MB), $t.groups[$k].files, $k + } + } + # Not Measure-Object -Property: it cannot read a dictionary key (5.1 throws, 7 sums to nothing). + $um = ($out.trees | ForEach-Object { $_.unmapped } | Measure-Object -Sum).Sum + if ($um) { ''; 'unmapped {0:N1} MiB: still not allocated after a flush (a file held open without write sharing); counted neither way' -f ($um / $MB) } + $cz = @($out.trees | Where-Object { $_.reported -and $_.compressed }) + if ($cz.Count) { + ''; 'compressed (ReFS dedup or compression): ' + (($cz | ForEach-Object { '{0} {1:N0} MiB' -f $_.name, ($_.compressed / $MB) }) -join ', ') + ' stored with no physical address, so not known to be shared or private; left out of allocated, private and shared%' + } + "($($res.Count) trees, $secs s, $cl-byte clusters; inline files count one cluster each)" +} finally { [Console]::OutputEncoding = $enc0 } diff --git a/skills/unity-worktree-cow/scripts/measure.py b/skills/unity-worktree-cow/scripts/measure.py old mode 100644 new mode 100755 index ca481d0..45ede91 --- a/skills/unity-worktree-cow/scripts/measure.py +++ b/skills/unity-worktree-cow/scripts/measure.py @@ -11,7 +11,16 @@ Physical offsets come from FIEMAP on Linux (btrfs, XFS) and F_LOG2PHYS_EXT on macOS (APFS). ZFS clones blocks but has no FIEMAP (OpenZFS 2.4 answers EOPNOTSUPP), so there this exits 1 rather than report every file unmapped. -Inline data (btrfs, small files) counts as one private block. On Linux each +Each block counts once per tree, in the first group (sorted by physical +address) that maps it, so the groups sum to the tree. + +btrfs specifics. Files small enough to live inside btrfs metadata (inline, +2 KiB by default) count their size: a clone copies them, so they are always +private. A compressed extent is reported with its uncompressed length from +its compressed start, and every reference to it, in any tree, has that start; +its size on disk is not in FIEMAP, so it is estimated as the distance to the +next extent start among all trees, at most 128 KiB (the largest compressed +extent). `compsize` reads the exact size, as root. On Linux each file is flushed before it is mapped (FIEMAP_FLAG_SYNC), so delayed-allocation data gets its physical block; on macOS every file written in the last 30 minutes is fsync'd first. Data still with no physical block is reported as @@ -24,7 +33,8 @@ """ import argparse, bisect, errno, fcntl, json, os, struct, sys, time -BLOCK = 4096 +BLOCK = 4096 # replaced by the filesystem's block size in main() +MAX_ENCODED = 128 * 1024 # btrfs: the largest compressed extent, on disk RECENT_SECS = 30 * 60 # files written this recently are flushed before mapping (macOS) @@ -37,29 +47,30 @@ class Unsupported(Exception): L2P = '=Iqq' # struct log2phys, #pragma pack(4): flags, contigbytes, devoffset def extents(fd, size): - """-> ([(lo, hi) device byte ranges], inline_blocks, unmapped_bytes)""" + """-> ([(lo, hi) device byte ranges], [(lo, length) encoded extents], inline, unmapped_bytes)""" out, off = [], 0 while off < size: try: _, n, dev = struct.unpack(L2P, fcntl.fcntl(fd, F_LOG2PHYS_EXT, struct.pack(L2P, 0, size - off, off))) except OSError: - return out, 0, size - off + return out, [], False, size - off if n <= 0: - return out, 0, size - off + return out, [], False, size - off out.append((dev - dev % BLOCK, dev + n + (-(dev + n) % BLOCK))) off += n - return out, 0, 0 + return out, [], False, 0 else: FS_IOC_FIEMAP = 0xC020660B FIEMAP_FLAG_SYNC = 0x1 # flush the file first, so delalloc data has a physical block FIEMAP_EXTENT_LAST, FIEMAP_EXTENT_UNKNOWN, FIEMAP_EXTENT_DELALLOC = 0x1, 0x2, 0x4 + FIEMAP_EXTENT_ENCODED = 0x8 # compressed: fe_length is the uncompressed length FIEMAP_EXTENT_DATA_INLINE = 0x200 HDR = '=QQIIII' # fm_start, fm_length, fm_flags, fm_mapped_extents, fm_extent_count, fm_reserved EXT = '=QQQQQIIII' # fe_logical, fe_physical, fe_length, 2x reserved64, fe_flags, 3x reserved BATCH = 256 def extents(fd, size): - out, inline, unmapped, start = [], 0, 0, 0 + out, enc, inline, unmapped, start = [], [], False, 0, 0 while True: buf = bytearray(struct.pack(HDR, start, 2 ** 64 - 1 - start, FIEMAP_FLAG_SYNC, 0, BATCH, 0) + bytes(struct.calcsize(EXT) * BATCH)) try: @@ -67,23 +78,26 @@ def extents(fd, size): except OSError as e: if e.errno in (errno.EOPNOTSUPP, errno.ENOTTY): raise Unsupported('FIEMAP') - return out, inline, size + return out, enc, inline, size mapped = struct.unpack_from(HDR, buf)[3] if mapped == 0: - return out, inline, unmapped + return out, enc, inline, unmapped last = False for i in range(mapped): logical, phys, length, _, _, flags, _, _, _ = struct.unpack_from(EXT, buf, struct.calcsize(HDR) + i * struct.calcsize(EXT)) if flags & FIEMAP_EXTENT_DATA_INLINE: - inline += 1 + inline = True elif flags & (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC): unmapped += length + elif flags & FIEMAP_EXTENT_ENCODED: + # Its end on disk is unknown until every tree is walked. + enc.append((phys - phys % BLOCK, length + (-length % BLOCK))) else: out.append((phys - phys % BLOCK, phys + length + (-(phys + length) % BLOCK))) start = logical + length last = last or bool(flags & FIEMAP_EXTENT_LAST) if last: - return out, inline, unmapped + return out, enc, inline, unmapped # ------------------------------------------------------------------ overlap @@ -110,6 +124,34 @@ def uncovered(cover, starts, lo, hi): return (hi - lo) - n +def own(raw): + """[(lo, hi, group)] -> disjoint ranges, each byte given to the first range + (by address, then group) that covers it. Two files of one tree can map the + same blocks (a reflink within the tree, a shared compressed extent).""" + out, end = [], -1 + for lo, hi, key in sorted(raw): + lo = max(lo, end) + if hi > lo: + out.append((lo, hi, key)) + end = hi + return out + + +def place_encoded(trees): + """Give each compressed extent an end: the next extent start among all + trees, within its uncompressed length and MAX_ENCODED.""" + starts = sorted({lo for t in trees for lo, _, _ in t['raw']} | {lo for t in trees for lo, _, _ in t['enc']}) + for t in trees: + for lo, n, key in t['enc']: + hi = lo + min(n, MAX_ENCODED) + i = bisect.bisect_right(starts, lo) + if i < len(starts): + hi = min(hi, starts[i]) + t['raw'].append((lo, hi, key)) + t['encoded'] = len({lo for lo, _, _ in t['enc']}) + del t['enc'] + + def group_key(rel, by): parts = rel.split(os.sep) if len(parts) > by: @@ -118,7 +160,7 @@ def group_key(rel, by): def walk(root, skip, by): - t = {'files': 0, 'logical': 0, 'inline': 0, 'unreadable': 0, 'unmapped': 0, 'groups': {}, 'raw': [], 'rawgroup': []} + t = {'files': 0, 'logical': 0, 'inline': 0, 'inline_bytes': 0, 'unreadable': 0, 'unmapped': 0, 'groups': {}, 'raw': [], 'enc': []} for d, dirs, files in os.walk(root): dirs[:] = [x for x in dirs if os.path.join(d, x) not in skip and not os.path.islink(os.path.join(d, x))] for f in files: @@ -145,11 +187,15 @@ def walk(root, skip, by): os.fsync(fd) except OSError: pass - ex, inl, um = extents(fd, st.st_size) + ex, enc, inl, um = extents(fd, st.st_size) finally: os.close(fd) - t['inline'] += inl; t['unmapped'] += um; g[2] += inl * BLOCK - t['raw'].extend(ex); t['rawgroup'].extend([key] * len(ex)) + if inl: + # Data inside btrfs metadata: never shared, costs its size. + t['inline'] += 1; t['inline_bytes'] += st.st_size; g[2] += st.st_size + t['unmapped'] += um + t['raw'].extend((lo, hi, key) for lo, hi in ex) + t['enc'].extend((lo, n, key) for lo, n in enc) return t @@ -173,36 +219,48 @@ def main(): want = {w.rstrip('/') for w in a.target.split(';') if w} report = [not want or n in want or r in want for n, r in zip(names, roots)] + global BLOCK + try: + BLOCK = os.statvfs(roots[0]).f_frsize or BLOCK + except (OSError, AttributeError): + pass + t0 = time.time() trees = [] for k, r in enumerate(roots): try: - t = walk(r, set(roots) - {r}, a.by) + trees.append(walk(r, set(roots) - {r}, a.by)) except Unsupported as e: sys.exit(f'{r}: this filesystem does not report physical extents ({e}), so private disk ' 'cannot be measured here (ZFS has none)') - t['runs'] = merge(list(t['raw'])) - t['allocated'] = sum(hi - lo for lo, hi in t['runs']) + t['inline'] * BLOCK - trees.append(t) + place_encoded(trees) + for t in trees: + t['raw'] = own(t['raw']) + t['runs'] = merge([[lo, hi] for lo, hi, _ in t['raw']]) + t['allocated'] = sum(hi - lo for lo, hi in t['runs']) + t['inline_bytes'] for k, t in enumerate(trees): if not report[k]: continue cover = merge([tuple(x) for j, o in enumerate(trees) if j != k for x in o['runs']]) starts = [lo for lo, _ in cover] - t['private'] = t['inline'] * BLOCK + sum(uncovered(cover, starts, lo, hi) for lo, hi in t['runs']) - for (lo, hi), key in zip(t['raw'], t['rawgroup']): - t['groups'][key][2] += uncovered(cover, starts, lo, hi) + t['private'] = t['inline_bytes'] + for lo, hi, key in t['raw']: + n = uncovered(cover, starts, lo, hi) + t['private'] += n + t['groups'][key][2] += n secs = round(time.time() - t0, 1) out = {'method': 'physical-overlap', 'cluster_bytes': BLOCK, 'seconds': secs, 'trees': []} for k, t in enumerate(trees): row = {'name': names[k], 'path': roots[k], 'reported': report[k], 'files': t['files'], 'logical': t['logical'], - 'inline_files': t['inline'], 'unreadable': t['unreadable'], 'unmapped': t['unmapped'], 'allocated': t['allocated']} + 'inline_files': t['inline'], 'inline_bytes': t['inline_bytes'], 'encoded_extents': t['encoded'], + 'unreadable': t['unreadable'], 'unmapped': t['unmapped'], 'allocated': t['allocated']} if report[k]: row['private'] = t['private'] row['shared'] = t['allocated'] - t['private'] - # Every group, largest private first: JSON consumers sum them, so none are dropped. - ordered = sorted(t['groups'].items(), key=lambda kv: -kv[1][2]) + # Every group, largest private first, ties by name: JSON consumers sum them, + # so none are dropped. + ordered = sorted(t['groups'].items(), key=lambda kv: (-kv[1][2], kv[0])) row['groups'] = {g: {'files': v[0], 'logical': v[1], 'private': v[2]} for g, v in ordered} out['trees'].append(row) if a.json: @@ -225,7 +283,16 @@ def main(): um = sum(t['unmapped'] for t in out['trees']) if um: print(f"\nunmapped {um / mib:,.1f} MiB: not yet allocated; run sync and measure again") - print(f"({len(trees)} trees, {secs} s, {BLOCK}-byte blocks; inline files count one block each)") + enc = sum(t['encoded_extents'] for t in out['trees']) + inl = [t for t in out['trees'] if t['reported'] and t['inline_files']] + if inl: + print("\ninline (stored in btrfs metadata, private to each tree" + + ("; uncompressed size, compression makes them smaller" if enc else "") + "): " + + ", ".join(f"{t['name']} {t['inline_files']:,} files {t['inline_bytes'] / mib:,.1f} MiB" for t in inl)) + if enc: + print(f"\n{enc:,} compressed extents: on-disk size estimated from extent spacing " + "(compsize reads it exactly, as root)") + print(f"({len(trees)} trees, {secs} s, {BLOCK}-byte blocks)") return 0 diff --git a/skills/unity-worktree-cow/scripts/unity-worktree-cow.sh b/skills/unity-worktree-cow/scripts/unity-worktree-cow.sh old mode 100644 new mode 100755 index cecd899..4d1d65f --- a/skills/unity-worktree-cow/scripts/unity-worktree-cow.sh +++ b/skills/unity-worktree-cow/scripts/unity-worktree-cow.sh @@ -424,13 +424,18 @@ cow_tree() { # cow_tree [--globs] [exclude-name...] # /E all subdirs (empty too), /COPY:DAT + /DCOPY:T keep timestamps - the # warm-index trick below needs file mtimes intact. /MT:8 still block-clones # (verified by refcount) and is ~3x faster on a 24k-file Library. /XJ never - # follows junctions. MSYS_NO_PATHCONV stops Git Bash rewriting /E as a path. + # follows junctions. /NC /BYTES /FP log each file as size and source path, + # for clone_check. MSYS_NO_PATHCONV stops Git Bash rewriting /E as a path. # shellcheck disable=SC2086 MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' \ - robocopy "$(wpath "$src")" "$(wpath "$dst")" /E /COPY:DAT /DCOPY:T /MT:8 /XJ /R:0 /W:0 /NFL /NDL /NJH /NJS /NP \ + robocopy "$(wpath "$src")" "$(wpath "$dst")" /E /COPY:DAT /DCOPY:T /MT:8 /XJ /R:0 /W:0 /NDL /NJH /NJS /NP /NC /BYTES /FP \ ${globs:+/XF $globs} ${xd[@]+/XD "${xd[@]}"} >"$log" 2>&1 local rc=$? - if [ $rc -ge 8 ]; then fail "robocopy failed (rc=$rc):"; tail -5 "$log" | sed 's/^/ /'; rm -f "$log"; return 1; fi + if [ $rc -ge 8 ]; then + fail "robocopy failed (rc=$rc):"; { grep -a ERROR "$log" || tail -5 "$log"; } | tail -5 | sed 's/^/ /' + rm -f "$log"; return 1 + fi + clone_check "$src" "$dst" "$log" || { rm -f "$log"; return 1; } rm -f "$log"; return 0 fi mkdir -p "$dst" || return 1 @@ -462,6 +467,65 @@ refs_shared() { END { exit !shared }' } +# robocopy clones a file when ReFS lets it and copies the bytes when ReFS does +# not, with the same exit code either way, so a probe that passed does not +# prove the next tree cloned. ReFS refuses a clone of a block that already has +# 8,176 references, and its dedup can spend most of those inside one file: on +# a deduplicated volume the seventh worktree of a project got whole-file +# copies of its largest Library files. A copy's extents all have Ref 1 and a +# clone's do not, so the largest files robocopy logged are checked; they are +# most of what a clone shares. Small files are left out: a file of a few +# clusters has read Ref 1 and 2 by turns under heavy writes (see measure.ps1), +# and ReFS stores the smallest inline, with no extents at all. +CLONE_CHECK_FILES=32 CLONE_CHECK_MIN=65536 +clone_check() { # clone_check ; Windows only + local s; s="$(wpath "$1")" + local size p rel f ext copied="" n=0 + while IFS=$'\t' read -r size p; do + rel="${p#"$s"\\}"; [ "$rel" != "$p" ] || continue + rel="${rel//\\//}"; f="$2/$rel"; [ -f "$f" ] || continue + ext="$(fsutil file queryExtentsAndRefCounts "$(wpath "$f")" 2>/dev/null)" + grep -q 'Ref:' <<<"$ext" || continue + refs_shared <<<"$ext" || { copied="$copied${copied:+$'\n'}$rel ($(( (size + 1023) / 1024 )) KiB)"; n=$((n + 1)); } + done < <(tr -d '\r' <"$3" | awk -F'\t' -v min="$CLONE_CHECK_MIN" \ + 'NF >= 2 && $(NF-1) ~ /^ *[0-9]+$/ && $(NF-1) + 0 >= min { print $(NF-1) + 0 "\t" $NF }' \ + | sort -rn | head -n "$CLONE_CHECK_FILES") + [ $n = 0 ] && return 0 + REASON=clone_copied + fail "ReFS copied $n of the largest files instead of cloning them:" + printf '%s\n' "$copied" | head -5 | sed 's/^/ /' + say " Most likely their blocks reached ReFS's limit of 8,176 references, which ReFS dedup on this" + say " volume uses up. Removing worktrees frees references; see SKILL.md 'Troubleshooting'." + return 1 +} + +# How many more clones of the golden's Library fit under that limit. Each +# clone of a file adds, to each of its blocks, as many references as the file +# has copies of that block: one, unless dedup folded repeats together. So a +# block's count R is that number times the trees holding the file, k, and the +# file has room for k * (8176 - R) / R more clones of its fullest block. Most +# blocks of a file are unique, so k is its commonest count. An estimate: a +# tree that rewrote part of the file moves both numbers. +REFS_MAX=8176 +ref_headroom() { # ref_headroom -> " " for the file that fills first + local lib="$1" size f + find "$lib" -type f -size +64k -printf '%s\t%p\n' 2>/dev/null | sort -rn | head -n "$CLONE_CHECK_FILES" \ + | while IFS=$'\t' read -r size f; do + fsutil file queryExtentsAndRefCounts "$(wpath "$f")" 2>/dev/null | tr -d '\r' \ + | awk -v f="${f#"$lib"/}" -v max="$REFS_MAX" ' + function hex(s, v, j) { s = tolower(s); sub(/^0x/, "", s); v = 0 + for (j = 1; j <= length(s); j++) v = v * 16 + index("0123456789abcdef", substr(s, j, 1)) - 1 + return v } + { c = 0; r = 0 + for (i = 1; i < NF; i++) { if ($i == "Clusters:") c = hex($(i + 1)); if ($i == "Ref:") r = hex($(i + 1)) } + if (r > 0) { w[r] += c; if (r > top) top = r } } + END { if (!top) exit + for (r in w) if (w[r] > most) { most = w[r]; k = r } + left = int(k * (max - top) / top); if (left < 0) left = 0 + printf "%d %d %s\n", left, top, f }' + done | sort -n | head -1 +} + # Prove that a clone into shares blocks, by doing one. A capability flag # is not enough: robocopy on NTFS, or on ReFS before Windows 11 24H2, copies # every byte and says nothing. Prints a reason; exit 0 iff cloning works. @@ -606,6 +670,16 @@ cmd_doctor() { say " $gd" say " unity=$(golden_field "$gd" unity_version) commit=$(golden_field "$gd" commit | cut -c1-10) created=$(golden_field "$gd" created) files=$(golden_field "$gd" files) build_target=$(build_target "$gd/Library")" [ "$(golden_field "$gd" unity_version)" = "$(unity_version "$proj")" ] || warn "golden was captured under a different editor version than this checkout declares; re-seed after upgrades" + if [ "$OS" = windows ]; then + local hr left refs hf; hr="$(ref_headroom "$gd/Library")" + if [ -n "$hr" ]; then + read -r left refs hf <<<"$hr" + if [ "$left" -ge 1000 ]; then good "ReFS references: far from the limit (at most $refs on one block of $REFS_MAX)" + elif [ "$left" -ge 50 ]; then good "ReFS references: room for about $left more worktrees (Library/$hf has $refs on one block, limit $REFS_MAX)" + elif [ "$left" -gt 0 ]; then warn "ReFS references: room for about $left more worktree(s) before Library/$hf reaches the limit ($refs of $REFS_MAX on one block); ReFS dedup does this, see SKILL.md 'Troubleshooting'" + else fail "ReFS references: Library/$hf is at the limit ($refs of $REFS_MAX on one block), so new and hydrate would fail with clone_copied; see SKILL.md 'Troubleshooting'"; bad=1; fi + fi + fi else say " none yet - run: uwt seed (with the editor closed)"; fi say ""; head_ "build state" local fb; fb="$(foreign_build_state "$proj")" @@ -790,13 +864,108 @@ pl_branch_create() { # pl_branch_create esac cm_ branch create "br:$1@$2" "$from" -c="created by uwt" >/dev/null 2>&1 } -# git clean -xdf for a workspace: delete private and ignored items. Only paths -# inside are touched, whatever cm prints. +# ------------------------------------------------------------------ keep list +# .uwt-keep, committed at the root of the repo or workspace, lists untracked +# paths that `new` keeps from the snapshot instead of cleaning: build output +# the first open would otherwise rebuild. One path per line, relative to that +# root, no globs; a line starting with # is a comment. The new branch's own +# copy is read, so a branch can keep less. What is kept was built from the +# snapshot's commit, so it can be stale for the branch. +KEEP_FILE=.uwt-keep +KEEP=(); KEPT="" +keep_load() { # keep_load : the valid entries into KEEP, a warning for the rest + local line k + KEEP=() + while IFS= read -r line || [ -n "$line" ]; do + line="${line%$'\r'}" + k="${line#"${line%%[![:space:]]*}"}"; k="${k%"${k##*[![:space:]]}"}" + case "$k" in ''|'#'*) continue ;; esac + k="${k//\\//}" + while [ "${k#./}" != "$k" ]; do k="${k#./}"; done + while [ "${k%/}" != "$k" ]; do k="${k%/}"; done + case "$k" in + *[*?[]*) warn "$KEEP_FILE: ignoring '$k': globs are not supported, list the path"; continue ;; + [A-Za-z]:*) warn "$KEEP_FILE: ignoring '$k': not a relative path"; continue ;; + esac + case "/$k/" in + //*|*/../*|*/./*|*//*|/.git/*|/.plastic/*) warn "$KEEP_FILE: ignoring '$k': not a relative path inside the worktree"; continue ;; + esac + KEEP+=("$k") + done <<<"$1" +} +lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; } +# keep_rel [fold]: exit 0 if is a kept path or inside one, 2 if a +# kept path is inside , 1 otherwise. fold compares without case. +keep_rel() { + local r="$1" k rc=1 + [ "${2:-}" = fold ] && r="$(lower "$r")" + for k in ${KEEP[@]+"${KEEP[@]}"}; do + [ "${2:-}" = fold ] && k="$(lower "$k")" + case "$r/" in "$k"/*) return 0 ;; esac + case "$k/" in "$r"/*) rc=2 ;; esac + done + return $rc +} +# The KEEP entries a clean would otherwise have removed: those that exist +# under and are, contain or sit inside one of the removal paths. +keep_matched() { # keep_matched [fold] + local k kf r rl="$2" + [ "${3:-}" = fold ] && rl="$(lower "$rl")" + for k in ${KEEP[@]+"${KEEP[@]}"}; do + [ -e "$1/$k" ] || [ -L "$1/$k" ] || continue + kf="$k"; [ "${3:-}" = fold ] && kf="$(lower "$k")" + while IFS= read -r r; do + [ -n "$r" ] || continue + case "$kf/" in "$r"/*) printf '%s\n' "$k"; break ;; esac + case "$r/" in "$kf"/*) printf '%s\n' "$k"; break ;; esac + done <<<"$rl" + done +} +keep_note() { # keep_note + [ -n "$KEPT" ] || return 0 + warn "kept from the snapshot ($KEEP_FILE): $(printf '%s' "$KEPT" | tr '\n' ' ')" + say " built from the snapshot's commit, which may not be $1's; delete them if they are stale" +} +keep_json() { + local k out="" + while IFS= read -r k; do [ -n "$k" ] && out="$out${out:+,}$(json_str "$k")"; done <<<"$KEPT" + printf '[%s]' "$out" +} + +# Delete under , except the kept paths inside it. +pl_prune() { # pl_prune [fold] + local c rc=0 + keep_rel "$2" "${3:-}" || rc=$? + case $rc in + 0) ;; + 2) if [ -d "$1/$2" ] && [ ! -L "$1/$2" ]; then + for c in "$1/$2"/* "$1/$2"/.[!.]* "$1/$2"/..?*; do + [ -e "$c" ] || [ -L "$c" ] || continue + pl_prune "$1" "$2/${c##*/}" "${3:-}" + done + else rm -rf -- "${1:?}/$2"; fi ;; + *) rm -rf -- "${1:?}/$2" ;; + esac +} +# git clean -xdf for a workspace: delete private and ignored items, except +# what a checked-in .uwt-keep lists. Only paths inside are +# touched, whatever cm prints. pl_clean() { # pl_clean - local code p - while IFS=$'\t' read -r code p; do - case "$p" in "$1"/*) rm -rf -- "$p" ;; esac - done < <(pl_status "$1" --private --ignored --cutignored) + local p list rels fold="" + case_insensitive "$1" && fold=fold + list="$(pl_status "$1" --private --ignored --cutignored)" + rels="$(printf '%s\n' "$list" | cut -f2- | while IFS= read -r p; do case "$p" in "$1"/*) printf '%s\n' "${p#"$1"/}" ;; esac; done)" + KEEP=(); KEPT="" + # A private .uwt-keep is the snapshot's, not the branch's. + if [ -f "$1/$KEEP_FILE" ] && ! printf '%s\n' "$rels" | grep -qxF -- "$KEEP_FILE"; then + keep_load "$(cat "$1/$KEEP_FILE")" + fi + while IFS= read -r p; do + [ -n "$p" ] && pl_prune "$1" "$p" "$fold" + done <<<"$rels" + # What was due for deletion and is still here: what was kept. + [ ${#KEEP[@]} -gt 0 ] && KEPT="$(keep_matched "$1" "$rels" "$fold")" + return 0 } # Content check for --verify: every controlled file's MD5 against the # server's for . cm decides "unchanged" from mtime and size alone, on @@ -916,7 +1085,7 @@ new_plastic() { # The clone is directory-level, so the snapshot's private files came too, # and a switch renames a private file in its way to .private.N. if [ "${OPT_INHERIT_UNTRACKED:-0}" = 1 ]; then warn "keeping private files inherited from the snapshot (--inherit-untracked)" - else pl_clean "$path"; fi + else pl_clean "$path"; keep_note "$branch"; fi hydrate_library "$gd" "$pdir" || rollback "Library clone failed" local secs=$(( $(now) - t0 )) @@ -929,7 +1098,7 @@ new_plastic() { esac local jpath="$path" jproj="$pdir" # in git's form: E:/x on Windows [ "$OS" = windows ] && { self="$(cygpath -m "$self")"; jpath="$(cygpath -m "$path")"; jproj="$(cygpath -m "$pdir")"; } - json_ok new "{\"path\":$(json_str "$jpath"),\"uwt\":$(json_str "$self"),\"project\":$(json_str "$jproj"),\"branch\":$(json_str "$branch"),\"head\":$(json_str "cs:$head"),\"seconds\":$secs,\"verified\":$([ "${OPT_VERIFY:-0}" = 1 ] && echo true || echo false),\"submodules_uninitialized\":0}" + json_ok new "{\"path\":$(json_str "$jpath"),\"uwt\":$(json_str "$self"),\"project\":$(json_str "$jproj"),\"branch\":$(json_str "$branch"),\"head\":$(json_str "cs:$head"),\"seconds\":$secs,\"verified\":$([ "${OPT_VERIFY:-0}" = 1 ] && echo true || echo false),\"submodules_uninitialized\":0,\"kept\":$(keep_json)}" exit $EXIT_OK } @@ -1069,8 +1238,23 @@ cmd_new() { good "content verified against a fresh index in $(( $(now) - vt ))s" fi # The clone is directory-level, so the snapshot's untracked files came too. + # Those .uwt-keep lists, as committed on the branch, stay: -x drops the + # standard ignore rules but still applies -e. if [ "${OPT_INHERIT_UNTRACKED:-0}" = 1 ]; then warn "keeping untracked files inherited from the snapshot (--inherit-untracked)" - else git -C "$path" clean -xdfq 2>/dev/null; fi + else + KEEP=(); KEPT="" + keep_load "$(git -C "$path" show "HEAD:$KEEP_FILE" 2>/dev/null)" + local keep_ex=() k gone="" + for k in ${KEEP[@]+"${KEEP[@]}"}; do keep_ex+=(-e "/$k"); done + [ ${#keep_ex[@]} -gt 0 ] && gone="$(git -C "$path" -c core.quotepath=false clean -xdn 2>/dev/null | sed -n 's#^Would remove \(.*\)$#\1#p' | sed 's#/$##')" + # The patterns are anchored with a leading /, which MSYS would rewrite to + # C:/Program Files/Git/... and so match nothing. With rewriting off a + # /e/... path would not reach git either, hence cd rather than -C. + (cd "$path" && MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' git clean -xdfq ${keep_ex[@]+"${keep_ex[@]}"} 2>/dev/null) + # What the clean would have removed and is still here: what was kept. + [ -n "$gone" ] && KEPT="$(keep_matched "$path" "$gone")" + keep_note "$branch" + fi local subs; subs="$(git -C "$path" ls-files -s | grep -c '^160000 ')" if [ "$subs" != 0 ]; then if [ "${OPT_INIT_SUBMODULES:-0}" = 1 ]; then @@ -1092,7 +1276,7 @@ cmd_new() { warn "the uwt skill is not committed, so the new worktree has no copy of it; commit $(skill_dir "$self")" fi [ "$OS" = windows ] && self="$(cygpath -m "$self")" - json_ok new "{\"path\":$(json_str "$reg"),\"uwt\":$(json_str "$self"),\"project\":$(json_str "$reg${pre:+/$pre}"),\"branch\":$(json_str "$branch"),\"head\":$(json_str "$(git -C "$path" rev-parse HEAD)"),\"seconds\":$secs,\"verified\":$([ "${OPT_VERIFY:-0}" = 1 ] && echo true || echo false),\"submodules_uninitialized\":$subs}" + json_ok new "{\"path\":$(json_str "$reg"),\"uwt\":$(json_str "$self"),\"project\":$(json_str "$reg${pre:+/$pre}"),\"branch\":$(json_str "$branch"),\"head\":$(json_str "$(git -C "$path" rev-parse HEAD)"),\"seconds\":$secs,\"verified\":$([ "${OPT_VERIFY:-0}" = 1 ] && echo true || echo false),\"submodules_uninitialized\":$subs,\"kept\":$(keep_json)}" exit $EXIT_OK } @@ -1304,7 +1488,9 @@ uwt - cheap Unity git worktrees (or Plastic workspaces) via copy-on-write uwt seed [PATH] [--force] snapshot the project + Library (editor CLOSED) uwt new BRANCH [--path DIR] [--base REF] [--inherit-untracked] [--init-submodules] [--verify] [--json] - git worktree add + clone the snapshot + hydrate + git worktree add + clone the snapshot + hydrate; + untracked files are cleaned except the paths + listed in a committed .uwt-keep uwt hydrate [PATH] [--force] [--json] give an existing worktree a Library from the golden; one that has a Library is left alone (exit 0) uwt list [PATH] [--json] the repo's worktrees and where each Library came from diff --git a/tests/README.md b/tests/README.md index 80b17a5..20d7f2c 100644 --- a/tests/README.md +++ b/tests/README.md @@ -23,16 +23,17 @@ Synthetic fixtures: a fake git repo shaped like a Unity project with a fake | 1 | `doctor` resolves the project from a subdirectory and reports state | | 2 | `seed` snapshots the tracked tree and `Library`, applies the deny list and the never-list, leaves the source alone, honours `--force`, rejects an empty `ArtifactDB`, keeps a dangling top-level symlink (Linux and macOS) | | 3 | the interlock refuses while a database is held open by another process (Linux and macOS) and while it is memory-mapped with the fd already closed, the way LMDB holds it (Linux; python3 builds the mapping); `doctor` names the open-file mechanism; a dead pid does not block. Windows needs a real editor, see below | -| 4 | `new` registers, clones, reconciles to the target branch (same-commit and cross-branch), cleans inherited untracked files, honours `--path`, `--base`, `--inherit-untracked`, checks out an existing branch, gives committed content for files the source hides behind `assume-unchanged`/`skip-worktree`, and refuses before registering when it cannot proceed | -| 5 | `hydrate` fills a plain worktree, refuses to overwrite without `--force`, warns on a Unity version mismatch; `--force` refuses (exit 3) when the project is opened while the replacement is being cloned (Linux and macOS) | +| 4 | `new` registers, clones, reconciles to the target branch (same-commit and cross-branch), cleans inherited untracked files except the paths a committed `.uwt-keep` lists (nested and ignored paths kept, their siblings cleaned, bad lines warned about, an untracked `.uwt-keep` ignored), honours `--path`, `--base`, `--inherit-untracked`, checks out an existing branch, gives committed content for files the source hides behind `assume-unchanged`/`skip-worktree`, and refuses before registering when it cannot proceed | +| 5 | `hydrate` fills a plain worktree, refuses to overwrite without `--force`, warns on a Unity version mismatch; `--force` refuses (exit 3) when the project is opened while the replacement is being cloned (Linux and macOS); on Windows a clone that robocopy turns into a byte copy (forced with `/NOCLONE`) fails `hydrate` and `new` with `clone_copied`, keeps the existing Library and rolls the worktree back | | 5b | `doctor`, `hydrate` and `list` report a `Library/` whose Bee player DAG or Burst cache manifest names another checkout, and pass one that names its own under any spelling (another case, a symlink, a Windows short name) or has none | -| 6 | CLI errors exit 2 | +| 5c | Windows, needs python: a file whose block has 2,000 references from inside it (built with `FSCTL_DUPLICATE_EXTENTS_TO_FILE`, the shape ReFS dedup leaves); after `seed`, `doctor` estimates two more worktrees, two clone and share, `doctor` then fails, and the third `new` fails with `clone_copied` and rolls back | +| 6 | CLI errors exit 2; the scripts are executable in a Linux or macOS checkout | | 7 | a project in a subdirectory of its repo: `seed` records the prefix, `new` clones back to it and leaves files outside it to git, `hydrate` given the worktree root finds the project | | 8 | `list` (text and `--json`) and where each `Library` came from; `remove` refuses the main worktree, a non-root path, a dirty worktree without `--force`, and a worktree whose `ArtifactDB` is open (exit 3), and keeps the branch, or with `--delete-branch` deletes it only when it has no commits of its own; `new --json` success and error records; `new --verify` rolls back a snapshot whose content changed behind matching stat data (which plain `new` lets through on Windows), runs its fresh-index pass only on Windows, and a configured `core.checkStat=minimal` does not weaken the check | | 9 | the case-collision detector (file and directory level) everywhere; through `new`, refusal on a case-folding volume (macOS CI) or success on a case-sensitive one | | 10 | submodules: `new` leaves them empty rather than cloning the source's `.git` link, the worktree is clean, the source is untouched; `--init-submodules` gives the worktree its own submodule repository | -| 11 | `measure` covers every worktree and the golden, a new 1 MiB file adds exactly 1 MiB private with no `sync`, the answer repeats; on ZFS, which has no physical extents to read, it refuses with exit 2 | -| 12 | Plastic: `doctor`, `seed` into `.plastic/uwt` (refuses a checkout, warns on local and hidden edits); `new` with a bare name, an existing branch, `--base` label and branch, its own workspace identity, a clean status, the source's edits and private files gone; refusals before anything is created (bad base, workspace name in use, `--init-submodules`); `--verify` rolls back a golden changed behind matching stat data, and refuses under `eolconversion.conf`; `hydrate` in a hand-made workspace; `list` (including a workspace that names the server differently), `measure`; `remove` refuses main, private files and checkouts, and `--force` undoes the checkout; `--delete-branch` deletes only a branch with no changesets that no other workspace is on; a partial (Gluon) workspace is refused; a project in a subdirectory, and removing a workspace whose main was deleted | +| 11 | `measure` covers every worktree and the golden, a new 1 MiB file adds exactly 1 MiB private with no `sync`, the answer repeats, a file reflinked within a tree is private once and the groups sum to the tree; on btrfs, compressed files (`chattr +c`) are reported as encoded extents, cost less than their logical size, no group exceeds its tree, and a reflink of them into another tree stays shared; 200 inline files of 100 bytes add exactly 20,000 bytes; a non-ASCII folder name comes back intact in UTF-8 `--json`; on ZFS, which has no physical extents to read, it refuses with exit 2; on Windows every tree reports `compressed`. Without cloning, on Windows (NTFS in CI): `measure.ps1` counts a file hardlinked into two trees as shared and each tree's own data as private, returns a non-ASCII folder name intact, skips a nested tree when both are given by 8.3 short names, and writes the same JSON and text under Windows PowerShell 5.1 and 7 | +| 12 | Plastic: `doctor`, `seed` into `.plastic/uwt` (refuses a checkout, warns on local and hidden edits); `new` with a bare name, an existing branch, `--base` label and branch, its own workspace identity, a clean status, the source's edits and private files gone, except what a checked-in `.uwt-keep` lists (inside a private directory too, and without case on a volume that folds it); refusals before anything is created (bad base, workspace name in use, `--init-submodules`); `--verify` rolls back a golden changed behind matching stat data, and refuses under `eolconversion.conf`; `hydrate` in a hand-made workspace; `list` (including a workspace that names the server differently), `measure`; `remove` refuses main, private files and checkouts, and `--force` undoes the checkout; `--delete-branch` deletes only a branch with no changesets that no other workspace is on; a partial (Gluon) workspace is refused; a project in a subdirectory, and removing a workspace whose main was deleted | Group 12 needs `cm` and a Plastic server, `local` by default (`UWT_TEST_PLASTIC_SERVER` to change it), and a volume that clones; otherwise @@ -51,9 +52,12 @@ from the server's machine, then set the client to name mode and CI has neither, so it runs locally only. CI also runs the suite on Linux on loopback btrfs, XFS (`reflink=1`) and ZFS -volumes, so every group runs on each filesystem `uwt` supports there. +volumes, so every group runs on each filesystem `uwt` supports there. On +Windows it runs on a ReFS VHDX twice: on Server 2025, where robocopy +block-clones, so every group runs; and on Server 2022, where it copies, so the +refusal paths run on ReFS. Both jobs fail if cloning is not what they expect. -On a volume that cannot block-clone (ubuntu and windows runners in CI) groups +On a volume that cannot block-clone (the default ubuntu and windows runners in CI) groups 2, 4 and 5 assert the refusal paths instead: exit 2, nothing published, nothing registered, no stray branch. Groups 7, 9 (through `new`) and 10 are skipped there. diff --git a/tests/run-tests.sh b/tests/run-tests.sh old mode 100644 new mode 100755 index 8c731bf..9fa5c9c --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -236,6 +236,37 @@ if [ $CLONES = 1 ]; then check "no bits carried into the worktree" bash -c "[ -z \"\$(git -C '$ROOT/wt-sw' ls-files -v | grep '^[a-zS] ')\" ]" git -C "$PROJ" update-index --no-skip-worktree README.md && git -C "$PROJ" update-index --no-assume-unchanged Assets/Scenes/A.unity git -C "$PROJ" checkout -q -- README.md Assets/Scenes/A.unity && uwt seed "$PROJ" --force >/dev/null 2>&1 + # .uwt-keep: a branch that commits one keeps those untracked paths from the + # snapshot (nested, ignored, beside a sibling that is cleaned); bad lines are + # warned about and skipped; a branch without one, or a .uwt-keep that is + # itself untracked in the snapshot, keeps nothing. + git -C "$PROJ" branch uwtkeep/off main && git -C "$PROJ" checkout -q -b uwtkeep/on main \ + && printf '# kept build output\nuwtkeep-out/a\r\n ./uwtkeep-ign/ \n../uwtkeep-escape\n/uwtkeep-abs\nuwtkeep-*\nuwtkeep-missing\n' > "$PROJ/.uwt-keep" \ + && git -C "$PROJ" add .uwt-keep && git -C "$PROJ" commit -qm keep && git -C "$PROJ" checkout -q main \ + && mkdir -p "$PROJ/uwtkeep-out/a" "$PROJ/uwtkeep-ign" && echo b > "$PROJ/uwtkeep-out/a/b.bin" && echo c > "$PROJ/uwtkeep-out/c.txt" \ + && echo x > "$PROJ/uwtkeep-ign/x" && echo /uwtkeep-ign/ >> "$PROJ/.git/info/exclude" && echo s > "$PROJ/uwtkeep-scratch.txt" \ + && printf 'uwtkeep-scratch.txt\nuwtkeep-out\n' > "$PROJ/.uwt-keep" && uwt seed "$PROJ" --force >/dev/null 2>&1 \ + || { echo "fixture: .uwt-keep setup failed"; exit 2; } + WK="$ROOT/wt-uwtkeep-on" + out="$(uwt new uwtkeep/on --path "$WK" --json 2>"$ROOT/uwtkeep-on.err")"; rc=$? + check ".uwt-keep: new exits 0" [ $rc = 0 ] + check ".uwt-keep: a listed path survives with what is below it" exists "$WK/uwtkeep-out/a/b.bin" + check ".uwt-keep: a listed ignored directory survives" exists "$WK/uwtkeep-ign/x" + check ".uwt-keep: an unlisted file beside a listed path is cleaned" absent "$WK/uwtkeep-out/c.txt" + check ".uwt-keep: unlisted untracked files are cleaned" absent "$WK/uwtkeep-scratch.txt" "$WK/scratch.txt" + check ".uwt-keep: '..', absolute and glob lines are warned about" \ + bash -c "grep -q \"ignoring '../uwtkeep-escape'\" '$ROOT/uwtkeep-on.err' && grep -q \"ignoring '/uwtkeep-abs'\" '$ROOT/uwtkeep-on.err' && grep -q \"ignoring 'uwtkeep-\\*': globs\" '$ROOT/uwtkeep-on.err'" + check ".uwt-keep: new names what it kept and that it may be stale" \ + bash -c "grep -q 'kept from the snapshot (.uwt-keep): uwtkeep-out/a uwtkeep-ign' '$ROOT/uwtkeep-on.err' && grep -q 'may not be uwtkeep/on' '$ROOT/uwtkeep-on.err'" + check ".uwt-keep: --json lists exactly the kept paths" json_is "d['value']['kept']==['uwtkeep-out/a','uwtkeep-ign']" <<<"$out" + WK0="$ROOT/wt-uwtkeep-off" + out="$(uwt new uwtkeep/off --path "$WK0" --json 2>/dev/null)"; rc=$? + check ".uwt-keep: without one committed, everything untracked is cleaned, an untracked .uwt-keep included" \ + bash -c "[ $rc = 0 ] && [ ! -e '$WK0/uwtkeep-out' ] && [ ! -e '$WK0/uwtkeep-ign' ] && [ ! -e '$WK0/uwtkeep-scratch.txt' ] && [ ! -e '$WK0/.uwt-keep' ]" + check ".uwt-keep: and --json reports nothing kept" json_is "d['value']['kept']==[]" <<<"$out" + git -C "$PROJ" worktree remove --force "$WK" >/dev/null 2>&1; git -C "$PROJ" worktree remove --force "$WK0" >/dev/null 2>&1 + rm -rf "$PROJ/uwtkeep-out" "$PROJ/uwtkeep-ign" "$PROJ/uwtkeep-scratch.txt" "$PROJ/.uwt-keep" "$ROOT/uwtkeep-on.err" + uwt seed "$PROJ" --force >/dev/null 2>&1 || { echo "fixture: re-seed after .uwt-keep failed"; exit 2; } else cd "$PROJ" out="$(uwt new feature/x 2>&1)"; rc=$? @@ -264,23 +295,40 @@ if [ $CLONES = 1 ]; then check "hydrate --force replaces" bash -c "echo junk > '$ROOT/plain/Library/JUNK'; bash '$UWT' hydrate '$ROOT/plain' --force >/dev/null 2>&1 && [ ! -e '$ROOT/plain/Library/JUNK' ]" # A --force that cannot finish must leave the Library it was replacing. The # failures are forced from PATH: a probe that finds no clone, then a clone - # that fails after the probe passed. + # that fails after the probe passed. On Windows also a clone that copies the + # bytes and reports success, which robocopy does when ReFS refuses to clone. echo mine > "$ROOT/plain/Library/MINE"; cp "$ROOT/plain/Library/ArtifactDB" "$ROOT/plain-adb" - SH="$ROOT/shim"; rm -rf "$SH"; mkdir -p "$SH/probe" "$SH/clone" + SH="$ROOT/shim"; rm -rf "$SH"; mkdir -p "$SH/probe" "$SH/clone" "$SH/copy" + hows="probe clone" if [ $WIN = 1 ]; then printf '#!/usr/bin/env bash\nexit 0\n' > "$SH/probe/fsutil" printf '#!/usr/bin/env bash\ncase "$*" in *.uwt-probe*) exec "%s" "$@" ;; esac\nexit 16\n' "$(command -v robocopy)" > "$SH/clone/robocopy" + printf '#!/usr/bin/env bash\ncase "$*" in *.uwt-probe*) exec "%s" "$@" ;; esac\nexec "%s" "$@" /NOCLONE\n' "$(command -v robocopy)" "$(command -v robocopy)" > "$SH/copy/robocopy" + hows="probe clone copy" else printf '#!/usr/bin/env bash\nexit 1\n' > "$SH/probe/cp" printf '#!/usr/bin/env bash\ncase "$*" in *.uwt-probe*) exec "%s" "$@" ;; esac\nexit 1\n' "$(command -v cp)" > "$SH/clone/cp" fi chmod +x "$SH"/*/* - for how in probe clone; do + for how in $hows; do PATH="$SH/$how:$PATH" uwt hydrate "$ROOT/plain" --force >/dev/null 2>&1; rc=$? check "hydrate --force with a failing $how exits 2" [ $rc = 2 ] check "and leaves the existing Library byte-identical" bash -c "cmp -s '$ROOT/plain/Library/ArtifactDB' '$ROOT/plain-adb' && [ -f '$ROOT/plain/Library/MINE' ]" check "and leaves no staging directory" absent "$ROOT/plain/Library.uwt-new" "$ROOT/plain/Library.uwt-old" done + if [ $WIN = 1 ]; then + out="$(PATH="$SH/copy:$PATH" uwt hydrate "$ROOT/plain" --force --json 2>"$ROOT/copy.err")" + check "a clone that copied is reason clone_copied" json_is "d['status']=='error' and d['exit']==2 and d['reason']=='clone_copied'" <<<"$out" + check "and names the copied files" grep -q 'ArtifactDB' "$ROOT/copy.err" + out="$(cd "$PROJ" && PATH="$SH/copy:$PATH" bash "$UWT" new copied/x --path "$ROOT/wt-copied" --json 2>/dev/null)"; rc=$? + check "new whose Library clone copied exits 2 with reason clone_copied" \ + bash -c "[ $rc = 2 ] && grep -q '\"reason\":\"clone_copied\"' <<<'$out'" + check "and rolls back the worktree and its branch" \ + bash -c "[ ! -e '$ROOT/wt-copied' ] && ! git -C '$PROJ' rev-parse --verify --quiet refs/heads/copied/x >/dev/null" + rm -f "$ROOT/copy.err" + else + skip "a clone that copies and reports success (Windows only: the check reads robocopy's log)" + fi # An editor that opens the project while the replacement is being cloned is # caught before the swap. Forced the same way: the real cp, then an fd held # open on the existing ArtifactDB. Not on Windows, for the reason group 3 gives. @@ -350,12 +398,66 @@ rm -rf "$FB/Library/Bee" "$FB/Library/BurstCache" check "a Library with no player-build state says so" bash -c "bash '$UWT' doctor '$FB' 2>&1 | grep -q 'no player-build state'" check "and is not flagged" fb_row False +# ------------------------------------------------------------------ 5c. ReFS reference limit +# ReFS refuses to clone a block past 8,176 references and robocopy then copies +# the file, reporting success. ReFS dedup gets there by folding repeated +# blocks inside a file; the fixture does the same with block clones inside +# one file: 2,000 unique clusters, then 2,000 that all map one block. Source +# and golden put that block at 4,000 references, so two worktrees fit and the +# third would take it past the limit. +group "5c. ReFS reference limit" +if [ $WIN = 1 ] && [ $CLONES = 1 ] && [ -n "$PY" ]; then + RP="$ROOT/refs-proj"; rm -rf "$RP" "$ROOT"/refs-wt-* + mkdir -p "$RP/ProjectSettings" "$RP/Assets" "$RP/Library/DataStore" && cd "$RP" && git init -q -b refs-main \ + && git config user.email t@t && git config user.name t && git config core.autocrlf false \ + && printf 'm_EditorVersion: 6000.7.0b1\n' > ProjectSettings/ProjectVersion.txt && echo a > Assets/a.txt \ + && printf '/Library/\n' > .gitignore && git add -A && git commit -qm init \ + && head -c 300000 /dev/urandom > Library/ArtifactDB && head -c 100000 /dev/urandom > Library/DataStore/uds.db \ + && "$PY" -c 'import ctypes, os, sys +from ctypes import wintypes as W +path, uniq, dup, CL = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), 4096 +with open(path, "wb") as f: + f.write(os.urandom((uniq + 1) * CL)); f.truncate((uniq + dup) * CL) +k32 = ctypes.WinDLL("kernel32", use_last_error=True); k32.CreateFileW.restype = W.HANDLE +class D(ctypes.Structure): + _fields_ = [("h", W.HANDLE), ("src", ctypes.c_longlong), ("dst", ctypes.c_longlong), ("n", ctypes.c_longlong)] +h = k32.CreateFileW(path, 0xC0000000, 7, None, 3, 0, None) +have = 1 +while have < dup: + c = min(have, dup - have); d = D(h, uniq * CL, (uniq + have) * CL, c * CL); got = W.DWORD() + if not k32.DeviceIoControl(h, 0x00098344, ctypes.byref(d), ctypes.sizeof(d), None, 0, ctypes.byref(got), None): + sys.exit("FSCTL_DUPLICATE_EXTENTS_TO_FILE failed: %d" % ctypes.get_last_error()) + have += c +k32.CloseHandle(h)' "$(cygpath -w "$RP/Library/DataStore/UDSData_0.bin")" 2000 2000 \ + && uwt seed "$RP" >/dev/null 2>&1 \ + || { echo "fixture: reference-limit project setup failed"; exit 2; } + check "the fixture block has 4,000 references after seed" \ + bash -c "fsutil file queryExtentsAndRefCounts '$(cygpath -w "$RP/Library/DataStore/UDSData_0.bin")' | grep -qi 'Ref: 0xfa0'" + out="$(uwt doctor "$RP" 2>&1)" + check "doctor estimates room for two more worktrees" grep -q 'room for about 2 more worktree(s) before Library/DataStore/UDSData_0.bin' <<<"$out" + check "two worktrees clone" bash -c "cd '$RP' && bash '$UWT' new rlim/a --path '$ROOT/refs-wt-a' >/dev/null 2>&1 && bash '$UWT' new rlim/b --path '$ROOT/refs-wt-b' >/dev/null 2>&1" + check "and share the block" shares_blocks "$ROOT/refs-wt-b/Library/DataStore/UDSData_0.bin" + uwt doctor "$RP" >"$ROOT/refs-doctor.log" 2>&1; rc=$? + check "doctor then fails: the file is at the limit" bash -c "[ $rc = 2 ] && grep -q 'UDSData_0.bin is at the limit' '$ROOT/refs-doctor.log'" + out="$(cd "$RP" && bash "$UWT" new rlim/c --path "$ROOT/refs-wt-c" --json 2>/dev/null)"; rc=$? + check "the third new fails with clone_copied" bash -c "[ $rc = 2 ] && grep -q '\"reason\":\"clone_copied\"' <<<'$out'" + check "and is rolled back" bash -c "[ ! -e '$ROOT/refs-wt-c' ] && ! git -C '$RP' rev-parse --verify --quiet refs/heads/rlim/c >/dev/null" + cd "$PROJ" && rm -rf "$RP" "$ROOT"/refs-wt-* "$ROOT/refs-doctor.log" +elif [ $WIN = 0 ]; then skip "ReFS reference limit (Windows only)" +elif [ $CLONES = 0 ]; then skip "ReFS reference limit (this volume cannot block-clone)" +else skip "ReFS reference limit (needs python to build the fixture)"; fi + # ------------------------------------------------------------------ 6. cli group "6. cli" check "unknown command exits 2" bash -c "bash '$UWT' frob >/dev/null 2>&1; [ \$? = 2 ]" check "unknown option exits 2" bash -c "bash '$UWT' doctor --bogus >/dev/null 2>&1; [ \$? = 2 ]" check "help exits 0" bash -c "bash '$UWT' help >/dev/null 2>&1" check "new without a branch exits 2" bash -c "cd '$PROJ' && bash '$UWT' new >/dev/null 2>&1; [ \$? = 2 ]" +# The mode git records is what a Linux or macOS checkout gets. Git Bash treats +# any file with a shebang as executable, so this can only fail off Windows. +for exe in "$UWT" "$(dirname "$UWT")/measure.py" "$HERE/run-tests.sh"; do + check "$(basename "$exe") is executable" [ -x "$exe" ] +done # ------------------------------------------------------------------ 7. subdirectory project # A Unity project that is a subdirectory of its repo (a monorepo). The golden @@ -580,10 +682,120 @@ else for i in range(256): open(os.path.join(sys.argv[1], "burst%d.bin" % i), "wb").write(os.urandom(1048576))' "$ROOT/wt-m" p2="$(priv)" check "a 256 MiB burst measured at once adds exactly 256 MiB" [ "$(( p2 - p1 ))" = 268435456 ] + # mval [path]: one number from measure --json, + # which must be UTF-8 (Python's stdin would decode it as the ANSI code page). + mval() { bash "$UWT" measure "${2:-$ROOT/wt-m}" --json 2>/dev/null | "$PY" -c 'import json,sys; t=[t for t in json.loads(sys.stdin.buffer.read().decode("utf-8"))["value"]["trees"] if t["reported"]][0]; print(eval(sys.argv[1]))' "$1"; } + gsum='sum(g["private"] for g in t["groups"].values()) == t["private"]' + # A reflink inside one tree: two files map the same blocks, which are private + # once, so the groups must not count them twice. + mkdir -p "$ROOT/wt-m/dup" + if cp --reflink=always "$ROOT/wt-m/new.bin" "$ROOT/wt-m/dup/new.bin" 2>/dev/null; then + check "a file reflinked within a tree is private once" [ "$(priv)" = "$p2" ] + check "and the groups still sum to the tree's private" [ "$(mval "$gsum")" = True ] + else + skip "reflink within a tree (cp --reflink=always is GNU coreutils)" + fi + if [ "$FSTYPE" = btrfs ] && mkdir -p "$ROOT/wt-m/cmp" && chattr +c "$ROOT/wt-m/cmp" 2>/dev/null; then + # Compressed extents: FIEMAP gives the uncompressed length from the + # compressed start, so neighbouring ranges overlap unless measure + # estimates their size on disk. + p3="$(priv)" + "$PY" -c 'import os,sys +for i in range(32): open(os.path.join(sys.argv[1], "c%d.txt" % i), "w").write(("compressible line %d\n" % i) * 50000)' "$ROOT/wt-m/cmp" + lc="$(du -sb --apparent-size "$ROOT/wt-m/cmp" | cut -f1)"; p4="$(priv)" + check "compressed files are reported as encoded extents" [ "$(mval 't.get("encoded_extents", 0) > 0')" = True ] + check "and add private disk, less than their logical size" [ "$(( p4 - p3 ))" -gt 0 -a "$(( p4 - p3 ))" -lt "$lc" ] + check "no group is larger than its tree" [ "$(mval 'all(g["private"] <= t["private"] for g in t["groups"].values())')" = True ] + check "and the groups sum to the tree's private" [ "$(mval "$gsum")" = True ] + # The same compressed extents reflinked into another tree are shared. + mp="$(mval 't["private"]' "$PROJ")" + cp -r --reflink=always "$ROOT/wt-m/cmp" "$PROJ/cmp-copy" + check "compressed extents reflinked into another tree stay shared" [ "$(( $(mval 't["private"]' "$PROJ") - mp ))" -le "$(( 32 * 4096 ))" ] + rm -rf "$PROJ/cmp-copy" + else + skip "compressed extents (needs btrfs and chattr +c)" + fi + if [ "$FSTYPE" = btrfs ]; then + # btrfs keeps files this small inside its metadata: they cost their size, + # not a block each. + p5="$(priv)"; i5="$(mval 't["inline_files"]')"; mkdir -p "$ROOT/wt-m/inl" + "$PY" -c 'import os,sys +for i in range(200): open(os.path.join(sys.argv[1], "i%d.txt" % i), "wb").write(b"x" * 100)' "$ROOT/wt-m/inl" + check "200 inline files of 100 bytes add 200 inline files" [ "$(( $(mval 't["inline_files"]') - i5 ))" = 200 ] + check "and exactly 20,000 bytes private" [ "$(( $(priv) - p5 ))" = 20000 ] + else + skip "inline files (needs btrfs)" + fi + # Windows writes stdout in the console's code page (437, 1252) unless told + # otherwise, which turns these into other bytes or '?'. + "$PY" -c 'import os,sys +d = os.path.join(sys.argv[1], "\u00fcn\u00ef-\u65e5\u672c"); os.makedirs(d, exist_ok=True) +open(os.path.join(d, "u.bin"), "wb").write(os.urandom(65536))' "$ROOT/wt-m" + check "a non-ASCII folder name comes back intact in --json" [ "$(mval '"\u00fcn\u00ef-\u65e5\u672c" in t["groups"]')" = True ] else skip "measure deltas (needs python)" fi check "measure of a path outside the repo exits 2" bash -c "cd '$PROJ' && bash '$UWT' measure '$ROOT' >/dev/null 2>&1; [ \$? = 2 ]" + if [ $WIN = 1 ]; then + check "measure reports compressed bytes per tree" json_is 'all(isinstance(t.get("compressed"), int) for t in d["value"]["trees"])' <<<"$out" + fi +fi + +# measure.ps1 on its own needs no cloning: NTFS has physical clusters too, and +# a file hardlinked into two trees shares them. So this part runs on CI's NTFS. +if [ $WIN = 1 ]; then + if [ -z "$PY" ]; then + skip "measure.ps1 on plain trees (needs python)" + else + MS="$ROOT/measure-ps1"; rm -rf "$MS" + # a: 3 MiB hardlinked into b, 1 MiB of its own in a non-ASCII folder, an + # empty file. b: the link and 2 MiB of its own. Random data, not copies: a + # Dev Drive may clone a copy. Written just now, so measure must flush. + "$PY" -c 'import os,sys +a, b = (os.path.join(sys.argv[1], n) for n in "ab"); u = os.path.join(a, "\u00fcn\u00ef-\u65e5\u672c") +for d in (b, u, os.path.join(a, "big")): os.makedirs(d) +open(os.path.join(a, "big", "shared.bin"), "wb").write(os.urandom(3 << 20)) +os.link(os.path.join(a, "big", "shared.bin"), os.path.join(b, "shared.bin")) +open(os.path.join(u, "own.bin"), "wb").write(os.urandom(1 << 20)); open(os.path.join(a, "empty"), "wb").close() +open(os.path.join(b, "own.bin"), "wb").write(os.urandom(2 << 20))' "$(cygpath -w "$MS")" + ps51="$(command -v powershell || true)"; ps7="$(command -v pwsh || true)" + # mps [args]: measure.ps1 over the two trees. + mps() { MSYS2_ARG_CONV_EXCL='*' "$1" -NoProfile -ExecutionPolicy Bypass -File "$(cygpath -w "$(dirname "$UWT")/measure.ps1")" "${@:2}" "a=$(cygpath -w "$MS/a")" "b=$(cygpath -w "$MS/b")" 2>/dev/null; } + # msj : from measure.ps1 -Json, read as UTF-8. + msj() { "$PY" -c 'import json,sys +d = json.loads(open(sys.argv[1], "rb").read().decode("utf-8")); t = {x["name"]: x for x in d["trees"]}; a, b = t["a"], t["b"] +sys.exit(0 if eval(sys.argv[2]) else 1)' "$(cygpath -w "$1")" "$2"; } + # uwt prefers pwsh; a stock Windows has only Windows PowerShell 5.1. + psx="${ps7:-$ps51}" + if [ -z "$psx" ]; then + skip "measure.ps1 on plain trees (no PowerShell on PATH)" + else + mps "$psx" -Json > "$MS/m.json" + check "measure.ps1: a file hardlinked into both trees is shared" msj "$MS/m.json" 'a["shared"] == b["shared"] == 3 << 20' + check "and each tree's own data is private" msj "$MS/m.json" 'a["private"] == 1 << 20 and b["private"] == 2 << 20' + check "a non-ASCII folder name comes back intact, in UTF-8" msj "$MS/m.json" 'a["groups"]["\u00fcn\u00ef-\u65e5\u672c"]["private"] == 1 << 20' + # A tree nested in another (the golden under .git), both given by 8.3 + # short names: .NET expands those, so roots taken as given would not + # match their own files and the nested tree would be counted twice. + mkdir -p "$MS/n/main/.git/g" + head -c 1048576 /dev/urandom > "$MS/n/main/own.bin"; head -c 2097152 /dev/urandom > "$MS/n/main/.git/g/lib.bin" + MSYS2_ARG_CONV_EXCL='*' "$psx" -NoProfile -ExecutionPolicy Bypass -File "$(cygpath -w "$(dirname "$UWT")/measure.ps1")" -Json \ + "a=$(cygpath -d "$MS/n/main")" "b=$(cygpath -d "$MS/n/main/.git/g")" > "$MS/n.json" 2>/dev/null + check "a nested tree given by short names is not counted twice" msj "$MS/n.json" 'a["logical"] == 1 << 20 and b["private"] == 2 << 20 and list(a["groups"]) == ["."]' + fi + if [ -z "$ps51" ] || [ -z "$ps7" ]; then + skip "measure.ps1 under 5.1 and 7 compared (needs powershell.exe and pwsh)" + else + # A difference between the two fails silently: same output or a bug. + mps "$ps51" -Json > "$MS/m51.json"; mps "$ps7" -Json > "$MS/m7.json" + check "Windows PowerShell 5.1 and 7 write the same --json" "$PY" -c 'import json,sys +a, b = (json.loads(open(f, "rb").read().decode("utf-8")) for f in sys.argv[1:]) +for d in (a, b): d["seconds"] = 0 +sys.exit(a != b)' "$(cygpath -w "$MS/m51.json")" "$(cygpath -w "$MS/m7.json")" + nosecs() { mps "$@" | sed -E 's/, [0-9.,]+ s,/,/'; } + check "and the same text" [ "$(nosecs "$ps51")" = "$(nosecs "$ps7")" ] + fi + fi fi # ------------------------------------------------------------------ 12. plastic @@ -726,6 +938,31 @@ else check "and names the file" grep -q 'eolconversion.conf' <<<"$out" rm -f "$PM/eolconversion.conf" + # .uwt-keep checked in on the branch: listed private paths survive, even + # inside a private directory cm reports whole, and match without case where + # the volume folds it. Deleted again so the counts below hold. + (cd "$PM" && pcm branch create "br:/main/uwtkeep@$PR" >/dev/null 2>&1 && pcm switch br:/main/uwtkeep --noinput >/dev/null 2>&1 \ + && printf 'uwtkeep-out/a\nuwtkeep-case\n' > .uwt-keep && pcm add .uwt-keep >/dev/null 2>&1 && pcm checkin -c keep >/dev/null 2>&1 \ + && pcm switch br:/main --noinput >/dev/null 2>&1 && [ ! -e .uwt-keep ] \ + && mkdir -p uwtkeep-out/a UwtKeep-Case && echo b > uwtkeep-out/a/b.bin && echo c > uwtkeep-out/c.txt && echo x > UwtKeep-Case/x) \ + && uwt seed "$PM" --force >/dev/null 2>&1 || { echo "fixture: plastic .uwt-keep setup failed"; exit 2; } + : > "$ROOT/uwtCaseProbe"; [ -e "$ROOT/UWTCASEPROBE" ] && folds=1 || folds=0; rm -f "$ROOT/uwtCaseProbe" + PK="$ROOT/uwtp-keep" + out="$(uwt new /main/uwtkeep --path "$PK" --json 2>/dev/null)"; rc=$? + check ".uwt-keep: new exits 0" [ $rc = 0 ] + check ".uwt-keep: a listed private path survives with what is below it" exists "$PK/uwtkeep-out/a/b.bin" + check ".uwt-keep: an unlisted file beside it, and other private files, are cleaned" absent "$PK/uwtkeep-out/c.txt" "$PK/scratch.txt" + if [ $folds = 1 ]; then + check ".uwt-keep: matches without case on a volume that folds it" exists "$PK/UwtKeep-Case/x" + check ".uwt-keep: --json lists the kept paths" json_is "d['value']['kept']==['uwtkeep-out/a','uwtkeep-case']" <<<"$out" + else + check ".uwt-keep: matches case exactly on a case-sensitive volume" absent "$PK/UwtKeep-Case" + check ".uwt-keep: --json lists the kept paths" json_is "d['value']['kept']==['uwtkeep-out/a']" <<<"$out" + fi + check ".uwt-keep: cm status is clean" [ "$(pstat "$PK")" = 0 ] + pcm workspace delete "$(pwp "$PK")" >/dev/null 2>&1; rm -rf "$PK" "$PM/uwtkeep-out" "$PM/UwtKeep-Case" + uwt seed "$PM" --force >/dev/null 2>&1 || { echo "fixture: plastic re-seed after .uwt-keep failed"; exit 2; } + # A workspace made by hand finds the golden through the repo's workspaces. pcm workspace create uwtp-hand "$(pwp "$ROOT/uwtp-hand")" "$PR" >/dev/null 2>&1 pcm update "$(pwp "$ROOT/uwtp-hand")" >/dev/null 2>&1