Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

fix: Windows lock contention was rethrown, not treated as busy (#105)

Matthew Kissingere23e0c670bd9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db069233..5f461b70 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,33 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## The Windows failure was a real bug in the alias lock — 2026-09-12
+
+- `rejects lost updates from eight independent processes` went red once on a Windows
+ runner. The first read of it here was wrong, and the number that refutes it was in the
+ log all along: **the test failed in 123 ms**, while both hang guards are 10 and 15
+ seconds away. Nothing was slow. A worker died, fast.
+- The only way `compareAndSet` does that is the `throw error` beside its lock, reached
+ whenever `mkdir` reports contention with a code other than `EEXIST`. **Windows has
+ exactly that case**: directory deletion is not synchronous, so a directory whose last
+ handle has not closed sits in pending-delete, where `mkdir` on that name answers `EPERM`
+ or `EACCES`. Every release runs `rmdir` in a `finally`, so with eight processes
+ contending, one landing in that window is ordinary contention — and it was rethrown.
+- `isLockContention` now recognises those two codes **on Windows only**. Widening it to
+ every platform would be the over-fix: on POSIX, `EPERM`/`EACCES` from `mkdir` means the
+ parent directory is not writable, and swallowing that would report a permission fault as
+ "busy". Both mistakes are pinned by tests — reverting to `EEXIST`-only fails the Windows
+ case, over-widening fails the POSIX guard.
+- Lock release stopped being able to decide the call's outcome. `rmdir` has no `force`, and
+ on Windows it can fail while a scanner holds the directory — which inside a `finally`
+ would replace a precise `Alias conflict` with an unrelated errno, or turn a successful
+ write into a failure. Cleanup failures are now swallowed, and a lingering lock degrades
+ to "busy" rather than corrupting anything.
+- Asserted on the decision rather than through a real Windows filesystem, so a Linux host
+ checks every branch and the platform is a parameter. The worker timings added alongside
+ are what made the failure legible in the first place, and they stay: one `FAILED` beside
+ seven fast children points at the code, where all eight slow points at the host.
+
## `--receipt` was relative to the wrong directory — 2026-09-12
- `scripts/verify-package-receipt.mjs` resolved `--receipt` against `--root` rather than the
diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
index a7cec2b1..ceaf431d 100644
--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md
+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
@@ -2090,6 +2090,8 @@ re-measured since the day it was written.
| 15.5 | Linux and Windows package receipts had no reproducible source | **Done 2026-09-12.** Four receipts from one CI run; the check extracted. See below |
| 15.6 | `webgpu` 0.6.0 to 0.6.1 in `render-service/` | **Deferred 2026-09-12, and the reason is its publish date.** Gated on the owner's GPU smoke. See below |
| 15.7 | `--receipt` resolved against `root`, not the working directory | **Done 2026-09-12.** Found by assembling the release. See below |
+| 15.8 | `v0.7.0` released | **Done 2026-09-12.** Tag `v0.7.0` at `44b4bc8`; four receipts and `SHA256SUMS.txt` from one CI run, each verified against the published tarball |
+| 15.9 | The Windows failure was a real bug in the alias lock, not a flake | **Found and fixed 2026-09-12.** `mkdir` contention on Windows reports `EPERM`/`EACCES`, which was rethrown. See below |
### 15.1 -- the tag is the whole rewrite, on the clone side too
@@ -2373,3 +2375,71 @@ Worth pairing with 15.3, which was the same shape in a different medium: there a
assertion read the whole file when it needed to read one block, and the prose in the same
commit kept it green. Here a fixture collapsed two directories that had to stay apart.
Both times the assertion was true and measured nothing.
+
+
+### 15.8 -- what 0.7.0 attests to
+
+Tag `v0.7.0` at `44b4bc8`, published with `kiln-engine-0.7.0.tgz`, four platform receipts
+and `SHA256SUMS.txt`. The property worth naming is that all five assets come from **one**
+CI run: the tarball is the artifact that run built, and each receipt is that same run's
+smoke on its own platform. Before publication every receipt was verified against the
+published file -- four platforms, one `tarballSha256`,
+`cf3491064ed139898977bbcb6cfeccd430444c3a492dc834e9d1e51793202b17`, and all four agreeing
+`engineVersion: 0.7.0`.
+
+That chain is what 15.4 and 15.5 were for, and it only closed because 15.7's bug was
+caught by a script that refused rather than warned. A release assembled by hand would
+have had no step at which four receipts and one tarball were required to agree.
+
+### 15.9 -- the number that was in the log the whole time
+
+`rejects lost updates from eight independent processes` went red once on a Windows runner,
+on a pull request whose diff could not reach it. The first reading here was that it was a
+timing flake, with two candidate causes -- runner startup contention or a stall in
+`rename`/`rmdir` -- and a note that neither could be told apart from a Linux host. **That
+was wrong, and the datum refuting it was already captured:**
+
+```
+(fail) rejects lost updates from eight independent processes [123.61ms]
+```
+
+123ms. Both hang guards are 10 and 15 seconds away. Nothing was slow, nothing was killed,
+and every explanation resting on elapsed time was dead on arrival. Ten green `main` runs
+and a green rerun made "flake" the comfortable conclusion, and the duration beside the
+failure was the thing that should have been read first.
+
+A worker died fast, and `compareAndSet` has exactly one way to do that: the `throw error`
+beside its lock, reached whenever `mkdir` reports contention with a code other than
+`EEXIST`.
+
+**Windows has exactly that case.** Directory deletion there is not synchronous: a directory
+whose last handle has not closed sits in a pending-delete state, and `mkdir` on that name
+fails with `EPERM` or `EACCES` rather than `EEXIST`. Every release in this file runs
+`rmdir(lock)` inside a `finally`, so with eight processes contending on one lock, a
+process arriving in that window is ordinary contention -- and the code rethrew it, exiting
+the worker non-zero with a stack trace the parent reported as `Worker failed:` and an
+empty stderr.
+
+Two changes, and the second matters as much as the first:
+
+- `isLockContention` recognises `EPERM` and `EACCES` **on Windows only**. Widening it to
+ every platform is the over-fix: on POSIX those codes from `mkdir` mean the parent
+ directory is not writable, and swallowing them would report a real permission fault as
+ "busy". Both mistakes are pinned -- reverting to `EEXIST`-only fails the Windows case,
+ over-widening fails the POSIX guard.
+- Lock release can no longer decide what the call throws. `rmdir` has no `force`, and on
+ Windows it can fail while a scanner holds the directory; inside a `finally` that would
+ replace a precise `Alias conflict` with an unrelated errno, or turn a successful write
+ into a failure. Cleanup failures are swallowed now, and a lingering lock degrades to
+ "busy" because `isLockContention` treats it that way.
+
+Verified on Linux, because the decision was the defect and a predicate taking `platform`
+as a parameter has every branch reachable from anywhere. That is the general point: this
+looked like it needed a Windows host, and it needed the error-code decision extracted far
+enough to test.
+
+**The lesson is the diagnosis, not the fix.** "Intermittent on one platform, green on
+rerun, ten green runs behind it" is a description that fits both a flake and a real race,
+and the reflex was to treat the frequency as the diagnosis. The distinguishing evidence
+cost nothing to read. This sits alongside 15.3 and 15.7: there an assertion was true and
+measured nothing; here an explanation was plausible and measured nothing.
diff --git a/scripts/experiment-program-aliases.ts b/scripts/experiment-program-aliases.ts
index e833d349..9c0983e3 100644
--- a/scripts/experiment-program-aliases.ts
+++ b/scripts/experiment-program-aliases.ts
@@ -29,12 +29,28 @@ if (process.argv[2] === '--child') {
['original', 'candidate-a', 'candidate-b'].map((code) => store.put(code)),
);
await aliases.compareAndSet('bridge', null, refs[0]!);
+ // A child was killed here once on a Windows runner, reported as `Worker failed:` with
+ // an empty stderr, which said nothing about why. The timings below exist because that
+ // message could not distinguish a slow child from a dead one -- and the distinction
+ // turned out to matter: the failing test took 123ms, so nothing was slow at all. The
+ // cause was the lock's error handling, fixed in `isLockContention`.
+ //
+ // Kept anyway, because the per-child comparison is what made that readable. All eight
+ // over the guard means the host is contended; one FAILED beside seven fast children
+ // means a worker died, which points at the code rather than the runner. The receipt
+ // also carries the slowest child on success, so a run at 60ms and a run at 9,000ms
+ // stop looking identical while both pass.
+ const spawnedAt = performance.now();
const children = Array.from({ length: 8 }, (_, i) => {
const child = Bun.spawn(
[process.execPath, import.meta.path, '--child', directory, refs[0]!, refs[1 + (i % 2)]!],
{ stdout: 'pipe', stderr: 'pipe' },
);
- const timer = setTimeout(() => child.kill(), 10000);
+ let killedAfterMs: number | undefined;
+ const timer = setTimeout(() => {
+ killedAfterMs = Math.round(performance.now() - spawnedAt);
+ child.kill();
+ }, 10000);
return (async () => {
try {
const [code, stdout, stderr] = await Promise.all([
@@ -42,14 +58,38 @@ if (process.argv[2] === '--child') {
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
- if (code !== 0) throw new Error(`Worker failed: ${stderr}`);
- return JSON.parse(stdout) as { status: string };
+ const elapsedMs = Math.round(performance.now() - spawnedAt);
+ if (code !== 0) {
+ const how =
+ killedAfterMs === undefined
+ ? `exited ${code} after ${elapsedMs}ms`
+ : `killed by the hang guard after ${killedAfterMs}ms`;
+ throw new Error(`Worker ${i} ${how}: ${stderr.trim() || '(no stderr)'}`);
+ }
+ return { ...(JSON.parse(stdout) as { status: string }), elapsedMs };
} finally {
clearTimeout(timer);
}
})();
});
- const results = await Promise.all(children);
+ const settled = await Promise.allSettled(children);
+ // Every child's timing, including the healthy ones, because "one slow among seven
+ // fast" and "all eight slow" are different diagnoses and only the comparison shows
+ // which. Reported on the failure path, where it is the whole point.
+ const failures = settled.filter((r) => r.status === 'rejected');
+ if (failures.length > 0) {
+ const timings = settled
+ .map((r, i) => (r.status === 'fulfilled' ? `${i}:${r.value.elapsedMs}ms` : `${i}:FAILED`))
+ .join(' ');
+ throw new Error(
+ `${failures.length} of 8 workers failed [${timings}]\n` +
+ failures.map((r) => ` ${(r.reason as Error).message}`).join('\n'),
+ );
+ }
+ const results = settled.map(
+ (r) => (r as PromiseFulfilledResult<{ status: string; elapsedMs: number }>).value,
+ );
+ const slowestMs = Math.max(...results.map((r) => r.elapsedMs));
const updated = results.filter((result) => result.status === 'updated').length;
if (updated !== 1) throw new Error(`Expected one winner, received ${updated}`);
const finalRef = await aliases.resolve('bridge');
@@ -65,6 +105,9 @@ if (process.argv[2] === '--child') {
const receipt = {
experiment: 'R0 project-local alias compare-and-set',
processes: 8,
+ // Headroom against the 10s hang guard, recorded on success too: a receipt showing
+ // 90ms and one showing 9000ms both pass, and only this number tells them apart.
+ slowestWorkerMs: slowestMs,
updated,
rejected: 7,
rejectionKinds: [
diff --git a/src/__tests__/program-aliases.test.ts b/src/__tests__/program-aliases.test.ts
index 42336254..a51dd12e 100644
--- a/src/__tests__/program-aliases.test.ts
+++ b/src/__tests__/program-aliases.test.ts
@@ -1,9 +1,9 @@
-import { expect, it } from 'bun:test';
+import { describe, expect, it } from 'bun:test';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { FileProgramStore } from '../program-store-node';
-import { ExperimentalProgramAliases } from '../experiments/program-aliases';
+import { ExperimentalProgramAliases, isLockContention } from '../experiments/program-aliases';
it('requires explicit CAS, preserves immutable source, and rejects collisions and corrupt aliases', async () => {
const directory = await mkdtemp(join(tmpdir(), 'kiln-alias-test-'));
@@ -35,6 +35,52 @@ it('requires explicit CAS, preserves immutable source, and rejects collisions an
}
});
+// The Windows red on 2026-09-12 failed in 123ms, which is what rules out every timing
+// explanation: both hang guards are seconds away. A worker died, fast, and the only way
+// `compareAndSet` does that is the `throw error` beside the lock -- reached whenever
+// `mkdir` reports contention with a code other than `EEXIST`.
+//
+// Windows has exactly that case. Directory deletion is not synchronous there, so a
+// directory whose last handle has not closed sits in pending-delete, and `mkdir` on that
+// name answers `EPERM` or `EACCES`. Every release runs `rmdir` in a `finally`, so with
+// eight processes contending, one landing in that window is ordinary contention.
+//
+// Asserted on the predicate rather than through a real Windows filesystem, because the
+// decision is what was wrong and a Linux host can check every branch of it. The platform
+// is a parameter for the same reason.
+describe('lock contention is recognised per platform', () => {
+ const err = (code: string) => Object.assign(new Error(code), { code });
+
+ it('treats EEXIST as contention everywhere', () => {
+ expect(isLockContention(err('EEXIST'), 'linux')).toBe(true);
+ expect(isLockContention(err('EEXIST'), 'win32')).toBe(true);
+ expect(isLockContention(err('EEXIST'), 'darwin')).toBe(true);
+ });
+
+ // The regression itself: these are what a pending-delete directory reports.
+ it('treats EPERM and EACCES as contention on Windows', () => {
+ expect(isLockContention(err('EPERM'), 'win32')).toBe(true);
+ expect(isLockContention(err('EACCES'), 'win32')).toBe(true);
+ });
+
+ // And does not swallow them elsewhere, where they mean the parent is not writable.
+ // Widening this to every platform would turn a real permission fault into "busy".
+ it('does not treat EPERM or EACCES as contention on POSIX', () => {
+ for (const platform of ['linux', 'darwin']) {
+ expect(isLockContention(err('EPERM'), platform)).toBe(false);
+ expect(isLockContention(err('EACCES'), platform)).toBe(false);
+ }
+ });
+
+ it('never swallows an unrelated failure', () => {
+ for (const code of ['ENOSPC', 'EROFS', 'ENAMETOOLONG', 'EMFILE']) {
+ expect(isLockContention(err(code), 'win32')).toBe(false);
+ expect(isLockContention(err(code), 'linux')).toBe(false);
+ }
+ expect(isLockContention(new Error('no code at all'), 'win32')).toBe(false);
+ });
+});
+
it('rejects lost updates from eight independent processes', async () => {
const child = Bun.spawn(
[
@@ -53,13 +99,20 @@ it('rejects lost updates from eight independent processes', async () => {
]);
expect(error).toBe('');
expect(code).toBe(0);
- expect(JSON.parse(output)).toMatchObject({
+ const receipt = JSON.parse(output);
+ expect(receipt).toMatchObject({
processes: 8,
updated: 1,
rejected: 7,
immutableReferencesResolved: 3,
originalSourcePreserved: true,
});
+ // Presence, not a bound. This is a wall-clock figure on whatever host is running, so
+ // asserting a ceiling here would be the flake this field exists to diagnose. What
+ // matters is that a passing receipt records its own headroom against the 10s guard --
+ // ~60ms on an idle Linux host, and the number that would have shown how close the
+ // 2026-09-12 Windows run came before it went red.
+ expect(typeof receipt.slowestWorkerMs).toBe('number');
} finally {
clearTimeout(timer);
}
diff --git a/src/experiments/program-aliases.ts b/src/experiments/program-aliases.ts
index e3c0007c..a2d7af85 100644
--- a/src/experiments/program-aliases.ts
+++ b/src/experiments/program-aliases.ts
@@ -1,9 +1,29 @@
/** Offline prototype only: deliberately absent from the package's public exports/tools. */
-import { mkdir, readFile, rename, rm, rmdir, writeFile } from 'node:fs/promises';
+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { assertProgramRef, type ProgramStore } from '../program-store';
+/**
+ * Whether a failed lock acquisition means "somebody else has it" rather than "broken".
+ *
+ * `mkdir` is the mutex, so POSIX answers this with `EEXIST` and nothing else. Windows has
+ * a second way to say the same thing: directory deletion is not synchronous, and a
+ * directory whose last handle has not closed sits in a pending-delete state where `mkdir`
+ * on that name fails with `EPERM` or `EACCES` instead of `EEXIST`. Every release here runs
+ * `rmdir(lock)` in a `finally`, so with eight processes contending, one arriving in that
+ * window is ordinary contention -- and the original code rethrew it, killing the worker.
+ *
+ * Narrowed to Windows deliberately. On POSIX, `EPERM`/`EACCES` from `mkdir` means the
+ * parent directory is not writable, and swallowing that would turn a real permission
+ * problem into a misleading "busy".
+ */
+export function isLockContention(error: unknown, platform: string = process.platform): boolean {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EEXIST') return true;
+ return platform === 'win32' && (code === 'EPERM' || code === 'EACCES');
+}
+
export class ExperimentalProgramAliases {
constructor(
readonly directory: string,
@@ -46,7 +66,7 @@ export class ExperimentalProgramAliases {
try {
await mkdir(lock);
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'EEXIST')
+ if (isLockContention(error))
throw new Error(`Alias busy: ${name}; reread and retry explicitly.`);
throw error;
}
@@ -61,7 +81,16 @@ export class ExperimentalProgramAliases {
});
await rename(temporary, target);
} finally {
- await Promise.all([rm(temporary, { force: true }), rmdir(lock)]);
+ // Cleanup must not decide what this call throws. `rmdir` has no `force`, and on
+ // Windows it can fail with `EBUSY`/`EPERM` while a scanner or another process holds
+ // the directory -- which in a `finally` would replace a precise `Alias conflict`
+ // with an unrelated errno, or turn a successful write into a failure. The lock's
+ // own name is what the next caller contends on, and `isLockContention` now treats a
+ // lingering one as busy, so failing to remove it degrades rather than corrupts.
+ await Promise.all([
+ rm(temporary, { force: true }).catch(() => {}),
+ rm(lock, { recursive: true, force: true }).catch(() => {}),
+ ]);
}
}
}