|
| 1 | +import { randomUUID } from "node:crypto"; |
| 2 | +import { |
| 3 | + existsSync, |
| 4 | + lstatSync, |
| 5 | + mkdirSync, |
| 6 | + readFileSync, |
| 7 | + readdirSync, |
| 8 | + realpathSync, |
| 9 | + renameSync, |
| 10 | + rmSync, |
| 11 | + statSync, |
| 12 | + writeFileSync, |
| 13 | +} from "node:fs"; |
| 14 | +import { tmpdir } from "node:os"; |
| 15 | +import { dirname, join, resolve } from "node:path"; |
| 16 | + |
| 17 | +export const TEST_TEMP_OWNER_FILE = ".opencodex-test-owner.json"; |
| 18 | +export const TEST_TEMP_RECOVERY_AGE_MS = 48 * 60 * 60 * 1000; |
| 19 | + |
| 20 | +const TEST_TEMP_OWNER_VERSION = 1; |
| 21 | +const TEST_TEMP_OWNER_KIND = "opencodex-test-root"; |
| 22 | +const WRAPPED_TEST_ROOT = /^opencodex-test-[A-Za-z0-9]{6}$/; |
| 23 | +const TRANSIENT_REMOVE_CODES = new Set(["EPERM", "EBUSY", "ENOTEMPTY"]); |
| 24 | +const DEFAULT_MAX_CANDIDATES = 10_000; |
| 25 | +const DEFAULT_MAX_TREE_ENTRIES = 250_000; |
| 26 | +const DEFAULT_MAX_DURATION_MS = 30_000; |
| 27 | + |
| 28 | +/** The first wait after a transient failure. Most release races clear on the first retry. */ |
| 29 | +export const REMOVE_RETRY_BASE_DELAY_MS = 50; |
| 30 | +/** The ceiling for a single wait, so a long tail never becomes a long stall between attempts. */ |
| 31 | +export const REMOVE_RETRY_MAX_DELAY_MS = 250; |
| 32 | +/** The total time the schedule may spend waiting on one tree. */ |
| 33 | +export const REMOVE_RETRY_BUDGET_MS = 15_000; |
| 34 | +/** Reclaiming a stale root is opportunistic: a root that resists briefly is left for a later run. */ |
| 35 | +export const RECOVERY_REMOVE_BUDGET_MS = 150; |
| 36 | + |
| 37 | +interface TestTempOwner { |
| 38 | + schemaVersion: 1; |
| 39 | + kind: typeof TEST_TEMP_OWNER_KIND; |
| 40 | + root: string; |
| 41 | + createdAtMs: number; |
| 42 | + pid: number; |
| 43 | + runId?: string; |
| 44 | +} |
| 45 | + |
| 46 | +export interface TestTempRecoveryResult { |
| 47 | + scanned: number; |
| 48 | + removed: number; |
| 49 | + skipped: number; |
| 50 | + errors: number; |
| 51 | + truncated: boolean; |
| 52 | +} |
| 53 | + |
| 54 | +type RemoveTreeOptions = Readonly<{ |
| 55 | + budgetMs?: number; |
| 56 | + delays?: readonly number[]; |
| 57 | + remove?: (path: string) => void; |
| 58 | + sleep?: (milliseconds: number) => void; |
| 59 | +}>; |
| 60 | + |
| 61 | +type RecoveryOptions = Readonly<{ |
| 62 | + tempRoot?: string; |
| 63 | + platform?: NodeJS.Platform; |
| 64 | + nowMs?: number; |
| 65 | + minimumAgeMs?: number; |
| 66 | + maxCandidates?: number; |
| 67 | + maxTreeEntries?: number; |
| 68 | + maxDurationMs?: number; |
| 69 | + /** Liveness seam. A recovery test must not depend on which pids the host happens to have. */ |
| 70 | + processIsAlive?: (pid: number) => boolean; |
| 71 | +}>; |
| 72 | + |
| 73 | +let automaticRecoveryAttempted = false; |
| 74 | + |
| 75 | +function errorCode(error: unknown): string { |
| 76 | + return error && typeof error === "object" && "code" in error ? String(error.code) : ""; |
| 77 | +} |
| 78 | + |
| 79 | +function samePath(left: string, right: string, platform: NodeJS.Platform): boolean { |
| 80 | + const normalizedLeft = resolve(left); |
| 81 | + const normalizedRight = resolve(right); |
| 82 | + return platform === "win32" |
| 83 | + ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase() |
| 84 | + : normalizedLeft === normalizedRight; |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * The only name shape a reclaimable root can have. |
| 89 | + * |
| 90 | + * A broader `ocx-*` class was considered and dropped: those directories never carried an |
| 91 | + * ownership marker, so under the marker requirement below they could only ever be scanned and |
| 92 | + * skipped, and the regex wide enough to catch them was also wide enough to put an unrelated |
| 93 | + * tool's directory on the candidate list. |
| 94 | + */ |
| 95 | +function isTestTempName(name: string): boolean { |
| 96 | + return WRAPPED_TEST_ROOT.test(name); |
| 97 | +} |
| 98 | + |
| 99 | +function processIsAlive(pid: number): boolean { |
| 100 | + if (pid === process.pid) return true; |
| 101 | + try { |
| 102 | + process.kill(pid, 0); |
| 103 | + return true; |
| 104 | + } catch (error) { |
| 105 | + return errorCode(error) !== "ESRCH"; |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +function parseOwner(path: string): TestTempOwner | null | undefined { |
| 110 | + const markerPath = join(path, TEST_TEMP_OWNER_FILE); |
| 111 | + if (!existsSync(markerPath)) return undefined; |
| 112 | + try { |
| 113 | + const marker = lstatSync(markerPath); |
| 114 | + if (!marker.isFile() || marker.isSymbolicLink()) return null; |
| 115 | + const parsed = JSON.parse(readFileSync(markerPath, "utf8")) as Partial<TestTempOwner>; |
| 116 | + if ( |
| 117 | + parsed.schemaVersion !== TEST_TEMP_OWNER_VERSION |
| 118 | + || parsed.kind !== TEST_TEMP_OWNER_KIND |
| 119 | + || typeof parsed.root !== "string" |
| 120 | + || typeof parsed.createdAtMs !== "number" |
| 121 | + || !Number.isFinite(parsed.createdAtMs) |
| 122 | + || typeof parsed.pid !== "number" |
| 123 | + || !Number.isSafeInteger(parsed.pid) |
| 124 | + || parsed.pid <= 0 |
| 125 | + || (parsed.runId !== undefined && typeof parsed.runId !== "string") |
| 126 | + ) return null; |
| 127 | + return parsed as TestTempOwner; |
| 128 | + } catch { |
| 129 | + return null; |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +function inspectTree( |
| 134 | + root: string, |
| 135 | + budget: { entries: number; deadlineMs: number; now: () => number }, |
| 136 | +): { safe: boolean; latestMtimeMs: number } { |
| 137 | + const pending = [root]; |
| 138 | + let latestMtimeMs = 0; |
| 139 | + while (pending.length > 0) { |
| 140 | + if (budget.entries <= 0 || budget.now() > budget.deadlineMs) { |
| 141 | + return { safe: false, latestMtimeMs }; |
| 142 | + } |
| 143 | + const current = pending.pop()!; |
| 144 | + let entry: ReturnType<typeof lstatSync>; |
| 145 | + try { |
| 146 | + entry = lstatSync(current); |
| 147 | + } catch { |
| 148 | + return { safe: false, latestMtimeMs }; |
| 149 | + } |
| 150 | + budget.entries -= 1; |
| 151 | + latestMtimeMs = Math.max(latestMtimeMs, entry.mtimeMs); |
| 152 | + if (entry.isSymbolicLink()) return { safe: false, latestMtimeMs }; |
| 153 | + if (!entry.isDirectory()) continue; |
| 154 | + let children: string[]; |
| 155 | + try { |
| 156 | + children = readdirSync(current); |
| 157 | + } catch { |
| 158 | + return { safe: false, latestMtimeMs }; |
| 159 | + } |
| 160 | + for (const child of children) pending.push(join(current, child)); |
| 161 | + } |
| 162 | + return { safe: true, latestMtimeMs }; |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * The waits between removal attempts: exponential from the base delay, capped, bounded by budget. |
| 167 | + * |
| 168 | + * The predecessor was flat -- 50 attempts at 50ms, so 2.5 seconds total. That budget was tuned on |
| 169 | + * a lightly loaded machine and six concurrent Windows shards exceed it, at which point the helper |
| 170 | + * rethrows the EPERM it exists to absorb and fails a test that had already finished asserting |
| 171 | + * (#4789). Growing the wait instead of the attempt count is what buys a long tail without paying |
| 172 | + * for it in the common case: the first retry still lands at 50ms, and a removal that succeeds on |
| 173 | + * its first attempt never sleeps at all, so nothing on the passing path gets slower. |
| 174 | + */ |
| 175 | +export function removeRetrySchedule(budgetMs: number = REMOVE_RETRY_BUDGET_MS): number[] { |
| 176 | + const delays: number[] = []; |
| 177 | + let spent = 0; |
| 178 | + let delay = REMOVE_RETRY_BASE_DELAY_MS; |
| 179 | + while (spent + delay <= budgetMs) { |
| 180 | + delays.push(delay); |
| 181 | + spent += delay; |
| 182 | + delay = Math.min(delay * 2, REMOVE_RETRY_MAX_DELAY_MS); |
| 183 | + } |
| 184 | + return delays; |
| 185 | +} |
| 186 | + |
| 187 | +/** Remove a test-owned tree while tolerating only transient Windows release races. */ |
| 188 | +export function removeTestTempTree(path: string, options: RemoveTreeOptions = {}): void { |
| 189 | + const delays = options.delays ?? removeRetrySchedule(options.budgetMs); |
| 190 | + const remove = options.remove ?? (target => rmSync(target, { recursive: true, force: true })); |
| 191 | + const sleep = options.sleep ?? Bun.sleepSync; |
| 192 | + |
| 193 | + for (let attempt = 0; attempt <= delays.length; attempt += 1) { |
| 194 | + try { |
| 195 | + remove(path); |
| 196 | + return; |
| 197 | + } catch (error) { |
| 198 | + if (!TRANSIENT_REMOVE_CODES.has(errorCode(error)) || attempt === delays.length) throw error; |
| 199 | + sleep(delays[attempt]!); |
| 200 | + } |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +/** Stamp a newly created root so future runs can prove its OpenCodex test ownership. */ |
| 205 | +export function writeTestTempOwner(root: string, runId?: string): void { |
| 206 | + const owner: TestTempOwner = { |
| 207 | + schemaVersion: TEST_TEMP_OWNER_VERSION, |
| 208 | + kind: TEST_TEMP_OWNER_KIND, |
| 209 | + root: realpathSync(root), |
| 210 | + createdAtMs: Date.now(), |
| 211 | + pid: process.pid, |
| 212 | + ...(runId ? { runId } : {}), |
| 213 | + }; |
| 214 | + const temporary = join(root, `.${TEST_TEMP_OWNER_FILE}.${process.pid}.${randomUUID()}.tmp`); |
| 215 | + writeFileSync(temporary, JSON.stringify(owner) + "\n", { encoding: "utf8", mode: 0o600, flag: "wx" }); |
| 216 | + renameSync(temporary, join(root, TEST_TEMP_OWNER_FILE)); |
| 217 | +} |
| 218 | + |
| 219 | +/** |
| 220 | + * Reclaim stale Windows test roots this tool can PROVE it owns. |
| 221 | + * |
| 222 | + * Ownership is the marker, not the name. A directory that merely looks like ours is scanned and |
| 223 | + * skipped: the accumulation already on a user's machine was written by versions that stamped |
| 224 | + * nothing, and deleting it on a name match would be this tool cleaning a TEMP tree it cannot |
| 225 | + * show it created. This release therefore changes future runs -- a root stamped by the code |
| 226 | + * below is reclaimable, everything older is left alone. |
| 227 | + * |
| 228 | + * On top of the marker: an exact mkdtemp-shaped name, a 48-hour grace period, direct-parent |
| 229 | + * containment, a dead owning pid, and a full no-link walk are all required before removal. |
| 230 | + * Invalid ownership metadata fails closed. |
| 231 | + */ |
| 232 | +export function recoverStaleTestTempArtifacts(options: RecoveryOptions = {}): TestTempRecoveryResult { |
| 233 | + const result: TestTempRecoveryResult = { |
| 234 | + scanned: 0, |
| 235 | + removed: 0, |
| 236 | + skipped: 0, |
| 237 | + errors: 0, |
| 238 | + truncated: false, |
| 239 | + }; |
| 240 | + const platform = options.platform ?? process.platform; |
| 241 | + if (platform !== "win32") return result; |
| 242 | + |
| 243 | + const nowMs = options.nowMs ?? Date.now(); |
| 244 | + const isAlive = options.processIsAlive ?? processIsAlive; |
| 245 | + const minimumAgeMs = options.minimumAgeMs ?? TEST_TEMP_RECOVERY_AGE_MS; |
| 246 | + const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES; |
| 247 | + const deadlineMs = Date.now() + (options.maxDurationMs ?? DEFAULT_MAX_DURATION_MS); |
| 248 | + const budget = { |
| 249 | + entries: options.maxTreeEntries ?? DEFAULT_MAX_TREE_ENTRIES, |
| 250 | + deadlineMs, |
| 251 | + now: Date.now, |
| 252 | + }; |
| 253 | + |
| 254 | + let tempRoot: string; |
| 255 | + try { |
| 256 | + tempRoot = realpathSync(options.tempRoot ?? tmpdir()); |
| 257 | + } catch { |
| 258 | + result.errors += 1; |
| 259 | + return result; |
| 260 | + } |
| 261 | + |
| 262 | + let names: string[]; |
| 263 | + try { |
| 264 | + names = readdirSync(tempRoot).sort(); |
| 265 | + } catch { |
| 266 | + result.errors += 1; |
| 267 | + return result; |
| 268 | + } |
| 269 | + |
| 270 | + for (const name of names) { |
| 271 | + if (!isTestTempName(name)) continue; |
| 272 | + if (result.scanned >= maxCandidates || Date.now() > deadlineMs || budget.entries <= 0) { |
| 273 | + result.truncated = true; |
| 274 | + break; |
| 275 | + } |
| 276 | + result.scanned += 1; |
| 277 | + const candidate = join(tempRoot, name); |
| 278 | + try { |
| 279 | + const rootEntry = lstatSync(candidate); |
| 280 | + if (!rootEntry.isDirectory() || rootEntry.isSymbolicLink()) { |
| 281 | + result.skipped += 1; |
| 282 | + continue; |
| 283 | + } |
| 284 | + const canonicalCandidate = realpathSync(candidate); |
| 285 | + if (!samePath(dirname(canonicalCandidate), tempRoot, platform)) { |
| 286 | + result.skipped += 1; |
| 287 | + continue; |
| 288 | + } |
| 289 | + |
| 290 | + // An absent marker is as disqualifying as a corrupt one. `undefined` used to mean "no |
| 291 | + // evidence either way, proceed on the name", which is exactly the name match this must not |
| 292 | + // be. |
| 293 | + const owner = parseOwner(candidate); |
| 294 | + if (!owner || !samePath(owner.root, canonicalCandidate, platform)) { |
| 295 | + result.skipped += 1; |
| 296 | + continue; |
| 297 | + } |
| 298 | + if (isAlive(owner.pid)) { |
| 299 | + result.skipped += 1; |
| 300 | + continue; |
| 301 | + } |
| 302 | + const rootActivityMs = Math.max(statSync(candidate).mtimeMs, owner.createdAtMs); |
| 303 | + if (nowMs - rootActivityMs < minimumAgeMs) { |
| 304 | + result.skipped += 1; |
| 305 | + continue; |
| 306 | + } |
| 307 | + const tree = inspectTree(candidate, budget); |
| 308 | + if (!tree.safe) { |
| 309 | + result.skipped += 1; |
| 310 | + if (Date.now() > deadlineMs || budget.entries <= 0) result.truncated = true; |
| 311 | + continue; |
| 312 | + } |
| 313 | + if (nowMs - Math.max(rootActivityMs, tree.latestMtimeMs) < minimumAgeMs) { |
| 314 | + result.skipped += 1; |
| 315 | + continue; |
| 316 | + } |
| 317 | + |
| 318 | + removeTestTempTree(candidate, { budgetMs: RECOVERY_REMOVE_BUDGET_MS }); |
| 319 | + result.removed += 1; |
| 320 | + } catch (error) { |
| 321 | + if (errorCode(error) !== "ENOENT") result.errors += 1; |
| 322 | + } |
| 323 | + } |
| 324 | + |
| 325 | + return result; |
| 326 | +} |
| 327 | + |
| 328 | +/** Run automatic recovery once per process, before the process creates its own test root. */ |
| 329 | +export function recoverStaleTestTempArtifactsOnce( |
| 330 | + options: RecoveryOptions = {}, |
| 331 | +): TestTempRecoveryResult | null { |
| 332 | + if (automaticRecoveryAttempted) return null; |
| 333 | + automaticRecoveryAttempted = true; |
| 334 | + return recoverStaleTestTempArtifacts(options); |
| 335 | +} |
| 336 | + |
| 337 | +/** Create the contained temp subtree used by every os.tmpdir() call in the child test process. */ |
| 338 | +export function createContainedTestTemp(root: string): string { |
| 339 | + const contained = join(root, "tmp"); |
| 340 | + mkdirSync(contained, { recursive: true }); |
| 341 | + return contained; |
| 342 | +} |
0 commit comments