pi-spine 2.25.0 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/batch/abort.mjs +74 -38
- package/src/batch/attached-engine-handoff.mjs +2 -2
- package/src/batch/attached-runner-promote.mjs +1 -1
- package/src/batch/attached-runner-reconcile.mjs +1 -1
- package/src/batch/batch-meta-reconstruct.mjs +6 -1
- package/src/batch/batch-state-lock.mjs +173 -31
- package/src/batch/contract-exec.mjs +46 -45
- package/src/batch/contract-spawn.mjs +225 -0
- package/src/batch/contract-verify.mjs +2 -1
- package/src/batch/detached-wait.mjs +1 -1
- package/src/batch/engine-lanes/matrix-run.mjs +6 -6
- package/src/batch/engine-lanes/merge.mjs +135 -34
- package/src/batch/engine-lanes/review-final.mjs +1 -1
- package/src/batch/engine-lanes.mjs +11 -9
- package/src/batch/engine.mjs +10 -10
- package/src/batch/lifecycle-archive.mjs +76 -1
- package/src/batch/lifecycle-cleanup.mjs +110 -0
- package/src/batch/lifecycle.mjs +100 -72
- package/src/batch/parent-session-monitor.mjs +77 -70
- package/src/batch/pause.mjs +92 -25
- package/src/batch/post-merge-limbo.mjs +35 -5
- package/src/batch/resume-gate-reopen.mjs +24 -8
- package/src/batch/resume-multi.mjs +1 -1
- package/src/batch/resume.mjs +1 -1
- package/src/batch/sequence-run.mjs +26 -8
- package/src/batch/sequence-wait.mjs +87 -8
- package/src/batch/state-guards.mjs +39 -7
- package/src/batch/state-io.mjs +131 -17
- package/src/batch/state.mjs +1 -0
- package/src/batch/worker-host.mjs +32 -4
- package/src/config/defaults.mjs +15 -1
- package/src/config/preflight/git-batch.mjs +47 -0
- package/src/config/spine-config-schema.mjs +67 -1
- package/src/fs/atomic-write.mjs +37 -1
package/package.json
CHANGED
package/src/batch/abort.mjs
CHANGED
|
@@ -8,6 +8,8 @@ import path from "node:path";
|
|
|
8
8
|
import { loadSpineConfig } from "../config/spine-config-load.mjs";
|
|
9
9
|
import { writeJsonAtomic } from "../fs/atomic-write.mjs";
|
|
10
10
|
import { archiveBatchStatePath } from "./lifecycle.mjs";
|
|
11
|
+
import { reloadStateForTerminalWrite } from "./lifecycle-archive.mjs";
|
|
12
|
+
import { runPostReleaseCleanup } from "./lifecycle-cleanup.mjs";
|
|
11
13
|
import { appendJournalEvent, journalPath, readJournalEvents, readJournalTail } from "./journal.mjs";
|
|
12
14
|
import { loadBatchStateFile } from "./reconcile.mjs";
|
|
13
15
|
import { appendBatchHistoryEntry } from "./state.mjs";
|
|
@@ -220,21 +222,29 @@ export function abortBatch(ctx) {
|
|
|
220
222
|
}
|
|
221
223
|
|
|
222
224
|
// Terminal abort write section runs under the global batch-state lock
|
|
223
|
-
// (SP-722 / #264): abort signal, archive,
|
|
224
|
-
// active state must not interleave with a
|
|
225
|
-
// concurrent complete/resume writer.
|
|
226
|
-
|
|
227
|
-
|
|
225
|
+
// (SP-722 / #264; SP-796 / #302): abort signal, archive, journal event,
|
|
226
|
+
// history entry, and clearing the active state must not interleave with a
|
|
227
|
+
// concurrent engine save or a concurrent complete/resume writer. Worker
|
|
228
|
+
// termination and worktree removal run after the lock is released.
|
|
229
|
+
const inLock = withBatchStateLock(projectRoot, () => {
|
|
230
|
+
// SP-792 / #301: archive the state as re-read inside the lock. Engine
|
|
231
|
+
// progress saved between the pre-lock read and here must survive into
|
|
232
|
+
// the archive; a changed or vanished state file fails closed instead.
|
|
233
|
+
const { state: fresh, refusal } = reloadStateForTerminalWrite({
|
|
234
|
+
projectRoot,
|
|
235
|
+
batchStatePath: loaded.path,
|
|
236
|
+
batchId,
|
|
237
|
+
action: "abort",
|
|
238
|
+
});
|
|
239
|
+
if (refusal) return { refusal, snapshot: null, archivePath: null };
|
|
240
|
+
|
|
241
|
+
const snapshot = buildAbortedSnapshot(fresh.raw, reason);
|
|
228
242
|
writeAbortSignal(projectRoot, batchId, {
|
|
229
243
|
hard,
|
|
230
244
|
reason: reason ?? null,
|
|
231
245
|
requestedAt: new Date().toISOString(),
|
|
232
246
|
});
|
|
233
247
|
|
|
234
|
-
if (hard) {
|
|
235
|
-
killLaneWorkers(snapshot.lanes, true);
|
|
236
|
-
}
|
|
237
|
-
|
|
238
248
|
const archivePath = writeBatchArchive(projectRoot, batchId, snapshot);
|
|
239
249
|
|
|
240
250
|
const eventsBefore = readJournalEvents(projectRoot, batchId);
|
|
@@ -250,12 +260,16 @@ export function abortBatch(ctx) {
|
|
|
250
260
|
const journalFile = journalPath(projectRoot, batchId);
|
|
251
261
|
if (!fs.existsSync(journalFile)) {
|
|
252
262
|
return {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
263
|
+
refusal: {
|
|
264
|
+
ok: false,
|
|
265
|
+
exitCode: 1,
|
|
266
|
+
error: "journal_missing_after_abort",
|
|
267
|
+
headline: "Abort archived state but journal file is missing",
|
|
268
|
+
suggestedCommand: "spine status --diagnose",
|
|
269
|
+
batchId,
|
|
270
|
+
},
|
|
271
|
+
snapshot: null,
|
|
272
|
+
archivePath: null,
|
|
259
273
|
};
|
|
260
274
|
}
|
|
261
275
|
|
|
@@ -268,34 +282,56 @@ export function abortBatch(ctx) {
|
|
|
268
282
|
archivePath: path.relative(projectRoot, archivePath),
|
|
269
283
|
});
|
|
270
284
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
285
|
+
clearActiveBatchState(fresh.path);
|
|
286
|
+
|
|
287
|
+
return { refusal: null, snapshot, archivePath };
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
// Cleanup runs only when the in-lock section succeeded (journaled
|
|
291
|
+
// `batch.aborted`); a refusal means nothing was archived for this batch.
|
|
292
|
+
if (inLock.refusal) return inLock.refusal;
|
|
293
|
+
|
|
294
|
+
// SP-796 / #302: worker kill and worktree removal run after the lock is
|
|
295
|
+
// released, so they no longer block concurrent engine saves. Failures
|
|
296
|
+
// here are reported as cleanupWarnings + `batch.cleanup_failed` instead
|
|
297
|
+
// of thrown, because the state was already archived and journaled aborted.
|
|
298
|
+
const cleanupSteps = [];
|
|
299
|
+
if (hard) {
|
|
300
|
+
cleanupSteps.push({
|
|
301
|
+
step: "kill_lane_workers",
|
|
302
|
+
run: () => {
|
|
303
|
+
killLaneWorkers(inLock.snapshot.lanes, true);
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
cleanupSteps.push({
|
|
307
|
+
step: "remove_worktrees",
|
|
308
|
+
run: () => {
|
|
309
|
+
const config = loadSpineConfig(projectRoot).config ?? {};
|
|
310
|
+
if (!shouldCleanupWorktreesOnHardAbort(config)) return;
|
|
311
|
+
const laneCount = maxLaneNumberFromBatchState(inLock.snapshot);
|
|
276
312
|
removeLaneWorktrees(projectRoot, batchId, laneCount);
|
|
277
313
|
appendJournalEvent(projectRoot, batchId, "batch.worktrees_cleaned", {
|
|
278
314
|
batchId,
|
|
279
315
|
laneCount,
|
|
280
316
|
reason: "hard_abort",
|
|
281
317
|
});
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
const cleanupWarnings = runPostReleaseCleanup({ projectRoot, batchId, steps: cleanupSteps });
|
|
286
322
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
}
|
|
323
|
+
return {
|
|
324
|
+
ok: true,
|
|
325
|
+
exitCode: 0,
|
|
326
|
+
batchId,
|
|
327
|
+
diagnosis: "aborted",
|
|
328
|
+
hard,
|
|
329
|
+
headline: hard
|
|
330
|
+
? `Batch ${batchId} hard-aborted and archived`
|
|
331
|
+
: `Batch ${batchId} aborted and archived`,
|
|
332
|
+
suggestedCommand: "spine preflight",
|
|
333
|
+
alternatives: ["spine batch dismiss", "spine status --diagnose"],
|
|
334
|
+
archivePath: inLock.archivePath,
|
|
335
|
+
cleanupWarnings,
|
|
336
|
+
};
|
|
301
337
|
}
|
|
@@ -120,7 +120,7 @@ export function attemptPostMergeLandLoopHandoff({
|
|
|
120
120
|
});
|
|
121
121
|
if (finalizeResult?.ok) {
|
|
122
122
|
clearBatchEnginePid(state);
|
|
123
|
-
saveSpineBatchState(projectRoot, state, {
|
|
123
|
+
saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
|
|
124
124
|
appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
|
|
125
125
|
signal,
|
|
126
126
|
action: "finalized_in_process",
|
|
@@ -145,7 +145,7 @@ export function attemptPostMergeLandLoopHandoff({
|
|
|
145
145
|
const fresh = loadSpineBatchState(projectRoot);
|
|
146
146
|
if (fresh.raw && enginePid) {
|
|
147
147
|
recordBatchEnginePid(fresh.raw, enginePid);
|
|
148
|
-
saveSpineBatchState(projectRoot, fresh.raw, {
|
|
148
|
+
saveSpineBatchState(projectRoot, fresh.raw, { bypassOwnerCheck: true });
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
appendJournalEvent(projectRoot, batchId, "engine.attached_post_merge_handoff", {
|
|
@@ -456,7 +456,7 @@ export function finalizeResumePostMergeLimbo({
|
|
|
456
456
|
batchId,
|
|
457
457
|
fromPhase,
|
|
458
458
|
});
|
|
459
|
-
saveSpineBatchState(projectRoot, state, {
|
|
459
|
+
saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
|
|
460
460
|
|
|
461
461
|
return finalizeResumedBatchForIntegrate({
|
|
462
462
|
projectRoot,
|
|
@@ -229,7 +229,7 @@ export function enforceAttachedEngineSingleOwner({ projectRoot, force = false, o
|
|
|
229
229
|
fromPhase,
|
|
230
230
|
allowRunningOrphanTerminate: true,
|
|
231
231
|
});
|
|
232
|
-
saveSpineBatchState(projectRoot, state, {
|
|
232
|
+
saveSpineBatchState(projectRoot, state, { bypassOwnerCheck: true });
|
|
233
233
|
return {
|
|
234
234
|
ok: true,
|
|
235
235
|
handoff: true,
|
|
@@ -382,7 +382,12 @@ export function ensureForceResumeBatchState(projectRoot, options = {}) {
|
|
|
382
382
|
};
|
|
383
383
|
}
|
|
384
384
|
|
|
385
|
-
|
|
385
|
+
// Operator-initiated force-resume intentionally rebuilds a batch whose live
|
|
386
|
+
// state is gone (#126): this is the one sanctioned archived resurrection.
|
|
387
|
+
const saved = saveSpineBatchState(projectRoot, reconstructed.state, {
|
|
388
|
+
bypassOwnerCheck: true,
|
|
389
|
+
allowArchivedResurrection: true,
|
|
390
|
+
});
|
|
386
391
|
appendJournalEvent(projectRoot, reconstructed.batchId, "batch.state_reconstructed", {
|
|
387
392
|
reason,
|
|
388
393
|
source: reconstructed.reconstructedFrom ?? "batch-meta",
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
import crypto from "node:crypto";
|
|
25
25
|
import fs from "node:fs";
|
|
26
26
|
import path from "node:path";
|
|
27
|
+
import { setTimeout as sleepAsync } from "node:timers/promises";
|
|
27
28
|
import {
|
|
28
29
|
ENGINE_STARTTIME_TOLERANCE_MS,
|
|
29
30
|
isProcessAlive,
|
|
@@ -172,6 +173,93 @@ function tryCreateLockFile(lockPath, token) {
|
|
|
172
173
|
}
|
|
173
174
|
}
|
|
174
175
|
|
|
176
|
+
/**
|
|
177
|
+
* Steal the lock by renaming it out of the acquisition path, but only when
|
|
178
|
+
* the renamed file is still the exact lock that was judged stale (SP-794 /
|
|
179
|
+
* GitHub #302 defect 1).
|
|
180
|
+
*
|
|
181
|
+
* A bare `unlinkSync` could remove a lock a different waiter had freshly
|
|
182
|
+
* acquired after the staleness judgment: two concurrent breakers of the same
|
|
183
|
+
* dead holder would both "win", each running the critical section while the
|
|
184
|
+
* other holds it. `renameSync` is atomic, so at most one breaker ever moves a
|
|
185
|
+
* given lock file; the token/content re-check guarantees the moved file is
|
|
186
|
+
* the same one the breaker judged stale. Exported for direct unit testing of
|
|
187
|
+
* the put-back branch, which cannot be scheduled deterministically through
|
|
188
|
+
* `withBatchStateLock`.
|
|
189
|
+
*
|
|
190
|
+
* @param {string} lockPath
|
|
191
|
+
* @param {string} staleToken ownership token observed when the lock was
|
|
192
|
+
* judged stale; empty for corrupt/invalid payloads that carry no token.
|
|
193
|
+
* @param {string} reason diagnostic label for the steal log
|
|
194
|
+
* @param {string | null} [staleContent] raw payload text observed when the
|
|
195
|
+
* lock was judged stale; compared in full when `staleToken` is empty.
|
|
196
|
+
*/
|
|
197
|
+
export function stealIfTokenMatches(lockPath, staleToken, reason, staleContent = null) {
|
|
198
|
+
const stolenPath = `${lockPath}.break.${process.pid}.${newOwnershipToken()}`;
|
|
199
|
+
try {
|
|
200
|
+
fs.renameSync(lockPath, stolenPath);
|
|
201
|
+
} catch {
|
|
202
|
+
// ENOENT: another breaker or the holder's release already removed the
|
|
203
|
+
// lock — nothing to steal. Any other FS error also leaves lockPath
|
|
204
|
+
// untouched; treat it as a lost race so the acquire loop keeps its
|
|
205
|
+
// wait-then-timeout behavior (the unlink-based break this replaces
|
|
206
|
+
// swallowed its failures the same way).
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
// Below this point nothing throws: every op is wrapped so a live holder's
|
|
210
|
+
// lock file is never stranded away from lockPath.
|
|
211
|
+
|
|
212
|
+
/** @type {string | null} */
|
|
213
|
+
let currentContent = null;
|
|
214
|
+
try {
|
|
215
|
+
currentContent = fs.readFileSync(stolenPath, "utf-8");
|
|
216
|
+
} catch {
|
|
217
|
+
currentContent = null;
|
|
218
|
+
}
|
|
219
|
+
let sameStaleLock = false;
|
|
220
|
+
if (typeof staleToken === "string" && staleToken.length > 0) {
|
|
221
|
+
try {
|
|
222
|
+
const current = JSON.parse(currentContent ?? "");
|
|
223
|
+
sameStaleLock =
|
|
224
|
+
current != null &&
|
|
225
|
+
typeof current === "object" &&
|
|
226
|
+
String(/** @type {{ token?: unknown }} */ (current).token ?? "") === staleToken;
|
|
227
|
+
} catch {
|
|
228
|
+
sameStaleLock = false;
|
|
229
|
+
}
|
|
230
|
+
} else {
|
|
231
|
+
// Corrupt/invalid payloads carry no trustworthy token — compare the
|
|
232
|
+
// full file content instead.
|
|
233
|
+
sameStaleLock = currentContent != null && currentContent === staleContent;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (sameStaleLock) {
|
|
237
|
+
logLockBreak(lockPath, reason);
|
|
238
|
+
try {
|
|
239
|
+
fs.unlinkSync(stolenPath);
|
|
240
|
+
} catch {
|
|
241
|
+
/* already removed */
|
|
242
|
+
}
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// The lock at lockPath was replaced between the staleness judgment and the
|
|
247
|
+
// rename — a new holder now owns it. Put the file back; EEXIST means a
|
|
248
|
+
// third process already acquired lockPath in the microscopic gap, which is
|
|
249
|
+
// also fine. Either way the renamed copy is discarded.
|
|
250
|
+
try {
|
|
251
|
+
fs.linkSync(stolenPath, lockPath);
|
|
252
|
+
} catch {
|
|
253
|
+
/* EEXIST — someone else owns lockPath now; discard the copy below */
|
|
254
|
+
} finally {
|
|
255
|
+
try {
|
|
256
|
+
fs.unlinkSync(stolenPath);
|
|
257
|
+
} catch {
|
|
258
|
+
/* already removed */
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
175
263
|
/**
|
|
176
264
|
* Break the lock when the recorded holder cannot still own it: dead PID,
|
|
177
265
|
* abandoned corrupt payload, same-process leak (no active holder), or a live
|
|
@@ -186,9 +274,12 @@ function tryCreateLockFile(lockPath, token) {
|
|
|
186
274
|
function breakStaleLock(lockPath) {
|
|
187
275
|
/** @type {{ pid?: number, startedAt?: number, token?: string } | null} */
|
|
188
276
|
let holder = null;
|
|
277
|
+
/** @type {string | null} raw payload text, for content-compare steals. */
|
|
278
|
+
let rawContent = null;
|
|
189
279
|
let corrupt = false;
|
|
190
280
|
try {
|
|
191
|
-
|
|
281
|
+
rawContent = fs.readFileSync(lockPath, "utf-8");
|
|
282
|
+
holder = JSON.parse(rawContent);
|
|
192
283
|
if (!holder || typeof holder !== "object") corrupt = true;
|
|
193
284
|
} catch {
|
|
194
285
|
corrupt = true;
|
|
@@ -211,23 +302,13 @@ function breakStaleLock(lockPath) {
|
|
|
211
302
|
} catch {
|
|
212
303
|
return;
|
|
213
304
|
}
|
|
214
|
-
|
|
215
|
-
logLockBreak(lockPath, "corrupt-stale");
|
|
216
|
-
fs.unlinkSync(lockPath);
|
|
217
|
-
} catch {
|
|
218
|
-
/* raced unlink */
|
|
219
|
-
}
|
|
305
|
+
stealIfTokenMatches(lockPath, "", "corrupt-stale", rawContent);
|
|
220
306
|
return;
|
|
221
307
|
}
|
|
222
308
|
|
|
223
309
|
const holderPid = Number(holder?.pid);
|
|
224
310
|
if (!Number.isFinite(holderPid) || holderPid <= 0) {
|
|
225
|
-
|
|
226
|
-
logLockBreak(lockPath, "invalid-pid");
|
|
227
|
-
fs.unlinkSync(lockPath);
|
|
228
|
-
} catch {
|
|
229
|
-
/* raced unlink */
|
|
230
|
-
}
|
|
311
|
+
stealIfTokenMatches(lockPath, "", "invalid-pid", rawContent);
|
|
231
312
|
return;
|
|
232
313
|
}
|
|
233
314
|
|
|
@@ -242,12 +323,12 @@ function breakStaleLock(lockPath) {
|
|
|
242
323
|
if (stillHeldByToken || stillHeldByPath) {
|
|
243
324
|
return;
|
|
244
325
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
326
|
+
stealIfTokenMatches(
|
|
327
|
+
lockPath,
|
|
328
|
+
token,
|
|
329
|
+
`leakedSelf token=${token} mapSize=${heldByThisProcess.size}`,
|
|
330
|
+
rawContent,
|
|
331
|
+
);
|
|
251
332
|
return;
|
|
252
333
|
}
|
|
253
334
|
|
|
@@ -255,12 +336,12 @@ function breakStaleLock(lockPath) {
|
|
|
255
336
|
// under suite load the PID is often recycled by an unrelated live process,
|
|
256
337
|
// and refusing to break left waiters stuck until timeout (stale-lock flake).
|
|
257
338
|
if (holderPid !== process.pid && !isProcessAlive(holderPid)) {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
339
|
+
stealIfTokenMatches(
|
|
340
|
+
lockPath,
|
|
341
|
+
String(holder?.token ?? ""),
|
|
342
|
+
`deadPid holder=${holderPid}`,
|
|
343
|
+
rawContent,
|
|
344
|
+
);
|
|
264
345
|
return;
|
|
265
346
|
}
|
|
266
347
|
|
|
@@ -281,12 +362,12 @@ function breakStaleLock(lockPath) {
|
|
|
281
362
|
}
|
|
282
363
|
if (liveStart == null || !Number.isFinite(liveStart) || liveStart <= 0) return;
|
|
283
364
|
if (liveStart - expectedStart > STARTTIME_TOLERANCE_MS) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
365
|
+
stealIfTokenMatches(
|
|
366
|
+
lockPath,
|
|
367
|
+
String(holder?.token ?? ""),
|
|
368
|
+
`pidRecycled holder=${holderPid}`,
|
|
369
|
+
rawContent,
|
|
370
|
+
);
|
|
290
371
|
}
|
|
291
372
|
}
|
|
292
373
|
}
|
|
@@ -355,3 +436,64 @@ export function withBatchStateLock(projectRoot, fn, options = {}) {
|
|
|
355
436
|
}
|
|
356
437
|
}
|
|
357
438
|
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Async twin of `withBatchStateLock` for event-loop callers (SP-797 / #302):
|
|
442
|
+
* same acquire loop, stale breaking, token release, and re-entrancy, but the
|
|
443
|
+
* contention wait yields via `node:timers/promises` instead of blocking the
|
|
444
|
+
* thread — a CLI-held lock can no longer freeze engine heartbeats, pipe
|
|
445
|
+
* draining, and stall timers. `fn` MUST stay synchronous: no `await` between
|
|
446
|
+
* acquire and release, or the re-entrancy map breaks. Uncontended calls reach
|
|
447
|
+
* `fn` before the first `await`. Waits >1 s log one `[spine]` stderr line.
|
|
448
|
+
*
|
|
449
|
+
* @param {string} projectRoot
|
|
450
|
+
* @param {() => unknown} fn synchronous critical section
|
|
451
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
452
|
+
* @returns {Promise<unknown>} `fn`'s return value
|
|
453
|
+
*/
|
|
454
|
+
export async function withBatchStateLockAsync(projectRoot, fn, options = {}) {
|
|
455
|
+
const lockPath = batchStateLockPath(projectRoot);
|
|
456
|
+
|
|
457
|
+
// Re-entrant pass-through: nested sync/async calls from this process run directly.
|
|
458
|
+
if (heldByThisProcess.has(lockPath)) {
|
|
459
|
+
return fn();
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
463
|
+
const deadline = Date.now() + timeoutMs;
|
|
464
|
+
const token = newOwnershipToken();
|
|
465
|
+
const waitStartedAt = Date.now();
|
|
466
|
+
|
|
467
|
+
for (;;) {
|
|
468
|
+
if (tryCreateLockFile(lockPath, token)) break;
|
|
469
|
+
breakStaleLock(lockPath);
|
|
470
|
+
if (Date.now() >= deadline) {
|
|
471
|
+
throw new Error(
|
|
472
|
+
`Timed out acquiring batch-state lock (${path.relative(projectRoot, lockPath)}) ` +
|
|
473
|
+
`after ${timeoutMs}ms — another spine process may be holding it`,
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
await sleepAsync(POLL_INTERVAL_MS);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const waitedMs = Date.now() - waitStartedAt;
|
|
480
|
+
heldByThisProcess.set(lockPath, token);
|
|
481
|
+
try {
|
|
482
|
+
return fn();
|
|
483
|
+
} finally {
|
|
484
|
+
// Token-gated unlink before map clear (see `withBatchStateLock`).
|
|
485
|
+
try {
|
|
486
|
+
releaseLockFile(lockPath, token);
|
|
487
|
+
} finally {
|
|
488
|
+
heldByThisProcess.delete(lockPath);
|
|
489
|
+
if (waitedMs > 1_000) {
|
|
490
|
+
const rel = path.relative(projectRoot, lockPath);
|
|
491
|
+
try {
|
|
492
|
+
process.stderr.write(`[spine] batch-state lock wait took ${waitedMs}ms (${rel}) — another spine process held it\n`);
|
|
493
|
+
} catch {
|
|
494
|
+
/* diagnostic only — never fail a state save on stderr */
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|