@kabxx/dsh-message-revision 0.1.0 → 0.1.1

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.
@@ -1,8 +1,13 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { lstat, mkdir, open, readFile, readdir, realpath, rename, rm, unlink } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, mkdir, open, readFile, readdir, readlink, rm, statfs, unlink } from 'node:fs/promises';
3
4
  import { hostname } from 'node:os';
4
5
  import { basename, dirname, join } from 'node:path';
5
6
  import manifest from '../package.json' with { type: 'json' };
7
+ import {
8
+ isCanonicalPath, isSamePath, moveEntryDurable, pathKey, readDarwinProcessScope,
9
+ readDarwinProcessStart, readWin32BootId, readWin32ProcessCreationTime, replaceFileDurable, resolveRolloutPath,
10
+ } from './platform.js';
6
11
 
7
12
  const release = /^v\d+\.\d+\.\d+(?:-[0-9a-z.-]+)?$/iu;
8
13
  const sessionFile = /^session\.v4\.jsonl(?:\.zstd)?$/u;
@@ -10,9 +15,17 @@ const digestPattern = /^[a-f0-9]{64}$/u;
10
15
  const garbageName = /^discard-[a-f0-9-]{36}$/u;
11
16
  const preparationName = /^preparing-[a-f0-9-]{36}$/u;
12
17
  const limit = 256 * 1024 * 1024;
18
+ const streamLimit = 16 * 1024 * 1024 * 1024;
19
+ const chunkSize = 128 * 1024;
20
+ const intentLimit = 4 * 1024 * 1024;
13
21
  const ownerHost = hostname();
14
22
  const busyKey = Symbol.for('dsh-message-revision.active-transactions');
15
23
  const active = globalThis[busyKey] ??= new Set();
24
+ const retirementKey = Symbol.for('dsh-message-revision.settled-retirements');
25
+ const settledRetirements = globalThis[retirementKey] ??= new Map();
26
+ const retirementDelays = [0, 100, 500, 2000];
27
+ const cleanupQueue = [];
28
+ let cleaning = false;
16
29
 
17
30
  function assert(condition, detail) {
18
31
  if (!condition) throw new Error(detail);
@@ -28,7 +41,13 @@ function optionalStat(path) {
28
41
  async function assertDirectory(path) {
29
42
  const entry = await optionalStat(path);
30
43
  if (entry === undefined) return false;
31
- assert(entry.isDirectory() && await realpath(path) === path, 'Unsafe transaction directory');
44
+ let canonical;
45
+ try { canonical = await isCanonicalPath(path); }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT') return false;
48
+ throw error;
49
+ }
50
+ assert(entry.isDirectory() && canonical, 'Unsafe transaction directory');
32
51
  return true;
33
52
  }
34
53
 
@@ -56,12 +75,56 @@ async function writeFileDurably(path, bytes) {
56
75
 
57
76
  async function readRegular(path, max = limit) {
58
77
  const entry = await lstat(path);
59
- assert(entry.isFile() && entry.size <= max && await realpath(path) === path, 'Unsafe transaction file');
78
+ assert(entry.isFile() && entry.size <= max && await isCanonicalPath(path), 'Unsafe transaction file');
60
79
  return readFile(path);
61
80
  }
62
81
 
63
82
  const digest = data => createHash('sha256').update(data).digest('hex');
64
83
 
84
+ async function regularIdentity(path) {
85
+ const entry = await lstat(path, { bigint: true });
86
+ assert(entry.isFile() && await isCanonicalPath(path), 'Unsafe transaction file');
87
+ return entry;
88
+ }
89
+
90
+ /** Copy and hash with one bounded buffer, optionally reading just a prefix. */
91
+ async function streamFile(path, { destination, mode = 0o600, max = streamLimit, length, sourceIdentity } = {}) {
92
+ const expected = await regularIdentity(path);
93
+ requireGivenIdentity(sourceIdentity, expected);
94
+ const source = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
95
+ let target;
96
+ try {
97
+ assert(sameIdentity(fileIdentity(await source.stat({ bigint: true })), fileIdentity(expected)),
98
+ 'Transaction source changed while opening');
99
+ if (destination !== undefined) target = await open(destination, 'wx', mode);
100
+ const digest = createHash('sha256');
101
+ const buffer = Buffer.allocUnsafe(chunkSize);
102
+ let size = 0;
103
+ while (length === undefined || size < length) {
104
+ const count = length === undefined ? buffer.length : Math.min(buffer.length, length - size);
105
+ const { bytesRead } = await source.read(buffer, 0, count, null);
106
+ if (bytesRead === 0) break;
107
+ size += bytesRead;
108
+ assert(size <= max, 'Streamed transaction artifact exceeds size limit');
109
+ digest.update(buffer.subarray(0, bytesRead));
110
+ if (target !== undefined) {
111
+ for (let offset = 0; offset < bytesRead;) {
112
+ const { bytesWritten } = await target.write(buffer, offset, bytesRead - offset, null);
113
+ assert(bytesWritten > 0, 'Unable to make progress writing rewrite artifact');
114
+ offset += bytesWritten;
115
+ }
116
+ }
117
+ }
118
+ assert(length === undefined || length === size, 'Transaction artifact is shorter than its candidate');
119
+ const after = await regularIdentity(path);
120
+ assert(sameIdentity(fileIdentity(after), fileIdentity(expected)), 'Transaction source changed during streaming');
121
+ if (target !== undefined) await target.sync();
122
+ return { size, digest: digest.digest('hex') };
123
+ } finally {
124
+ try { await target?.close(); } finally { await source.close(); }
125
+ }
126
+ }
127
+
65
128
  function safeComponent(value) {
66
129
  return typeof value === 'string' && value.length > 0 && value !== '.' && value !== '..' && !/[\\/\u0000]/u.test(value);
67
130
  }
@@ -75,39 +138,149 @@ function childPath(parentPath, child) {
75
138
  'Unsafe recorded child path');
76
139
  const store = dirname(dirname(dirname(parentPath)));
77
140
  const path = join(store, child.project, child.directory, child.filename);
78
- assert(dirname(path) !== dirname(parentPath), 'Transaction cannot move its parent directory');
141
+ assert(!isSamePath(dirname(path), dirname(parentPath)), 'Transaction cannot move its parent directory');
79
142
  return path;
80
143
  }
81
144
 
82
- async function moveDirectory(from, to) {
145
+ async function moveDirectory(from, to, expectedIdentity) {
83
146
  assert(await assertDirectory(from), 'Transaction source directory disappeared');
84
147
  assert(await assertDirectory(dirname(to)), 'Transaction destination parent disappeared');
85
148
  assert(!await optionalStat(to), 'Transaction destination is already occupied');
86
- await rename(from, to);
149
+ const current = expectedIdentity && await transactionDirectoryIdentity(from);
150
+ if (expectedIdentity && current !== expectedIdentity) return false;
151
+ await moveEntryDurable(from, to);
87
152
  await syncDirectory(dirname(from));
88
- if (dirname(to) !== dirname(from)) await syncDirectory(dirname(to));
153
+ if (!isSamePath(dirname(to), dirname(from))) await syncDirectory(dirname(to));
154
+ return true;
155
+ }
156
+
157
+ async function transactionDirectoryIdentity(path) {
158
+ const entry = await lstat(path, { bigint: true }).catch(error => {
159
+ if (error.code !== 'ENOENT') throw error;
160
+ return undefined;
161
+ });
162
+ if (!entry) return undefined;
163
+ let canonical;
164
+ try { canonical = await isCanonicalPath(path); }
165
+ catch (error) {
166
+ if (error.code === 'ENOENT') return undefined;
167
+ throw error;
168
+ }
169
+ assert(entry.isDirectory() && canonical, 'Unsafe transaction directory');
170
+ return `${entry.dev}:${entry.ino}`;
89
171
  }
90
172
 
91
173
  async function removeRetiredDirectory(directory) {
92
174
  if (!await assertDirectory(directory)) return;
93
- await rm(directory, { recursive: true });
175
+ await rm(directory, process.platform === 'win32'
176
+ ? { recursive: true, maxRetries: 5, retryDelay: 50 }
177
+ : { recursive: true });
94
178
  await syncDirectory(dirname(directory));
95
179
  }
96
180
 
97
- function assertOwnerReleased(owner) {
181
+ async function listedProcessStart(pid) {
182
+ try {
183
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
184
+ // The comm field can contain spaces and parentheses. Field 22 is starttime.
185
+ const close = stat.lastIndexOf(')');
186
+ const ticks = stat.slice(close + 1).trim().split(/\s+/u)[19];
187
+ assert(close > 0 && typeof ticks === 'string' && /^\d+$/u.test(ticks), 'Cannot identify transaction owner process');
188
+ return ticks;
189
+ } catch (error) {
190
+ if (error.code === 'ENOENT' || error.code === 'ESRCH') return undefined;
191
+ throw error;
192
+ }
193
+ }
194
+
195
+ let processScope;
196
+ function readProcessScope() {
197
+ if (process.platform !== 'linux') return undefined;
198
+ return processScope ??= Promise.all([
199
+ readFile('/proc/sys/kernel/random/boot_id', 'utf8'), readlink('/proc/self/ns/pid'),
200
+ ]).then(([bootId, pidNamespace]) => ({ bootId: bootId.trim(), pidNamespace })).catch(() => undefined);
201
+ }
202
+
203
+ async function transactionOwner() {
204
+ const owner = { host: ownerHost, pid: process.pid };
205
+ if (process.platform === 'linux') {
206
+ const scope = await readProcessScope();
207
+ if (!scope) return owner;
208
+ const startTicks = await listedProcessStart(process.pid);
209
+ assert(startTicks !== undefined, 'Cannot identify current process for transaction recovery');
210
+ return { ...owner, ...scope, startTicks };
211
+ }
212
+ if (process.platform === 'darwin') {
213
+ const scope = await readDarwinProcessScope();
214
+ const darwinStartLabel = await readDarwinProcessStart(process.pid);
215
+ if (scope && darwinStartLabel) return { ...owner, ...scope, darwinStartLabel };
216
+ return owner;
217
+ }
218
+ if (process.platform === 'win32') {
219
+ const win32CreationTime = readWin32ProcessCreationTime(process.pid);
220
+ const win32BootId = readWin32BootId();
221
+ if (typeof win32CreationTime === 'string') {
222
+ return { ...owner, win32CreationTime, ...(win32BootId ? { win32BootId } : {}) };
223
+ }
224
+ return owner;
225
+ }
226
+ return owner;
227
+ }
228
+
229
+ async function assertOwnerReleased(owner) {
98
230
  assert(owner?.host === ownerHost && Number.isSafeInteger(owner.pid) && owner.pid > 0,
99
231
  'Transaction belongs to another host or has invalid ownership');
100
- if (owner.pid === process.pid) return;
101
- try { process.kill(owner.pid, 0); } catch (error) {
102
- if (error.code === 'ESRCH') return;
103
- throw error;
232
+ if (owner.bootId !== undefined || owner.pidNamespace !== undefined || owner.startTicks !== undefined) {
233
+ assert(typeof owner.bootId === 'string' && typeof owner.pidNamespace === 'string'
234
+ && typeof owner.startTicks === 'string' && /^\d+$/u.test(owner.startTicks), 'Invalid transaction process identity');
235
+ const scope = await readProcessScope();
236
+ assert(scope, 'Cannot verify transaction owner process identity');
237
+ if (scope.bootId !== owner.bootId) return;
238
+ assert(scope.pidNamespace === owner.pidNamespace, 'Transaction belongs to another PID namespace');
239
+ const startTicks = await listedProcessStart(owner.pid);
240
+ if (startTicks !== owner.startTicks || owner.pid === process.pid) return;
241
+ } else if (owner.darwinBootId !== undefined || owner.darwinStartLabel !== undefined) {
242
+ assert(typeof owner.darwinBootId === 'string' && owner.darwinBootId.length > 0
243
+ && typeof owner.darwinStartLabel === 'string' && owner.darwinStartLabel.length > 0,
244
+ 'Invalid transaction process identity');
245
+ const scope = await readDarwinProcessScope();
246
+ assert(scope, 'Cannot verify transaction owner process identity');
247
+ if (scope.darwinBootId !== owner.darwinBootId) return;
248
+ const startLabel = await readDarwinProcessStart(owner.pid);
249
+ if (startLabel === null || startLabel !== owner.darwinStartLabel || owner.pid === process.pid) return;
250
+ } else if (owner.win32CreationTime !== undefined || owner.win32BootId !== undefined) {
251
+ assert(typeof owner.win32CreationTime === 'string' && /^\d+$/u.test(owner.win32CreationTime)
252
+ && (owner.win32BootId === undefined || (typeof owner.win32BootId === 'string' && /^[a-f0-9]{32}$/u.test(owner.win32BootId))),
253
+ 'Invalid transaction process identity');
254
+ if (owner.pid === process.pid) return;
255
+ if (owner.win32BootId !== undefined) {
256
+ const currentBootId = readWin32BootId();
257
+ if (currentBootId && currentBootId !== owner.win32BootId) return;
258
+ }
259
+ const creationTime = readWin32ProcessCreationTime(owner.pid);
260
+ assert(creationTime !== undefined, 'Cannot verify transaction owner process identity');
261
+ if (creationTime === null || creationTime !== owner.win32CreationTime) return;
262
+ } else {
263
+ // Older pending journals only contain a PID. A live numeric PID cannot
264
+ // prove who owned one of those journals, so keep it recoverable on disk.
265
+ if (owner.pid === process.pid) return;
266
+ try { process.kill(owner.pid, 0); } catch (error) {
267
+ if (error.code === 'ESRCH') return;
268
+ throw error;
269
+ }
104
270
  }
105
271
  throw new Error('The process that started this rewrite is still running');
106
272
  }
107
273
 
108
274
  async function verifyChildFile(path, expected) {
109
- const bytes = await readRegular(path);
110
- assert(digest(bytes) === expected.digest, 'Recorded child data has changed');
275
+ if (expected.identity !== undefined) {
276
+ const directory = await lstat(dirname(path), { bigint: true });
277
+ const identity = await regularIdentity(path);
278
+ assert(directory.isDirectory() && String(directory.dev) === expected.directoryIdentity.dev
279
+ && String(directory.ino) === expected.directoryIdentity.ino
280
+ && sameIdentity(fileIdentity(identity), expected.identity), 'Recorded child data has changed');
281
+ return;
282
+ }
283
+ assert((await streamFile(path, { max: limit })).digest === expected.digest, 'Recorded child data has changed');
111
284
  }
112
285
 
113
286
  export async function hasPendingRewrite(parentPath) {
@@ -123,17 +296,262 @@ export async function hasPendingRewrite(parentPath) {
123
296
  return false;
124
297
  }
125
298
 
126
- /** Keep the intent immutable. Publish it and sync its directory before moving any session. */
299
+ function fileIdentity(entry) {
300
+ return {
301
+ dev: String(entry.dev), ino: String(entry.ino), size: String(entry.size),
302
+ mtimeNs: String(entry.mtimeNs), ctimeNs: String(entry.ctimeNs),
303
+ };
304
+ }
305
+
306
+ function sameIdentity(left, right) {
307
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size
308
+ && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
309
+ }
310
+
311
+ function entryRecord(entry) {
312
+ const header = entry.header ?? entry.handle?.header;
313
+ return {
314
+ id: header?.id,
315
+ parentSession: header?.parentSession,
316
+ createdAt: header?.createdAt,
317
+ project: basename(dirname(dirname(entry.path))),
318
+ directory: basename(dirname(entry.path)),
319
+ filename: basename(entry.path),
320
+ };
321
+ }
322
+
323
+ function v2ArtifactPath(journal, artifact) {
324
+ return artifact.index === 0 ? journal.parentPath : childPath(journal.parentPath, artifact);
325
+ }
326
+
327
+ function v2StoredPath(journal, artifact, kind) {
328
+ return join(journal.directory, 'artifacts', `artifact-${artifact.index}.${kind}`);
329
+ }
330
+
331
+ function requireGivenIdentity(given, actual) {
332
+ if (given !== undefined) {
333
+ assert(sameIdentity(fileIdentity(given), fileIdentity(actual)), 'Rewrite source changed since preparation');
334
+ }
335
+ }
336
+
337
+ export class RewriteJournalSpaceError extends Error {
338
+ constructor(requiredBytes, availableBytes) {
339
+ super('磁盘可用空间不足,无法暂存本次编辑的候选日志和备份。');
340
+ this.name = 'RewriteJournalSpaceError';
341
+ this.requiredBytes = requiredBytes;
342
+ this.availableBytes = availableBytes;
343
+ }
344
+ }
345
+
346
+ async function assertJournalSpace(destination, sizes, metadataBytes = intentLimit) {
347
+ const filesystem = await statfs(destination, { bigint: true });
348
+ const blockSize = filesystem.frsize > 0n ? filesystem.frsize : filesystem.bsize;
349
+ assert(blockSize > 0n && filesystem.bavail >= 0n, 'Cannot verify available transaction disk space');
350
+ const blocks = size => (size + blockSize - 1n) / blockSize;
351
+ // Allow for the intent, enclosing directories and allocation bookkeeping.
352
+ const overhead = blocks(BigInt(metadataBytes)) + BigInt(sizes.length + 4);
353
+ const required = (sizes.reduce((total, size) => total + blocks(size), overhead)) * blockSize;
354
+ const available = filesystem.bavail * blockSize;
355
+ if (required > available) throw new RewriteJournalSpaceError(required, available);
356
+ }
357
+
358
+ async function planRewriteSetCopies(parent, artifacts) {
359
+ const parentPath = parent.path;
360
+ assert(Array.isArray(artifacts) && artifacts.length > 0 && isSamePath(artifacts[0].path, parentPath), 'Parent artifact must be first');
361
+ const copies = [];
362
+ for (const [index, artifact] of artifacts.entries()) {
363
+ const record = { ...entryRecord(artifact), index };
364
+ assert(isSamePath(v2ArtifactPath({ parentPath }, record), artifact.path), 'Rewrite artifact is outside the session storage root');
365
+ assert(typeof artifact.candidatePath === 'string' && !isSamePath(artifact.candidatePath, artifact.path), 'Missing rewrite candidate');
366
+ const originalIdentity = await regularIdentity(artifact.path);
367
+ requireGivenIdentity(artifact.identity ?? (index === 0 ? parent.identity : undefined), originalIdentity);
368
+ const candidateIdentity = await regularIdentity(artifact.candidatePath);
369
+ assert(artifact.size === undefined || candidateIdentity.size === BigInt(artifact.size), 'Rewrite candidate changed since preparation');
370
+ assert(originalIdentity.size <= BigInt(streamLimit) && candidateIdentity.size <= BigInt(streamLimit),
371
+ 'Streamed transaction artifact exceeds size limit');
372
+ copies.push({ artifact, record, originalIdentity, candidateIdentity });
373
+ }
374
+ return copies;
375
+ }
376
+
377
+ async function assertRewriteSetCopiesFit(destination, copies) {
378
+ const journalDev = (await lstat(destination, { bigint: true })).dev;
379
+ assert(copies.every(({ originalIdentity }) => originalIdentity.dev === journalDev),
380
+ 'Rewrite artifacts must be on the transaction filesystem');
381
+ // Space already used by the originals and prepared candidates is reflected
382
+ // in bavail. Only their additional journal copies consume new file blocks.
383
+ const sizes = copies.flatMap(({ originalIdentity, candidateIdentity }) => [originalIdentity.size, candidateIdentity.size]);
384
+ await assertJournalSpace(destination, sizes);
385
+ return journalDev;
386
+ }
387
+
388
+ /** Allow the Host to fail early before releasing the live Agent. */
389
+ export async function assertRewriteSetSpace(parent, artifacts) {
390
+ const root = namespace(parent.path);
391
+ let destination = dirname(parent.path);
392
+ for (const path of [join(destination, 'plugins'), dirname(root), root, join(root, `v${manifest.version}`)]) {
393
+ if (!await assertDirectory(path)) break;
394
+ destination = path;
395
+ }
396
+ await assertRewriteSetCopiesFit(destination, await planRewriteSetCopies(parent, artifacts));
397
+ }
398
+
399
+ /** Prepare a durable multi-log journal under caller-held native writer locks. */
400
+ export async function prepareRewriteSetJournal(parent, children, artifacts, { messageId } = {}) {
401
+ const parentPath = parent.path;
402
+ const parentKey = pathKey(parentPath);
403
+ const header = parent.header ?? parent.handle?.header;
404
+ assert(typeof header?.id === 'string' && header.id.length > 0 && sessionFile.test(basename(parentPath)),
405
+ 'Missing parent session header or path');
406
+ assert(Array.isArray(artifacts) && artifacts.length > 0 && isSamePath(artifacts[0].path, parentPath), 'Parent artifact must be first');
407
+ const root = namespace(parentPath);
408
+ const versionPath = join(root, `v${manifest.version}`);
409
+ for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root, versionPath]) await ensureDirectory(path);
410
+ assert(!active.has(parentKey) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
411
+ active.add(parentKey);
412
+ const temporary = join(versionPath, `preparing-${randomUUID()}`);
413
+ const directory = join(versionPath, 'rewrite');
414
+ try {
415
+ const copies = await planRewriteSetCopies(parent, artifacts);
416
+ await mkdir(temporary, { mode: 0o700 });
417
+ await mkdir(join(temporary, 'artifacts'), { mode: 0o700 });
418
+ const journal = { directory: temporary, parentPath };
419
+ const intent = {
420
+ format: 2, parentId: header.id, filename: basename(parentPath), owner: await transactionOwner(),
421
+ artifacts: [], children: [],
422
+ ...(messageId === undefined ? {} : { delivery: { messageId } }),
423
+ };
424
+ const journalDev = await assertRewriteSetCopiesFit(journal.directory, copies);
425
+ for (const { artifact, record, originalIdentity, candidateIdentity } of copies) {
426
+ const candidatePath = v2StoredPath(journal, record, 'candidate');
427
+ const candidate = await streamFile(artifact.candidatePath, {
428
+ destination: candidatePath, mode: Number(originalIdentity.mode & 0o777n), sourceIdentity: candidateIdentity,
429
+ });
430
+ assert((artifact.size === undefined || candidate.size === artifact.size)
431
+ && (artifact.digest === undefined || candidate.digest === artifact.digest), 'Rewrite candidate changed since preparation');
432
+ const original = await streamFile(artifact.path, {
433
+ destination: v2StoredPath(journal, record, 'original'), sourceIdentity: originalIdentity,
434
+ });
435
+ intent.artifacts.push({
436
+ ...record,
437
+ original: { ...original, mode: Number(originalIdentity.mode & 0o777n), identity: fileIdentity(originalIdentity) },
438
+ candidate: { ...candidate, records: artifact.retained, identity: fileIdentity(await regularIdentity(candidatePath)) },
439
+ });
440
+ }
441
+ for (const child of children) {
442
+ const record = entryRecord(child);
443
+ assert(isSamePath(childPath(parentPath, record), child.path), 'Child is outside the session storage root');
444
+ const identity = await regularIdentity(child.path);
445
+ requireGivenIdentity(child.identity, identity);
446
+ const directoryIdentity = await lstat(dirname(child.path), { bigint: true });
447
+ assert(directoryIdentity.isDirectory() && directoryIdentity.dev === journalDev,
448
+ 'Withdrawn child must be on the transaction filesystem');
449
+ intent.children.push({ ...record, identity: fileIdentity(identity),
450
+ directoryIdentity: { dev: String(directoryIdentity.dev), ino: String(directoryIdentity.ino) } });
451
+ }
452
+ validateIntent(intent, { header }, parentPath);
453
+ const bytes = JSON.stringify(intent);
454
+ assert(Buffer.byteLength(bytes) <= intentLimit, 'Rewrite transaction metadata exceeds size limit');
455
+ await writeFileDurably(join(temporary, 'intent.json'), bytes);
456
+ await syncDirectory(join(temporary, 'artifacts'));
457
+ await syncDirectory(temporary);
458
+ const directoryIdentity = await transactionDirectoryIdentity(temporary);
459
+ await moveDirectory(temporary, directory);
460
+ return { directory, directoryIdentity, intent, parentPath, dshPath: parent.dshPath };
461
+ } catch (error) {
462
+ active.delete(parentKey);
463
+ await removeRetiredDirectory(temporary).catch(() => {});
464
+ throw error;
465
+ }
466
+ }
467
+
468
+ export function rewriteSetArtifactPath(journal, index = 0) {
469
+ assert(journal.intent?.format === 2 && Number.isSafeInteger(index) && journal.intent.artifacts[index], 'Unknown rewrite artifact');
470
+ return v2ArtifactPath(journal, journal.intent.artifacts[index]);
471
+ }
472
+
473
+ async function matchRewriteSetArtifact(journal, index = 0) {
474
+ const path = rewriteSetArtifactPath(journal, index);
475
+ const artifact = journal.intent.artifacts[index];
476
+ const candidate = artifact.candidate;
477
+ const original = artifact.original;
478
+ const current = await regularIdentity(path);
479
+ if (sameIdentity(fileIdentity(current), original.identity)) return { kind: 'original', current };
480
+ // A prior recovery may have restored the bytes at a new inode.
481
+ if (current.size === BigInt(original.size) && (await streamFile(path)).digest === original.digest) {
482
+ return { kind: 'original', current };
483
+ }
484
+ if (current.size >= BigInt(candidate.size)
485
+ && (await streamFile(path, { length: candidate.size })).digest === candidate.digest) {
486
+ return { kind: 'candidate', current };
487
+ }
488
+ return { kind: 'conflict', current };
489
+ }
490
+
491
+ /** Publish child candidates first so recovery can identify a partial publication. */
492
+ export async function publishRewriteSetArtifacts(journal) {
493
+ assert(journal.intent?.format === 2, 'Not a multi-log rewrite journal');
494
+ const order = [...journal.intent.artifacts.slice(1), journal.intent.artifacts[0]];
495
+ for (const artifact of order) {
496
+ const path = v2ArtifactPath(journal, artifact);
497
+ const source = v2StoredPath(journal, artifact, 'candidate');
498
+ assert(sameIdentity(fileIdentity(await regularIdentity(path)), artifact.original.identity), 'Rewrite source changed before publish');
499
+ assert(sameIdentity(fileIdentity(await regularIdentity(source)), artifact.candidate.identity), 'Rewrite candidate changed before publish');
500
+ await replaceFileDurable(source, path);
501
+ await syncDirectory(dirname(path));
502
+ await syncDirectory(dirname(source));
503
+ }
504
+ }
505
+
506
+ export async function restoreRewriteSetArtifacts(journal, { canRestoreArtifact } = {}) {
507
+ assert(journal.intent?.format === 2 && !journal.committed, 'Not an uncommitted multi-log rewrite journal');
508
+ const pending = [];
509
+ for (const artifact of journal.intent.artifacts) {
510
+ const path = v2ArtifactPath(journal, artifact);
511
+ const { kind, current } = await matchRewriteSetArtifact(journal, artifact.index);
512
+ assert(kind !== 'conflict', 'Rewrite artifact changed after publish');
513
+ if (kind !== 'candidate') continue;
514
+ const hasSuffix = current.size > BigInt(artifact.candidate.size);
515
+ const allowed = await canRestoreArtifact?.(artifact, kind, artifact.index, path);
516
+ assert(hasSuffix ? allowed === true : allowed !== false, 'Candidate artifact cannot be restored safely');
517
+ const original = v2StoredPath(journal, artifact, 'original');
518
+ const backup = await regularIdentity(original);
519
+ const restored = await streamFile(original);
520
+ assert(restored.size === artifact.original.size && restored.digest === artifact.original.digest, 'Original rewrite backup changed');
521
+ pending.push({ artifact, path, original, backup: fileIdentity(backup), current: fileIdentity(current) });
522
+ }
523
+ for (const { path, current } of pending) {
524
+ assert(sameIdentity(fileIdentity(await regularIdentity(path)), current), 'Rewrite artifact changed during recovery');
525
+ }
526
+ await restoreWithdrawnChildren(journal);
527
+ for (const { artifact, path, original, backup } of pending.reverse()) {
528
+ const openFlags = (process.platform === 'win32' ? constants.O_RDWR : constants.O_RDONLY) | (constants.O_NOFOLLOW ?? 0);
529
+ const handle = await open(original, openFlags);
530
+ try {
531
+ assert(sameIdentity(fileIdentity(await handle.stat({ bigint: true })), backup), 'Original rewrite backup changed');
532
+ if (process.platform !== 'win32') await handle.chmod(artifact.original.mode);
533
+ await handle.sync();
534
+ } finally { await handle.close(); }
535
+ // A crash after this rename can resume using the original digest to
536
+ // identify the already restored native file at its new inode.
537
+ await replaceFileDurable(original, path);
538
+ await syncDirectory(dirname(path));
539
+ await syncDirectory(dirname(original));
540
+ }
541
+ }
542
+
543
+ /** Keep the original journal API for version 1 callers and transactions. */
127
544
  export async function prepareRewriteJournal(parent, children, replacement) {
128
545
  const parentPath = parent.path;
546
+ const parentKey = pathKey(parentPath);
129
547
  const parentId = parent.handle.header.id;
130
548
  const root = namespace(parentPath);
131
549
  const versionPath = join(root, `v${manifest.version}`);
132
550
  for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root, versionPath]) {
133
551
  await ensureDirectory(path);
134
552
  }
135
- assert(!active.has(parentPath) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
136
- active.add(parentPath);
553
+ assert(!active.has(parentKey) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
554
+ active.add(parentKey);
137
555
  const temporary = join(versionPath, `preparing-${randomUUID()}`);
138
556
  const directory = join(versionPath, 'rewrite');
139
557
  try {
@@ -144,8 +562,8 @@ export async function prepareRewriteJournal(parent, children, replacement) {
144
562
  const localDirectory = basename(dirname(path));
145
563
  const { id, parentSession, createdAt } = child.handle.header;
146
564
  const record = { id, parentSession, createdAt, project, directory: localDirectory, filename: basename(path),
147
- digest: digest(await readRegular(path)) };
148
- assert(childPath(parentPath, record) === path, 'Child and parent use different storage roots');
565
+ digest: (await streamFile(path, { max: limit })).digest };
566
+ assert(isSamePath(childPath(parentPath, record), path), 'Child and parent use different storage roots');
149
567
  records.push(record);
150
568
  }
151
569
  const candidate = createHash('sha256');
@@ -153,7 +571,7 @@ export async function prepareRewriteJournal(parent, children, replacement) {
153
571
  for (const bytes of replacement.buffers) { candidate.update(bytes); size += bytes.length; }
154
572
  assert(size <= limit, 'Replacement transcript is too large');
155
573
  const intent = {
156
- format: 1, parentId, filename: basename(parentPath), owner: { host: ownerHost, pid: process.pid },
574
+ format: 1, parentId, filename: basename(parentPath), owner: await transactionOwner(),
157
575
  original: digest(replacement.original), candidate: { digest: candidate.digest('hex'), size, records: replacement.retained },
158
576
  children: records,
159
577
  };
@@ -161,10 +579,11 @@ export async function prepareRewriteJournal(parent, children, replacement) {
161
579
  await writeFileDurably(join(temporary, 'original'), replacement.original);
162
580
  await writeFileDurably(join(temporary, 'intent.json'), JSON.stringify(intent));
163
581
  await syncDirectory(temporary);
582
+ const directoryIdentity = await transactionDirectoryIdentity(temporary);
164
583
  await moveDirectory(temporary, directory);
165
- return { directory, intent, parentPath };
584
+ return { directory, directoryIdentity, intent, parentPath };
166
585
  } catch (error) {
167
- active.delete(parentPath);
586
+ active.delete(parentKey);
168
587
  // The preparation directory never contains moved children. Keep an already
169
588
  // published intent intact so the next recovery can make the same decision.
170
589
  await removeRetiredDirectory(temporary).catch(() => {});
@@ -173,7 +592,7 @@ export async function prepareRewriteJournal(parent, children, replacement) {
173
592
  }
174
593
 
175
594
  export function forgetRewriteJournal(journal) {
176
- if (journal) active.delete(journal.parentPath);
595
+ if (journal) active.delete(pathKey(journal.parentPath));
177
596
  }
178
597
 
179
598
  function childLocations(journal, entry, index) {
@@ -189,21 +608,29 @@ export async function stageWithdrawnChildren(journal) {
189
608
  }
190
609
  }
191
610
 
611
+ async function resolveChildLocation(journal, entry, index) {
612
+ const { from, to, path } = childLocations(journal, entry, index);
613
+ const original = await assertDirectory(from);
614
+ const held = await assertDirectory(to);
615
+ assert(original !== held, 'Cannot distinguish the original child directory from a conflict');
616
+ const rollout = original ? path : join(to, entry.filename);
617
+ await verifyChildFile(rollout, entry);
618
+ return { from, to, rollout, original };
619
+ }
620
+
621
+ export async function resolveRewriteSetChildPath(journal, index) {
622
+ const entry = journal.intent?.format === 2 && Number.isSafeInteger(index) && journal.intent.children[index];
623
+ assert(entry, 'Unknown withdrawn child');
624
+ return (await resolveChildLocation(journal, entry, index)).rollout;
625
+ }
626
+
192
627
  export async function restoreWithdrawnChildren(journal) {
193
628
  const restore = [];
194
629
  // Validate every move before making any. A repeat after a crash accepts an
195
630
  // already restored directory only if it still holds the exact same rollout.
196
631
  for (const [index, entry] of journal.intent.children.entries()) {
197
- const { from, to, path } = childLocations(journal, entry, index);
198
- const original = await assertDirectory(from);
199
- const held = await assertDirectory(to);
200
- assert(original !== held, 'Cannot distinguish the original child directory from a conflict');
201
- if (original) {
202
- await verifyChildFile(path, entry);
203
- } else {
204
- await verifyChildFile(join(to, entry.filename), entry);
205
- restore.push({ from, to });
206
- }
632
+ const location = await resolveChildLocation(journal, entry, index);
633
+ if (!location.original) restore.push(location);
207
634
  }
208
635
  for (const { from, to } of restore.toReversed()) await moveDirectory(to, from);
209
636
  }
@@ -213,8 +640,9 @@ export async function markRewriteCommitted(journal) {
213
640
  // candidate. Once present, recovery can only finish cleanup.
214
641
  const temporary = join(journal.directory, `commit-${randomUUID()}.tmp`);
215
642
  await writeFileDurably(temporary, Buffer.alloc(0));
216
- await rename(temporary, join(journal.directory, 'committed'));
643
+ await replaceFileDurable(temporary, join(journal.directory, 'committed'));
217
644
  await syncDirectory(journal.directory);
645
+ journal.committed = true;
218
646
  }
219
647
 
220
648
  export async function clearFailedCommitMarker(journal) {
@@ -223,25 +651,160 @@ export async function clearFailedCommitMarker(journal) {
223
651
  await syncDirectory(journal.directory);
224
652
  }
225
653
 
226
- export async function retireRewriteJournal(journal) {
654
+ function reportCleanupFailure(onCleanupError, error) {
655
+ try { onCleanupError?.(error); } catch { /* The durable directory remains recoverable. */ }
656
+ }
657
+
658
+ async function drainCleanup() {
659
+ try {
660
+ while (cleanupQueue.length > 0) {
661
+ const { garbage, onCleanupError } = cleanupQueue.shift();
662
+ await removeRetiredDirectory(garbage).catch(error => reportCleanupFailure(onCleanupError, error));
663
+ }
664
+ } finally {
665
+ cleaning = false;
666
+ }
667
+ }
668
+
669
+ export async function retireRewriteJournal(journal, { deferCleanup = false, onCleanupError } = {}) {
227
670
  const garbage = join(dirname(journal.directory), `discard-${randomUUID()}`);
228
- // Rename first. If deletion terminates partway through, startup does not
229
- // mistake the partial removal for a journal that still needs rollback.
230
- await moveDirectory(journal.directory, garbage);
231
- await removeRetiredDirectory(garbage);
671
+ // Rename first. Startup will resume cleanup of any detached directory.
672
+ if (!await moveDirectory(journal.directory, garbage, journal.directoryIdentity)) return;
673
+ if (!deferCleanup) return removeRetiredDirectory(garbage);
674
+ if (cleanupQueue.length >= 64) {
675
+ reportCleanupFailure(onCleanupError, new Error('Deferred rewrite cleanup will resume on startup'));
676
+ return;
677
+ }
678
+ cleanupQueue.push({ garbage, onCleanupError });
679
+ if (!cleaning) {
680
+ cleaning = true;
681
+ setImmediate(() => { void drainCleanup(); });
682
+ }
683
+ }
684
+
685
+ function completeSettledRetirement(path, state) {
686
+ clearTimeout(state.timer);
687
+ if (settledRetirements.get(path) === state) settledRetirements.delete(path);
688
+ }
689
+
690
+ function scheduleRetirementAttempt(path, state) {
691
+ const delay = retirementDelays[state.attempts];
692
+ if (state.timer || delay === undefined) return;
693
+ state.timer = setTimeout(() => {
694
+ state.timer = undefined;
695
+ void retrySettledRewriteRetirement(path);
696
+ }, delay);
697
+ state.timer.unref();
698
+ }
699
+
700
+ /** Remember only durable commits whose native prompt is already settled. */
701
+ export function scheduleSettledRewriteRetirement(journal, { onCleanupError } = {}) {
702
+ const { parentPath, directory, directoryIdentity, committed } = journal;
703
+ assert(committed && directoryIdentity, 'Cannot retire an unverified or unsettled transaction');
704
+ const key = pathKey(parentPath);
705
+ const known = settledRetirements.get(key);
706
+ if (known?.journal.directoryIdentity === directoryIdentity) return;
707
+ if (known) completeSettledRetirement(key, known);
708
+ const state = { journal: { directory, directoryIdentity }, onCleanupError, attempts: 0 };
709
+ settledRetirements.set(key, state);
710
+ scheduleRetirementAttempt(key, state);
711
+ }
712
+
713
+ /** Retry on edit admission as well as on the bounded background schedule. */
714
+ export async function retrySettledRewriteRetirement(path) {
715
+ const key = pathKey(path);
716
+ const state = settledRetirements.get(key);
717
+ if (!state) return;
718
+ if (state.running) return state.running;
719
+ clearTimeout(state.timer);
720
+ state.timer = undefined;
721
+ state.attempts++;
722
+ state.running = (async () => {
723
+ try {
724
+ const { journal, onCleanupError } = state;
725
+ if (await transactionDirectoryIdentity(journal.directory) === journal.directoryIdentity) {
726
+ assert((await readRegular(join(journal.directory, 'committed'), 0)).length === 0, 'Invalid transaction commit marker');
727
+ await retireRewriteJournal(journal, { deferCleanup: true, onCleanupError });
728
+ }
729
+ completeSettledRetirement(key, state);
730
+ } catch (error) {
731
+ if (state.attempts >= retirementDelays.length) reportCleanupFailure(state.onCleanupError, error);
732
+ if (settledRetirements.get(key) === state) scheduleRetirementAttempt(key, state);
733
+ }
734
+ })();
735
+ try { await state.running; } finally { state.running = undefined; }
736
+ }
737
+
738
+ function validIdentity(identity, keys = ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs']) {
739
+ return identity !== null && typeof identity === 'object'
740
+ && keys.every(key => typeof identity[key] === 'string' && /^-?\d{1,40}$/u.test(identity[key]));
741
+ }
742
+
743
+ function validFile(record) {
744
+ return Number.isSafeInteger(record?.size) && record.size > 0 && record.size <= streamLimit
745
+ && typeof record.digest === 'string' && digestPattern.test(record.digest)
746
+ && validIdentity(record.identity) && BigInt(record.identity.size) === BigInt(record.size);
747
+ }
748
+
749
+ function validChildRecord(record) {
750
+ return typeof record?.id === 'string' && record.id.length > 0 && typeof record.parentSession === 'string'
751
+ && record.parentSession.length > 0 && record.parentSession !== record.id && Number.isSafeInteger(record.createdAt)
752
+ && record.createdAt >= 0;
753
+ }
754
+
755
+ function validateSetIntent(intent, path) {
756
+ assert(Array.isArray(intent.artifacts) && intent.artifacts.length > 0 && Array.isArray(intent.children),
757
+ 'Invalid multi-log transaction artifacts');
758
+ const ids = new Set();
759
+ const paths = new Set();
760
+ const withdrawnIds = new Set(intent.children.map(record => record?.id));
761
+ const seenWithdrawn = new Set();
762
+ for (const [index, artifact] of intent.artifacts.entries()) {
763
+ assert(artifact?.index === index && validFile(artifact.original) && validFile(artifact.candidate)
764
+ && Number.isInteger(artifact.original.mode) && artifact.original.mode >= 0 && artifact.original.mode <= 0o777
765
+ && Number.isSafeInteger(artifact.candidate.records) && artifact.candidate.records >= 0,
766
+ 'Invalid multi-log artifact metadata');
767
+ if (index === 0) {
768
+ assert(artifact.id === intent.parentId && artifact.filename === basename(path), 'Invalid parent artifact metadata');
769
+ } else {
770
+ assert(validChildRecord(artifact) && !withdrawnIds.has(artifact.parentSession), 'Invalid child artifact metadata');
771
+ }
772
+ const directory = pathKey(dirname(index === 0 ? path : childPath(path, artifact)));
773
+ assert(!ids.has(artifact.id) && !paths.has(directory), 'Duplicate transaction identifier or path');
774
+ ids.add(artifact.id);
775
+ paths.add(directory);
776
+ }
777
+ for (const child of intent.children) {
778
+ assert(validChildRecord(child) && validIdentity(child.identity) && validIdentity(child.directoryIdentity, ['dev', 'ino'])
779
+ && child.identity.dev === child.directoryIdentity.dev
780
+ && (!withdrawnIds.has(child.parentSession) || seenWithdrawn.has(child.parentSession)), 'Invalid recorded child lineage');
781
+ const directory = pathKey(dirname(childPath(path, child)));
782
+ assert(!ids.has(child.id) && !paths.has(directory), 'Duplicate transaction identifier or path');
783
+ ids.add(child.id);
784
+ seenWithdrawn.add(child.id);
785
+ paths.add(directory);
786
+ }
232
787
  }
233
788
 
234
789
  function validateIntent(intent, snapshot, path) {
235
790
  const { id } = snapshot.header;
236
- assert(intent?.format === 1 && intent.parentId === id && intent.filename === basename(path), 'Unknown transaction format or parent');
791
+ assert((intent?.format === 1 || intent?.format === 2) && intent.parentId === id && intent.filename === basename(path), 'Unknown transaction format or parent');
792
+ if (intent.format === 2) {
793
+ if (intent.delivery !== undefined) {
794
+ const { messageId } = intent.delivery ?? {};
795
+ assert(typeof messageId === 'string' && messageId.length > 0 && messageId.length <= 2048,
796
+ 'Invalid pending delivery metadata');
797
+ }
798
+ return validateSetIntent(intent, path);
799
+ }
237
800
  assert(digestPattern.test(intent.original) && digestPattern.test(intent.candidate?.digest)
238
801
  && Number.isSafeInteger(intent.candidate.size) && intent.candidate.size > 0 && intent.candidate.size <= limit
239
802
  && Number.isSafeInteger(intent.candidate.records) && intent.candidate.records >= 0 && Array.isArray(intent.children),
240
803
  'Invalid transaction hashes or boundaries');
241
804
  const ids = new Set([id]);
242
- const paths = new Set([dirname(path)]);
805
+ const paths = new Set([pathKey(dirname(path))]);
243
806
  for (const child of intent.children) {
244
- const directory = dirname(childPath(path, child));
807
+ const directory = pathKey(dirname(childPath(path, child)));
245
808
  assert(typeof child.id === 'string' && child.id.length > 0 && !ids.has(child.id)
246
809
  && ids.has(child.parentSession) && !paths.has(directory) && Number.isSafeInteger(child.createdAt)
247
810
  && digestPattern.test(child.digest), 'Invalid recorded child lineage');
@@ -252,28 +815,40 @@ function validateIntent(intent, snapshot, path) {
252
815
 
253
816
  /** Scan only artifacts located by the native persistence backend. */
254
817
  export async function readRewriteJournals(snapshot) {
255
- const path = snapshot?.location?.path;
256
- if (snapshot?.location?.kind !== 'jsonl' || typeof path !== 'string' || !sessionFile.test(basename(path))
257
- || !await assertDirectory(dirname(path))) return [];
818
+ const dshPath = snapshot?.location?.path;
819
+ if (snapshot?.location?.kind !== 'jsonl' || typeof dshPath !== 'string' || !sessionFile.test(basename(dshPath))) return [];
820
+ const path = await resolveRolloutPath(dshPath).catch(error => {
821
+ if (error.code !== 'ENOENT') throw error;
822
+ return undefined;
823
+ });
824
+ if (!path || !await assertDirectory(dirname(path))) return [];
258
825
  const root = namespace(path);
259
826
  for (const directory of [join(dirname(path), 'plugins'), dirname(root), root]) {
260
827
  if (!await assertDirectory(directory)) return [];
261
828
  }
262
- if (active.has(path)) return [];
829
+ if (active.has(pathKey(path))) return [];
263
830
  const journals = [];
264
831
  for (const name of await readdir(root)) {
265
832
  if (!release.test(name)) continue;
266
833
  const versionPath = join(root, name);
267
834
  if (!await assertDirectory(versionPath)) continue;
268
835
  const directory = join(versionPath, 'rewrite');
269
- if (await assertDirectory(directory)) {
270
- const intent = JSON.parse(await readRegular(join(directory, 'intent.json'), 4 * 1024 * 1024));
836
+ const directoryIdentity = await transactionDirectoryIdentity(directory);
837
+ if (!directoryIdentity) continue;
838
+ try {
839
+ const intent = JSON.parse(await readRegular(join(directory, 'intent.json'), intentLimit));
271
840
  validateIntent(intent, snapshot, path);
272
- assertOwnerReleased(intent.owner);
841
+ await assertOwnerReleased(intent.owner);
273
842
  const marker = join(directory, 'committed');
274
843
  const committed = await optionalStat(marker) !== undefined;
275
844
  if (committed) assert((await readRegular(marker, 0)).length === 0, 'Invalid transaction commit marker');
276
- journals.push({ directory, intent, parentPath: path, committed });
845
+ if (await transactionDirectoryIdentity(directory) === directoryIdentity) {
846
+ journals.push({ directory, directoryIdentity, intent, parentPath: path, dshPath, committed });
847
+ }
848
+ } catch (error) {
849
+ // Retirement atomically moves the entire directory out of this path.
850
+ // A missing file in a directory that still exists remains an error.
851
+ if (error.code !== 'ENOENT' || await transactionDirectoryIdentity(directory) === directoryIdentity) throw error;
277
852
  }
278
853
  }
279
854
  assert(journals.length <= 1, 'Multiple unresolved rewrites for the same session');
@@ -310,10 +885,11 @@ export async function readRewriteOriginal(journal) {
310
885
  return original;
311
886
  }
312
887
 
313
- export async function matchJournalRevision(journal) {
314
- const raw = await readRegular(journal.parentPath);
315
- if (digest(raw) === journal.intent.original) return 'original';
888
+ export async function matchJournalRevision(journal, index = 0) {
889
+ if (journal.intent?.format === 2) return (await matchRewriteSetArtifact(journal, index)).kind;
890
+ if ((await streamFile(journal.parentPath, { max: limit })).digest === journal.intent.original) return 'original';
316
891
  const { size, digest: hash } = journal.intent.candidate;
317
- if (raw.length >= size && digest(raw.subarray(0, size)) === hash) return 'candidate';
892
+ const current = await regularIdentity(journal.parentPath);
893
+ if (current.size >= BigInt(size) && (await streamFile(journal.parentPath, { length: size })).digest === hash) return 'candidate';
318
894
  return 'conflict';
319
895
  }