fix(tests): deterministic concurrency via injectable clock seam; delete flaky racing tests (#459)
* feat(#453): add deterministic clock seam to lock modules Introduces get-shit-done/bin/lib/clock.cjs exporting realClock with now() (Date.now) and sleep() (Atomics.wait). acquireStateLock, writeStateMd, and readModifyWriteStateMd in state.cjs each accept an optional trailing clock param (default: realClock). withPlanningLock in planning-workspace.cjs gains the same seam. No production behavior change — all callers that omit the param continue to use realClock. Adds tests/helpers/clock.cjs (makeFakeClock) and tests/clock-seam.test.cjs with 20 deterministic in-process tests covering: lock serialization, timeout throw at maxWaitMs boundary, stale-lock takeover, lock released on error path, withPlanningLock timeout recovery, exit-cleanup integration, readModifyWriteStateMd call-site coverage (7 cmd*), and roadmap analyze behavioral assertion (50 phases, no elapsed-time gate). Deletes/converts per research verdicts: removes 11 source-grep/elapsed-time/ non-deterministic-concurrent tests across concurrency-safety.test.cjs, locking-bugs-1909-1916-1925-1927.test.cjs, and bug-1974-context-exhaustion- record.test.cjs. All deleted tests have deterministic replacements in clock-seam.test.cjs or surviving barrier-based tests. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#453): update module inventory for clock.cjs; make EEXIST-retry assertion behavioral Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#453): satisfy lint-tests — allow-test-rule annotation on readFileSync/includes runtime output check Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: CI Rebase Check <ci@gsd-redux> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
41
get-shit-done/bin/lib/clock.cjs
Normal file
41
get-shit-done/bin/lib/clock.cjs
Normal file
@@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Deterministic clock seam for lock modules (issue #453).
|
||||
*
|
||||
* Production code uses `realClock` (the default). Test code passes in a
|
||||
* `makeFakeClock()` instance to drive lock timing without real wall-clock
|
||||
* waits or Atomics.wait calls.
|
||||
*
|
||||
* Both methods in realClock use exactly the same system primitives that
|
||||
* acquireStateLock and withPlanningLock used inline before the seam was
|
||||
* introduced:
|
||||
* - now() → Date.now()
|
||||
* - sleep() → Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
||||
*/
|
||||
|
||||
// Module-level Atomics.wait buffer reused across every realClock.sleep() call.
|
||||
// The buffer value is always 0 (never written), so reuse is semantically
|
||||
// identical to allocating a fresh buffer each time.
|
||||
const _realSleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
const realClock = {
|
||||
/** Return current epoch milliseconds (same as the inline Date.now() calls in state.cjs). */
|
||||
now() {
|
||||
return Date.now();
|
||||
},
|
||||
|
||||
/**
|
||||
* Synchronous sleep via Atomics.wait.
|
||||
* This is the identical primitive acquireStateLock and withPlanningLock used
|
||||
* inline before the seam. Atomics.wait on a shared buffer that is never
|
||||
* notified times out after exactly `ms` milliseconds without spinning the CPU.
|
||||
*
|
||||
* @param {number} ms - milliseconds to sleep
|
||||
*/
|
||||
sleep(ms) {
|
||||
Atomics.wait(_realSleepBuf, 0, 0, ms);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = { realClock };
|
||||
@@ -12,6 +12,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { platformEnsureDir } = require('./shell-command-projection.cjs');
|
||||
const { realClock } = require('./clock.cjs');
|
||||
const {
|
||||
createSharedPointerAdapter,
|
||||
createSessionScopedPointerAdapter,
|
||||
@@ -82,10 +83,19 @@ function planningPaths(cwd, ws) {
|
||||
};
|
||||
}
|
||||
|
||||
function withPlanningLock(cwd, fn) {
|
||||
/**
|
||||
* @param {string} cwd
|
||||
* @param {function} fn - callback to run while holding the lock
|
||||
* @param {{ now(): number, sleep(ms: number): void }} [clock]
|
||||
* Optional clock seam for testing. Defaults to realClock (Date.now + Atomics.wait).
|
||||
* Pass a fake clock from tests/helpers/clock.cjs to drive timeout/stale logic
|
||||
* without real wall-clock waits.
|
||||
*/
|
||||
function withPlanningLock(cwd, fn, clock) {
|
||||
if (clock === undefined) clock = realClock;
|
||||
const lockPath = path.join(planningDir(cwd), '.lock');
|
||||
const lockTimeout = 10000; // 10 seconds
|
||||
const start = Date.now();
|
||||
const start = clock.now();
|
||||
|
||||
// Ensure .planning/ exists
|
||||
try { platformEnsureDir(planningDir(cwd)); } catch { /* ok */ }
|
||||
@@ -109,13 +119,7 @@ function withPlanningLock(cwd, fn) {
|
||||
}
|
||||
}
|
||||
|
||||
// Allocate once before the retry loop — reused on every Atomics.wait spin.
|
||||
// The buffer value is always 0 (never written), so reuse is semantically
|
||||
// identical to allocating fresh each time. Mirrors the #316/#399 fix for
|
||||
// acquireStateLock in state.cjs.
|
||||
const sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
while (Date.now() - start < lockTimeout) {
|
||||
while (clock.now() - start < lockTimeout) {
|
||||
try {
|
||||
return runWithHeldLock();
|
||||
} catch (err) {
|
||||
@@ -123,21 +127,21 @@ function withPlanningLock(cwd, fn) {
|
||||
// are recoverable — wait and retry rather than propagating.
|
||||
// See PLANNING_LOCK_RETRY_ERRNOS for the full list and rationale.
|
||||
if (PLANNING_LOCK_RETRY_ERRNOS.has(err.code)) {
|
||||
Atomics.wait(sleepBuf, 0, 0, 100);
|
||||
clock.sleep(100);
|
||||
continue;
|
||||
}
|
||||
if (err.code === 'EEXIST') {
|
||||
// Lock exists — check if stale (>30s old)
|
||||
try {
|
||||
const stat = fs.statSync(lockPath);
|
||||
if (Date.now() - stat.mtimeMs > 30000) {
|
||||
if (clock.now() - stat.mtimeMs > 30000) {
|
||||
fs.unlinkSync(lockPath);
|
||||
continue; // retry
|
||||
}
|
||||
} catch { continue; }
|
||||
|
||||
// Wait and retry (cross-platform, no shell dependency)
|
||||
Atomics.wait(sleepBuf, 0, 0, 100);
|
||||
clock.sleep(100);
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
|
||||
@@ -7,6 +7,7 @@ const path = require('path');
|
||||
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, output, error } = require('./core.cjs');
|
||||
const { platformWriteSync, platformReadSync, platformEnsureDir } = require('./shell-command-projection.cjs');
|
||||
const { planningDir, planningPaths } = require('./planning-workspace.cjs');
|
||||
const { realClock } = require('./clock.cjs');
|
||||
const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
|
||||
const scanPhasePlans = require('./plan-scan.cjs');
|
||||
const {
|
||||
@@ -992,14 +993,20 @@ const ACQUIRE_LOCK_RETRY_ERRNOS = new Set([
|
||||
/**
|
||||
* Acquire a lockfile for STATE.md operations.
|
||||
* Returns the lock path for later release.
|
||||
*
|
||||
* @param {string} statePath
|
||||
* @param {{ now(): number, sleep(ms: number): void }} [clock]
|
||||
* Optional clock seam for testing. Defaults to realClock (Date.now + Atomics.wait).
|
||||
* Pass a fake clock from tests/helpers/clock.cjs to drive timeout/stale logic
|
||||
* without real wall-clock waits.
|
||||
*/
|
||||
function acquireStateLock(statePath) {
|
||||
function acquireStateLock(statePath, clock) {
|
||||
if (clock === undefined) clock = realClock;
|
||||
const lockPath = statePath + '.lock';
|
||||
const retryDelay = 200; // ms
|
||||
const staleThresholdMs = 10000;
|
||||
const maxWaitMs = 30000;
|
||||
const startedAt = Date.now();
|
||||
const sleepBuffer = new Int32Array(new SharedArrayBuffer(4)); // hoisted; value stays 0, pure Atomics.wait timeout target
|
||||
const startedAt = clock.now();
|
||||
|
||||
|
||||
while (true) {
|
||||
@@ -1021,19 +1028,19 @@ function acquireStateLock(statePath) {
|
||||
// writer causes lost updates (#3711 regression).
|
||||
try {
|
||||
const stat = fs.statSync(lockPath);
|
||||
if (Date.now() - stat.mtimeMs > staleThresholdMs) {
|
||||
if (clock.now() - stat.mtimeMs > staleThresholdMs) {
|
||||
try { fs.unlinkSync(lockPath); } catch { /* already gone */ }
|
||||
continue;
|
||||
}
|
||||
} catch { continue; /* released between EEXIST and stat */ }
|
||||
if (Date.now() - startedAt >= maxWaitMs) {
|
||||
if (clock.now() - startedAt >= maxWaitMs) {
|
||||
throw new Error(
|
||||
'acquireStateLock: ' + lockPath + ' held by live process for ' +
|
||||
(Date.now() - startedAt) + 'ms (exceeded ' + maxWaitMs + 'ms budget)'
|
||||
(clock.now() - startedAt) + 'ms (exceeded ' + maxWaitMs + 'ms budget)'
|
||||
);
|
||||
}
|
||||
const jitter = Math.floor(Math.random() * 50);
|
||||
Atomics.wait(sleepBuffer, 0, 0, retryDelay + jitter);
|
||||
clock.sleep(retryDelay + jitter);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1048,14 +1055,20 @@ function releaseStateLock(lockPath) {
|
||||
* All STATE.md writes should use this instead of raw writeFileSync.
|
||||
* Uses a simple lockfile to prevent parallel agents from overwriting
|
||||
* each other's changes (race condition with read-modify-write cycle).
|
||||
*
|
||||
* @param {string} statePath
|
||||
* @param {string} content
|
||||
* @param {string} [cwd]
|
||||
* @param {{ now(): number, sleep(ms: number): void }} [clock]
|
||||
* Optional clock seam; defaults to realClock. Passed through to acquireStateLock.
|
||||
*/
|
||||
function writeStateMd(statePath, content, cwd) {
|
||||
function writeStateMd(statePath, content, cwd, clock) {
|
||||
// Invalidate disk scan cache before computing new frontmatter — the write
|
||||
// may create new PLAN/SUMMARY files that buildStateFrontmatter must see.
|
||||
// Safe for any calling pattern, not just short-lived CLI processes (#1967).
|
||||
if (cwd) _diskScanCache.delete(cwd);
|
||||
const synced = syncStateFrontmatter(content, cwd);
|
||||
const lockPath = acquireStateLock(statePath);
|
||||
const lockPath = acquireStateLock(statePath, clock);
|
||||
try {
|
||||
platformWriteSync(statePath, synced);
|
||||
} finally {
|
||||
@@ -1080,10 +1093,12 @@ function writeStateMd(statePath, content, cwd) {
|
||||
* When resync is false, syncStateFrontmatter still runs to maintain/create the
|
||||
* frontmatter block, but any existing progress.* sub-keys are preserved from
|
||||
* the pre-transform file rather than being rebuilt from disk.
|
||||
* @param {{ now(): number, sleep(ms: number): void }} [clock]
|
||||
* Optional clock seam; defaults to realClock. Passed through to acquireStateLock.
|
||||
*/
|
||||
function readModifyWriteStateMd(statePath, transformFn, cwd, options) {
|
||||
function readModifyWriteStateMd(statePath, transformFn, cwd, options, clock) {
|
||||
const resync = !options || options.resync !== false;
|
||||
const lockPath = acquireStateLock(statePath);
|
||||
const lockPath = acquireStateLock(statePath, clock);
|
||||
try {
|
||||
const content = platformReadSync(statePath) || '';
|
||||
// Snapshot the existing progress block BEFORE the transform so we can
|
||||
@@ -1979,6 +1994,8 @@ module.exports = {
|
||||
stateExtractField,
|
||||
stateReplaceField,
|
||||
stateReplaceFieldWithFallback,
|
||||
acquireStateLock,
|
||||
releaseStateLock,
|
||||
writeStateMd,
|
||||
readModifyWriteStateMd,
|
||||
updatePerformanceMetricsSection,
|
||||
|
||||
Reference in New Issue
Block a user