@lark-apaas/fullstack-cli 1.1.59-alpha.20260720184331 → 1.1.59-alpha.20260721012847

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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
+ const { spawnSync: nodeSpawnSync } = require('child_process');
5
6
 
6
7
  const DEFAULT_OUTBOX_ROOT = '/tmp/event/miaoda-preview-phase/v1';
7
8
  const MAX_EVENT_BYTES = 16 * 1024;
@@ -10,10 +11,185 @@ const DEFAULT_MAX_ROOT_BYTES = 64 * 1024 * 1024;
10
11
  const DEFAULT_MAX_ROOT_DIRECTORIES = 128;
11
12
  const DEFAULT_MAX_ROOT_SCAN_DIRECTORIES = 256;
12
13
  const DEFAULT_MAX_RUN_SCAN_ENTRIES = 64;
14
+ const DEFAULT_MAX_FALLBACK_FILES = 32;
15
+ const DEFAULT_MAX_FALLBACK_BYTES = 2 * 1024 * 1024;
16
+ const DEFAULT_MAX_FALLBACK_EVENTS = 256;
17
+ const MAX_FALLBACK_RECORD_BYTES = MAX_EVENT_BYTES + 4 * 1024;
18
+ const FALLBACK_TERMINAL_RESERVE_BYTES = 1024;
13
19
  const RUN_ID_PATTERN = /^prv_[A-Za-z0-9_-]{1,60}$/;
14
20
  const STATE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
21
+ const PRODUCER_INSTANCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
22
+ const FALLBACK_SESSION_ID_PATTERN = /^pfs_[a-f0-9]{32}$/;
15
23
  const PROCESS_START_TICKS_PATTERN = /^\d+$/;
16
24
  const PRODUCER_EPOCH_PATTERN = /^ppe_[a-f0-9]{32}$/;
25
+ const INSTANCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/;
26
+ const PRODUCER_REGISTER_URL = 'http://127.0.0.1:8091/shell/exec';
27
+ const PRODUCER_REGISTER_ATTEMPTS = 2;
28
+ const PRODUCER_REGISTER_CURL_TIMEOUT_SECONDS = '0.35';
29
+ const PRODUCER_REGISTER_PROCESS_TIMEOUT_MS = 400;
30
+ const PRODUCER_REGISTER_MAX_RESPONSE_BYTES = 64 * 1024;
31
+ const TRANSIENT_ERRNO_CODES = new Set([
32
+ 'EAGAIN',
33
+ 'EINTR',
34
+ 'EBUSY',
35
+ 'EMFILE',
36
+ 'ENFILE',
37
+ 'ENOMEM',
38
+ ]);
39
+ const MAX_TRANSIENT_ATTEMPTS = 3;
40
+
41
+ function producerRegistrationError(code, message, cause) {
42
+ const error = new Error(message, cause == null ? undefined : { cause });
43
+ error.code = code;
44
+ return error;
45
+ }
46
+
47
+ function validateProducerRegistrationResponse(response, request) {
48
+ const commonInvalid =
49
+ response?.protocol !== 'preview-phase-outbox-v1' ||
50
+ response.capability_status !== 'supported' ||
51
+ response.generation !== request.generation ||
52
+ response.producer_epoch !== request.producer_epoch ||
53
+ response.producer_generation !== request.generation;
54
+ const rejected = response?.registration_status === 'rejected';
55
+ const rejectedInvalid =
56
+ rejected &&
57
+ (response.registration_reason !== 'stale_epoch' ||
58
+ response.writer_active === true ||
59
+ response.sealed !== true ||
60
+ response.fallback_required !== true ||
61
+ response.fallback_session_id !== request.fallback_session_id ||
62
+ response.fallback_final_seq !== 1 ||
63
+ response.producer_state !== 'rejected' ||
64
+ request.rejected_event == null);
65
+ const acceptedInvalid =
66
+ !rejected &&
67
+ ((response?.registration_status != null &&
68
+ response.registration_status !== 'accepted') ||
69
+ response.writer_active !== true ||
70
+ response.producer_state !== 'active');
71
+ if (commonInvalid || rejectedInvalid || acceptedInvalid) {
72
+ throw producerRegistrationError(
73
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
74
+ 'invalid preview phase producer registration response'
75
+ );
76
+ }
77
+ return response;
78
+ }
79
+
80
+ function registerPreviewPhaseProducerViaShellServer(
81
+ request,
82
+ spawnSync = nodeSpawnSync
83
+ ) {
84
+ const wireRequest = {
85
+ phase_outbox: {
86
+ protocol: 'preview-phase-outbox-v1',
87
+ operation: 'register',
88
+ run_id: request.run_id,
89
+ generation: request.generation,
90
+ expected_instance_id: request.expected_instance_id,
91
+ producer_epoch: request.producer_epoch,
92
+ writer_instance_id: request.writer_instance_id,
93
+ pid: request.pid,
94
+ process_start_ticks: request.process_start_ticks,
95
+ ...(request.rejected_event == null
96
+ ? {}
97
+ : {
98
+ producer_instance_id: request.producer_instance_id,
99
+ fallback_session_id: request.fallback_session_id,
100
+ rejected_event: request.rejected_event,
101
+ }),
102
+ },
103
+ };
104
+ const result = spawnSync(
105
+ 'curl',
106
+ [
107
+ '--silent',
108
+ '--show-error',
109
+ '--connect-timeout',
110
+ PRODUCER_REGISTER_CURL_TIMEOUT_SECONDS,
111
+ '--max-time',
112
+ PRODUCER_REGISTER_CURL_TIMEOUT_SECONDS,
113
+ '--request',
114
+ 'POST',
115
+ '--header',
116
+ 'Content-Type: application/json',
117
+ '--data-binary',
118
+ '@-',
119
+ PRODUCER_REGISTER_URL,
120
+ ],
121
+ {
122
+ input: Buffer.from(JSON.stringify(wireRequest), 'utf8'),
123
+ encoding: 'utf8',
124
+ timeout: PRODUCER_REGISTER_PROCESS_TIMEOUT_MS,
125
+ maxBuffer: PRODUCER_REGISTER_MAX_RESPONSE_BYTES,
126
+ windowsHide: true,
127
+ }
128
+ );
129
+ if (result?.error) {
130
+ const code =
131
+ result.error.code === 'ETIMEDOUT'
132
+ ? 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN'
133
+ : 'PREVIEW_PHASE_PRODUCER_REGISTRATION_UNAVAILABLE';
134
+ throw producerRegistrationError(
135
+ code,
136
+ `preview phase producer registration transport failed: ${result.error.message}`,
137
+ result.error
138
+ );
139
+ }
140
+ if (result?.signal || result?.status === 28) {
141
+ throw producerRegistrationError(
142
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
143
+ 'preview phase producer registration acknowledgement timed out'
144
+ );
145
+ }
146
+ if (result?.status !== 0) {
147
+ throw producerRegistrationError(
148
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_UNAVAILABLE',
149
+ `preview phase producer registration transport exited ${String(result?.status)}`
150
+ );
151
+ }
152
+ let envelope;
153
+ try {
154
+ envelope = JSON.parse(result.stdout || '');
155
+ } catch (error) {
156
+ throw producerRegistrationError(
157
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
158
+ 'preview phase producer registration returned invalid JSON',
159
+ error
160
+ );
161
+ }
162
+ if (envelope?.success !== true || envelope?.data?.success !== true) {
163
+ const detail = envelope?.data?.error || envelope?.message || 'rejected';
164
+ const detailText = String(detail);
165
+ let code = 'PREVIEW_PHASE_PRODUCER_REGISTRATION_REJECTED';
166
+ if (detailText.includes('registration acknowledgement unknown')) {
167
+ code = 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN';
168
+ } else if (detailText.includes('producer epoch already belongs')) {
169
+ code = 'PREVIEW_PHASE_PRODUCER_EPOCH_CONFLICT';
170
+ } else if (
171
+ detailText.includes('publish preview phase canonical registration') ||
172
+ detailText.includes('conflicts with canonical run')
173
+ ) {
174
+ code = 'PREVIEW_PHASE_RUN_CONFLICT';
175
+ }
176
+ throw producerRegistrationError(
177
+ code,
178
+ `preview phase producer registration rejected: ${detailText}`
179
+ );
180
+ }
181
+ let response;
182
+ try {
183
+ response = JSON.parse(envelope.data.output || '');
184
+ } catch (error) {
185
+ throw producerRegistrationError(
186
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
187
+ 'preview phase producer registration acknowledgement was invalid',
188
+ error
189
+ );
190
+ }
191
+ return validateProducerRegistrationResponse(response, request);
192
+ }
17
193
 
18
194
  function readLinuxProcessStartTicks(fileSystem, pid) {
19
195
  try {
@@ -47,13 +223,46 @@ function assertSafeDirectory(fileSystem, directoryPath) {
47
223
  fileSystem.chmodSync(directoryPath, 0o700);
48
224
  }
49
225
 
226
+ // Canonical generations are published only by the staging-directory rename.
227
+ // Every later lookup must be existing-only: recreating a path that the
228
+ // controller just quarantined would hide the durable generation and could
229
+ // manufacture a second, unrelated canonical lifecycle.
230
+ function assertExistingSafeDirectory(fileSystem, directoryPath) {
231
+ const stat = fileSystem.lstatSync(directoryPath);
232
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
233
+ throw new Error(`unsafe preview phase outbox path: ${directoryPath}`);
234
+ }
235
+ fileSystem.chmodSync(directoryPath, 0o700);
236
+ }
237
+
238
+ function createFallbackSessionID(randomUUID = require('crypto').randomUUID) {
239
+ const sessionID = `pfs_${String(randomUUID())
240
+ .replaceAll('-', '')
241
+ .toLowerCase()}`;
242
+ if (!FALLBACK_SESSION_ID_PATTERN.test(sessionID)) {
243
+ throw new Error('invalid preview phase fallback session UUID');
244
+ }
245
+ return sessionID;
246
+ }
247
+
50
248
  function createPreviewPhaseOutbox(options) {
51
249
  const fileSystem = options.fs || fs;
52
250
  const root = options.root || DEFAULT_OUTBOX_ROOT;
53
251
  const randomUUID = options.random_uuid || require('crypto').randomUUID;
54
252
  const now = options.now || Date.now;
55
253
  const writerInstanceID = options.writer_instance_id || randomUUID();
254
+ const producerInstanceID = options.producer_instance_id || writerInstanceID;
255
+ const fallbackSessionID =
256
+ options.fallback_session_id || createFallbackSessionID();
56
257
  const producerEpoch = options.producer_epoch;
258
+ const expectedInstanceID = options.expected_instance_id;
259
+ const registerProducer =
260
+ options.register_producer ||
261
+ (request =>
262
+ registerPreviewPhaseProducerViaShellServer(
263
+ request,
264
+ options.spawn_sync || nodeSpawnSync
265
+ ));
57
266
  const getProcessStartTicks =
58
267
  options.get_process_start_ticks ||
59
268
  (pid => readLinuxProcessStartTicks(fileSystem, pid));
@@ -70,15 +279,36 @@ function createPreviewPhaseOutbox(options) {
70
279
  options.max_root_scan_directories ?? DEFAULT_MAX_ROOT_SCAN_DIRECTORIES;
71
280
  const maxRunScanEntries =
72
281
  options.max_run_scan_entries ?? DEFAULT_MAX_RUN_SCAN_ENTRIES;
282
+ const maxFallbackFiles =
283
+ options.max_fallback_files ??
284
+ Math.min(DEFAULT_MAX_FALLBACK_FILES, maxRunScanEntries);
285
+ const maxFallbackBytes =
286
+ options.max_fallback_bytes ?? DEFAULT_MAX_FALLBACK_BYTES;
287
+ const maxFallbackEvents =
288
+ options.max_fallback_events ?? DEFAULT_MAX_FALLBACK_EVENTS;
289
+ const maxFallbackRecordBytes =
290
+ options.max_fallback_record_bytes ?? MAX_FALLBACK_RECORD_BYTES;
73
291
  if (!RUN_ID_PATTERN.test(options.run_id || '')) {
74
292
  throw new Error('invalid preview run_id for phase outbox');
75
293
  }
76
294
  if (!PRODUCER_EPOCH_PATTERN.test(producerEpoch || '')) {
77
295
  throw new Error('invalid preview phase producer_epoch');
78
296
  }
297
+ if (!INSTANCE_ID_PATTERN.test(expectedInstanceID || '')) {
298
+ throw new Error('invalid preview phase expected_instance_id');
299
+ }
300
+ if (typeof registerProducer !== 'function') {
301
+ throw new Error('invalid preview phase producer registrar');
302
+ }
79
303
  if (!STATE_ID_PATTERN.test(writerInstanceID)) {
80
304
  throw new Error('invalid preview phase writer_instance_id');
81
305
  }
306
+ if (!STATE_ID_PATTERN.test(producerInstanceID)) {
307
+ throw new Error('invalid preview phase producer_instance_id');
308
+ }
309
+ if (!FALLBACK_SESSION_ID_PATTERN.test(fallbackSessionID)) {
310
+ throw new Error('invalid preview phase fallback_session_id');
311
+ }
82
312
  if (!PROCESS_START_TICKS_PATTERN.test(currentProcessStartTicks || '')) {
83
313
  throw new Error('invalid preview phase process_start_ticks');
84
314
  }
@@ -100,13 +330,41 @@ function createPreviewPhaseOutbox(options) {
100
330
  if (!Number.isSafeInteger(maxRunScanEntries) || maxRunScanEntries <= 0) {
101
331
  throw new Error('invalid preview phase max_run_scan_entries');
102
332
  }
103
- const runDir = path.join(root, options.run_id);
104
- const eventsPath = path.join(runDir, 'events.jsonl');
105
- const metaPath = path.join(runDir, 'meta.json');
106
- const writerLockPath = path.join(runDir, 'writer.lock');
107
- const sealPath = path.join(runDir, 'sealed.json');
108
- const degradedPath = path.join(runDir, 'degraded.json');
109
- const quiesceRequestPath = path.join(runDir, 'quiesce.request.json');
333
+ if (
334
+ !Number.isSafeInteger(maxFallbackFiles) ||
335
+ maxFallbackFiles <= 0 ||
336
+ maxFallbackFiles > maxRunScanEntries
337
+ ) {
338
+ throw new Error('invalid preview phase max_fallback_files');
339
+ }
340
+ if (!Number.isSafeInteger(maxFallbackBytes) || maxFallbackBytes <= 0) {
341
+ throw new Error('invalid preview phase max_fallback_bytes');
342
+ }
343
+ if (!Number.isSafeInteger(maxFallbackEvents) || maxFallbackEvents <= 0) {
344
+ throw new Error('invalid preview phase max_fallback_events');
345
+ }
346
+ if (
347
+ !Number.isSafeInteger(maxFallbackRecordBytes) ||
348
+ maxFallbackRecordBytes <= 0
349
+ ) {
350
+ throw new Error('invalid preview phase max_fallback_record_bytes');
351
+ }
352
+ const canonicalRunDir = path.join(root, options.run_id);
353
+ const stagingName = `.staging-${process.pid}-${writerInstanceID}`;
354
+ const stagingRunDir = path.join(root, stagingName);
355
+ let runDir = canonicalRunDir;
356
+ let eventsPath = path.join(runDir, 'events.jsonl');
357
+ let metaPath = path.join(runDir, 'meta.json');
358
+ let writerLockPath = path.join(runDir, 'writer.lock');
359
+ let sealPath = path.join(runDir, 'sealed.json');
360
+ let degradedPath = path.join(runDir, 'degraded.json');
361
+ let fallbackIntentPath = path.join(runDir, 'fallback.intent.json');
362
+ let quiesceRequestPath = path.join(runDir, 'quiesce.request.json');
363
+ let unboundFallbackPath = path.join(runDir, 'producer.unbound.json');
364
+ const fallbackSpoolPath = path.join(
365
+ canonicalRunDir,
366
+ `fallback-${fallbackSessionID}.jsonl`
367
+ );
110
368
  const producerEpochMarkerPath = path.join(
111
369
  root,
112
370
  `producer-epoch-${producerEpoch}.json`
@@ -114,6 +372,7 @@ function createPreviewPhaseOutbox(options) {
114
372
  let recovered = false;
115
373
  let metadata = null;
116
374
  let writerLockOwned = false;
375
+ let writerLockDirectory = null;
117
376
  let eventsFD = null;
118
377
  let committedBytes = null;
119
378
  let degraded = false;
@@ -123,8 +382,49 @@ function createPreviewPhaseOutbox(options) {
123
382
  let closeResult = false;
124
383
  let producerMarkerActive = false;
125
384
  let producerMarkerTerminal = false;
385
+ let producerRegistrationDurable = false;
386
+ let producerRegistrationAttemptCount = 0;
387
+ let producerRegistrationLastError = null;
126
388
  let producerStartedAtMs = null;
127
389
  let producerTerminalAtMs = null;
390
+ let canonicalPublicationDurable = false;
391
+ let everOwnedCanonicalWriter = false;
392
+ let fallbackFD = null;
393
+ let fallbackBytes = 0;
394
+ let fallbackSeq = 0;
395
+ let fallbackStarted = false;
396
+ let fallbackSealed = false;
397
+ let fallbackFailed = false;
398
+ let fallbackCreatedAt = null;
399
+ function selectRunDirectory(directoryPath) {
400
+ if (runDir !== directoryPath) {
401
+ if (eventsFD != null) {
402
+ throw new Error(
403
+ 'cannot switch preview phase directory with an open events fd'
404
+ );
405
+ }
406
+ metadata = null;
407
+ recovered = false;
408
+ committedBytes = null;
409
+ }
410
+ runDir = directoryPath;
411
+ eventsPath = path.join(runDir, 'events.jsonl');
412
+ metaPath = path.join(runDir, 'meta.json');
413
+ writerLockPath = path.join(runDir, 'writer.lock');
414
+ sealPath = path.join(runDir, 'sealed.json');
415
+ degradedPath = path.join(runDir, 'degraded.json');
416
+ fallbackIntentPath = path.join(runDir, 'fallback.intent.json');
417
+ quiesceRequestPath = path.join(runDir, 'quiesce.request.json');
418
+ unboundFallbackPath = path.join(runDir, 'producer.unbound.json');
419
+ }
420
+
421
+ function ownsSelectedWriterLock() {
422
+ return writerLockOwned && writerLockDirectory === runDir;
423
+ }
424
+
425
+ function isTransientFilesystemError(error) {
426
+ return TRANSIENT_ERRNO_CODES.has(error?.code);
427
+ }
128
428
 
129
429
  function rootQuotaError(message) {
130
430
  const error = new Error(message);
@@ -245,12 +545,12 @@ function createPreviewPhaseOutbox(options) {
245
545
  return value;
246
546
  }
247
547
 
248
- function syncRunDirectory() {
548
+ function syncDirectory(directoryPath) {
249
549
  const flags =
250
550
  fs.constants.O_RDONLY |
251
551
  (fs.constants.O_DIRECTORY || 0) |
252
552
  (fs.constants.O_NOFOLLOW || 0);
253
- const fd = fileSystem.openSync(runDir, flags);
553
+ const fd = fileSystem.openSync(directoryPath, flags);
254
554
  try {
255
555
  fileSystem.fsyncSync(fd);
256
556
  } finally {
@@ -258,6 +558,10 @@ function createPreviewPhaseOutbox(options) {
258
558
  }
259
559
  }
260
560
 
561
+ function syncRunDirectory() {
562
+ syncDirectory(runDir);
563
+ }
564
+
261
565
  function syncRootDirectory() {
262
566
  const flags =
263
567
  fs.constants.O_RDONLY |
@@ -328,7 +632,9 @@ function createPreviewPhaseOutbox(options) {
328
632
  if (fd != null) {
329
633
  try {
330
634
  fileSystem.closeSync(fd);
331
- } catch {}
635
+ } catch {
636
+ // Best-effort fd cleanup.
637
+ }
332
638
  }
333
639
  try {
334
640
  fileSystem.rmSync(tempPath, { force: true });
@@ -408,69 +714,21 @@ function createPreviewPhaseOutbox(options) {
408
714
 
409
715
  function publishActiveProducerMarker() {
410
716
  if (producerMarkerActive) return;
411
- if (!metadata || !writerLockOwned) {
717
+ if (
718
+ !producerRegistrationDurable ||
719
+ !metadata ||
720
+ !ownsSelectedWriterLock()
721
+ ) {
412
722
  throw new Error(
413
- 'preview phase producer marker requires writer ownership'
723
+ 'preview phase producer marker requires authoritative registration'
414
724
  );
415
725
  }
416
- if (fileSystem.existsSync(producerEpochMarkerPath)) {
417
- const existing = readAndValidateProducerMarker();
418
- if (!markerBelongsToThisWriter(existing) || existing.state !== 'active') {
419
- throw producerMarkerConflict();
420
- }
421
- producerStartedAtMs = existing.started_at_ms;
422
- producerMarkerActive = true;
423
- return;
424
- }
425
-
426
- producerStartedAtMs = producerStartedAtMs ?? now();
427
- const marker = buildProducerMarker('active');
428
- const tempPath = path.join(
429
- root,
430
- `.producer-epoch.${producerEpoch}.${process.pid}.${writerInstanceID}.tmp`
431
- );
432
- let fd = null;
433
- try {
434
- const flags =
435
- fs.constants.O_CREAT |
436
- fs.constants.O_EXCL |
437
- fs.constants.O_WRONLY |
438
- (fs.constants.O_NOFOLLOW || 0);
439
- fd = fileSystem.openSync(tempPath, flags, 0o600);
440
- writeAll(fd, Buffer.from(`${JSON.stringify(marker)}\n`, 'utf8'));
441
- fileSystem.fsyncSync(fd);
442
- fileSystem.closeSync(fd);
443
- fd = null;
444
- try {
445
- fileSystem.linkSync(tempPath, producerEpochMarkerPath);
446
- syncRootDirectory();
447
- } catch (error) {
448
- if (error?.code !== 'EEXIST') throw error;
449
- const existing = readAndValidateProducerMarker();
450
- if (
451
- !markerBelongsToThisWriter(existing) ||
452
- existing.state !== 'active'
453
- ) {
454
- throw producerMarkerConflict();
455
- }
456
- producerStartedAtMs = existing.started_at_ms;
457
- }
458
- producerMarkerActive = true;
459
- } finally {
460
- if (fd != null) {
461
- try {
462
- fileSystem.closeSync(fd);
463
- } catch {}
464
- }
465
- let tempRemoved = false;
466
- try {
467
- fileSystem.rmSync(tempPath, { force: true });
468
- tempRemoved = true;
469
- } catch {
470
- // A stale temp file is never accepted as lifecycle proof.
471
- }
472
- if (tempRemoved) syncRootDirectory();
726
+ const existing = readAndValidateProducerMarker();
727
+ if (!markerBelongsToThisWriter(existing) || existing.state !== 'active') {
728
+ throw producerMarkerConflict();
473
729
  }
730
+ producerStartedAtMs = existing.started_at_ms;
731
+ producerMarkerActive = true;
474
732
  }
475
733
 
476
734
  function publishTerminalProducerMarker() {
@@ -513,7 +771,9 @@ function createPreviewPhaseOutbox(options) {
513
771
  if (fd != null) {
514
772
  try {
515
773
  fileSystem.closeSync(fd);
516
- } catch {}
774
+ } catch {
775
+ // Best-effort fd cleanup.
776
+ }
517
777
  }
518
778
  let tempRemoved = false;
519
779
  try {
@@ -526,13 +786,16 @@ function createPreviewPhaseOutbox(options) {
526
786
  }
527
787
  }
528
788
 
529
- function readAndValidateMetadata() {
530
- const stat = fileSystem.lstatSync(metaPath);
789
+ function readAndValidateMetadataAt(directoryPath) {
790
+ const candidateMetaPath = path.join(directoryPath, 'meta.json');
791
+ const stat = fileSystem.lstatSync(candidateMetaPath);
531
792
  if (!stat.isFile() || stat.isSymbolicLink()) {
532
- throw new Error(`unsafe preview phase outbox path: ${metaPath}`);
793
+ throw new Error(`unsafe preview phase outbox path: ${candidateMetaPath}`);
533
794
  }
534
- fileSystem.chmodSync(metaPath, 0o600);
535
- const metadata = JSON.parse(fileSystem.readFileSync(metaPath, 'utf8'));
795
+ fileSystem.chmodSync(candidateMetaPath, 0o600);
796
+ const metadata = JSON.parse(
797
+ fileSystem.readFileSync(candidateMetaPath, 'utf8')
798
+ );
536
799
  if (
537
800
  metadata.protocol !== 'preview-phase-outbox-v1' ||
538
801
  metadata.schema_version !== 1 ||
@@ -544,11 +807,17 @@ function createPreviewPhaseOutbox(options) {
544
807
  (metadata.quiesce_supported !== undefined &&
545
808
  metadata.quiesce_supported !== true)
546
809
  ) {
547
- throw new Error(`invalid preview phase outbox metadata: ${metaPath}`);
810
+ throw new Error(
811
+ `invalid preview phase outbox metadata: ${candidateMetaPath}`
812
+ );
548
813
  }
549
814
  return metadata;
550
815
  }
551
816
 
817
+ function readAndValidateMetadata() {
818
+ return readAndValidateMetadataAt(runDir);
819
+ }
820
+
552
821
  function ensureMetadata() {
553
822
  if (metadata) return;
554
823
  if (fileSystem.existsSync(metaPath)) {
@@ -580,15 +849,350 @@ function createPreviewPhaseOutbox(options) {
580
849
  if (error?.code !== 'EEXIST') throw error;
581
850
  }
582
851
  } finally {
852
+ let removed = false;
583
853
  try {
584
854
  fileSystem.rmSync(tempPath, { force: true });
855
+ removed = true;
585
856
  } catch {
586
857
  // A stale temp file is harmless and never consumed by the reader.
587
858
  }
859
+ if (removed) syncRunDirectory();
588
860
  }
589
861
  metadata = readAndValidateMetadata();
590
862
  }
591
863
 
864
+ function validateFallbackIntent(intent, canonicalMetadata) {
865
+ if (
866
+ intent.protocol !== 'preview-phase-fallback-intent-v1' ||
867
+ intent.schema_version !== 1 ||
868
+ intent.producer_epoch !== producerEpoch ||
869
+ intent.run_id !== options.run_id ||
870
+ intent.generation !== canonicalMetadata.generation ||
871
+ !Number.isFinite(intent.created_at_ms) ||
872
+ intent.created_at_ms <= 0 ||
873
+ !STATE_ID_PATTERN.test(intent.reason || '')
874
+ ) {
875
+ throw new Error(
876
+ `invalid preview phase fallback intent: ${path.join(
877
+ canonicalRunDir,
878
+ 'fallback.intent.json'
879
+ )}`
880
+ );
881
+ }
882
+ return intent;
883
+ }
884
+
885
+ function fallbackSpoolError(code, message, cause) {
886
+ const error = new Error(message, cause == null ? undefined : { cause });
887
+ error.code = code;
888
+ return error;
889
+ }
890
+
891
+ function encodeFallbackRecord(record, description) {
892
+ const payload = JSON.stringify(record);
893
+ if (typeof payload !== 'string') {
894
+ throw fallbackSpoolError(
895
+ 'PREVIEW_PHASE_FALLBACK_RECORD_INVALID',
896
+ `invalid preview phase fallback ${description}`
897
+ );
898
+ }
899
+ const encoded = Buffer.from(`${payload}\n`, 'utf8');
900
+ if (encoded.length > maxFallbackRecordBytes) {
901
+ throw fallbackSpoolError(
902
+ 'PREVIEW_PHASE_FALLBACK_RECORD_TOO_LARGE',
903
+ `preview phase fallback ${description} exceeds ${maxFallbackRecordBytes} bytes`
904
+ );
905
+ }
906
+ return encoded;
907
+ }
908
+
909
+ function fallbackTimestamp() {
910
+ const timestamp = now();
911
+ if (!Number.isFinite(timestamp) || timestamp <= 0) {
912
+ throw fallbackSpoolError(
913
+ 'PREVIEW_PHASE_FALLBACK_TIMESTAMP_INVALID',
914
+ 'invalid preview phase fallback timestamp'
915
+ );
916
+ }
917
+ return timestamp;
918
+ }
919
+
920
+ function closeFallbackFD() {
921
+ if (fallbackFD == null) return;
922
+ try {
923
+ fileSystem.closeSync(fallbackFD);
924
+ } catch {
925
+ // The durable boundary is fdatasync, not close. Never reuse this fd.
926
+ }
927
+ fallbackFD = null;
928
+ }
929
+
930
+ function ensureFallbackSpool(initialEventBytes) {
931
+ if (fallbackFD != null) return;
932
+ if (fallbackSealed) {
933
+ throw fallbackSpoolError(
934
+ 'PREVIEW_PHASE_FALLBACK_SEALED',
935
+ 'preview phase fallback spool is sealed'
936
+ );
937
+ }
938
+ if (fallbackFailed) {
939
+ throw fallbackSpoolError(
940
+ 'PREVIEW_PHASE_FALLBACK_DEGRADED',
941
+ 'preview phase fallback spool is degraded'
942
+ );
943
+ }
944
+
945
+ assertSafeDirectory(fileSystem, root);
946
+ assertExistingSafeDirectory(fileSystem, canonicalRunDir);
947
+ const parentMetadata = readAndValidateMetadataAt(canonicalRunDir);
948
+ const entries = readDirectoryEntriesBounded(
949
+ canonicalRunDir,
950
+ maxRunScanEntries,
951
+ `preview phase run scan exceeds ${maxRunScanEntries} entries: ${canonicalRunDir}`
952
+ );
953
+ const fallbackFiles = entries.filter(entry =>
954
+ /^fallback-pfs_[a-f0-9]{32}\.jsonl$/.test(entry.name)
955
+ );
956
+ if (fallbackFiles.length >= maxFallbackFiles) {
957
+ throw fallbackSpoolError(
958
+ 'PREVIEW_PHASE_FALLBACK_FILE_LIMIT',
959
+ `preview phase fallback file limit reached ${maxFallbackFiles}`
960
+ );
961
+ }
962
+ if (fileSystem.existsSync(fallbackSpoolPath)) {
963
+ throw fallbackSpoolError(
964
+ 'PREVIEW_PHASE_FALLBACK_SESSION_CONFLICT',
965
+ `preview phase fallback session already exists: ${fallbackSessionID}`
966
+ );
967
+ }
968
+
969
+ const createdAt = fallbackTimestamp();
970
+ const metaRecord = encodeFallbackRecord(
971
+ {
972
+ protocol: 'preview-phase-fallback-spool-v1',
973
+ schema_version: 1,
974
+ record_type: 'meta',
975
+ session_id: fallbackSessionID,
976
+ producer_epoch: producerEpoch,
977
+ run_id: options.run_id,
978
+ parent_generation: parentMetadata.generation,
979
+ producer_instance_id: producerInstanceID,
980
+ pid: process.pid,
981
+ process_start_ticks: currentProcessStartTicks,
982
+ // Protocol timestamps use Unix epoch milliseconds. The compact field
983
+ // name is retained because this is a versioned wire contract.
984
+ created_at: createdAt,
985
+ },
986
+ 'meta record'
987
+ );
988
+ if (
989
+ metaRecord.length + initialEventBytes + FALLBACK_TERMINAL_RESERVE_BYTES >
990
+ maxFallbackBytes
991
+ ) {
992
+ throw fallbackSpoolError(
993
+ 'PREVIEW_PHASE_FALLBACK_FILE_QUOTA_EXCEEDED',
994
+ `preview phase fallback file quota would exceed ${maxFallbackBytes} bytes`
995
+ );
996
+ }
997
+ assertRootByteQuota(
998
+ metaRecord.length + initialEventBytes + FALLBACK_TERMINAL_RESERVE_BYTES
999
+ );
1000
+
1001
+ const tempPath = path.join(
1002
+ canonicalRunDir,
1003
+ `.fallback-${fallbackSessionID}.${process.pid}.${writerInstanceID}.tmp`
1004
+ );
1005
+ const directoryFlags =
1006
+ fs.constants.O_RDONLY |
1007
+ (fs.constants.O_DIRECTORY || 0) |
1008
+ (fs.constants.O_NOFOLLOW || 0);
1009
+ let directoryFD = null;
1010
+ let fd = null;
1011
+ let published = false;
1012
+ try {
1013
+ directoryFD = fileSystem.openSync(canonicalRunDir, directoryFlags);
1014
+ const fileFlags =
1015
+ fs.constants.O_CREAT |
1016
+ fs.constants.O_EXCL |
1017
+ fs.constants.O_WRONLY |
1018
+ fs.constants.O_APPEND |
1019
+ (fs.constants.O_NOFOLLOW || 0);
1020
+ fd = fileSystem.openSync(tempPath, fileFlags, 0o600);
1021
+ fileSystem.fchmodSync(fd, 0o600);
1022
+ writeAll(fd, metaRecord);
1023
+ fileSystem.fsyncSync(fd);
1024
+ try {
1025
+ fileSystem.linkSync(tempPath, fallbackSpoolPath);
1026
+ } catch (error) {
1027
+ if (error?.code === 'EEXIST') {
1028
+ throw fallbackSpoolError(
1029
+ 'PREVIEW_PHASE_FALLBACK_SESSION_CONFLICT',
1030
+ `preview phase fallback session already exists: ${fallbackSessionID}`,
1031
+ error
1032
+ );
1033
+ }
1034
+ throw error;
1035
+ }
1036
+ // Sync the already-open directory, so quarantine rename after link does
1037
+ // not invalidate the durability proof for the published file name.
1038
+ fileSystem.fsyncSync(directoryFD);
1039
+ published = true;
1040
+ try {
1041
+ fileSystem.rmSync(tempPath);
1042
+ fileSystem.fsyncSync(directoryFD);
1043
+ } catch {
1044
+ // A quarantine rename can make the old path unreachable. The hidden
1045
+ // hard-link alias is harmless; the published session remains bounded.
1046
+ }
1047
+ fallbackFD = fd;
1048
+ fd = null;
1049
+ fallbackBytes = metaRecord.length;
1050
+ fallbackStarted = true;
1051
+ fallbackCreatedAt = createdAt;
1052
+ } catch (error) {
1053
+ fallbackFailed = true;
1054
+ throw error;
1055
+ } finally {
1056
+ if (fd != null) {
1057
+ try {
1058
+ fileSystem.closeSync(fd);
1059
+ } catch {
1060
+ // Best-effort fd cleanup.
1061
+ }
1062
+ }
1063
+ if (!published) {
1064
+ try {
1065
+ fileSystem.rmSync(tempPath, { force: true });
1066
+ if (directoryFD != null) fileSystem.fsyncSync(directoryFD);
1067
+ } catch {
1068
+ // Best-effort temp cleanup after a failed publication.
1069
+ }
1070
+ }
1071
+ if (directoryFD != null) {
1072
+ try {
1073
+ fileSystem.closeSync(directoryFD);
1074
+ } catch {
1075
+ // Best-effort directory-fd cleanup.
1076
+ }
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ function appendFallback(event) {
1082
+ if (fallbackSealed) {
1083
+ throw fallbackSpoolError(
1084
+ 'PREVIEW_PHASE_FALLBACK_SEALED',
1085
+ 'preview phase fallback spool is sealed'
1086
+ );
1087
+ }
1088
+ if (fallbackFailed) {
1089
+ throw fallbackSpoolError(
1090
+ 'PREVIEW_PHASE_FALLBACK_DEGRADED',
1091
+ 'preview phase fallback spool is degraded'
1092
+ );
1093
+ }
1094
+ if (!event || typeof event !== 'object' || Array.isArray(event)) {
1095
+ throw fallbackSpoolError(
1096
+ 'PREVIEW_PHASE_FALLBACK_RECORD_INVALID',
1097
+ 'invalid preview phase fallback event'
1098
+ );
1099
+ }
1100
+ if (fallbackSeq >= maxFallbackEvents) {
1101
+ throw fallbackSpoolError(
1102
+ 'PREVIEW_PHASE_FALLBACK_EVENT_LIMIT',
1103
+ `preview phase fallback event limit reached ${maxFallbackEvents}`
1104
+ );
1105
+ }
1106
+ const nextSeq = fallbackSeq + 1;
1107
+ const fallbackEvent = {
1108
+ ...event,
1109
+ transport: 'fallback_spool',
1110
+ fallback_session_id: fallbackSessionID,
1111
+ fallback_seq: nextSeq,
1112
+ };
1113
+ const eventPayload = JSON.stringify(fallbackEvent);
1114
+ if (
1115
+ typeof eventPayload !== 'string' ||
1116
+ Buffer.byteLength(eventPayload, 'utf8') > MAX_EVENT_BYTES
1117
+ ) {
1118
+ throw fallbackSpoolError(
1119
+ 'PREVIEW_PHASE_EVENT_TOO_LARGE',
1120
+ `preview phase event exceeds ${MAX_EVENT_BYTES} bytes`
1121
+ );
1122
+ }
1123
+ const record = encodeFallbackRecord(
1124
+ {
1125
+ protocol: 'preview-phase-fallback-spool-v1',
1126
+ schema_version: 1,
1127
+ record_type: 'event',
1128
+ session_id: fallbackSessionID,
1129
+ seq: nextSeq,
1130
+ event: fallbackEvent,
1131
+ },
1132
+ 'event record'
1133
+ );
1134
+
1135
+ ensureFallbackSpool(record.length);
1136
+ if (
1137
+ fallbackBytes + record.length + FALLBACK_TERMINAL_RESERVE_BYTES >
1138
+ maxFallbackBytes
1139
+ ) {
1140
+ throw fallbackSpoolError(
1141
+ 'PREVIEW_PHASE_FALLBACK_FILE_QUOTA_EXCEEDED',
1142
+ `preview phase fallback file quota would exceed ${maxFallbackBytes} bytes`
1143
+ );
1144
+ }
1145
+ try {
1146
+ writeAll(fallbackFD, record);
1147
+ fileSystem.fdatasyncSync(fallbackFD);
1148
+ fallbackBytes += record.length;
1149
+ fallbackSeq = nextSeq;
1150
+ fallbackRequired = true;
1151
+ return true;
1152
+ } catch (error) {
1153
+ fallbackFailed = true;
1154
+ closeFallbackFD();
1155
+ throw error;
1156
+ }
1157
+ }
1158
+
1159
+ function sealFallback() {
1160
+ if (!fallbackStarted) return !fallbackFailed;
1161
+ if (fallbackSealed) return true;
1162
+ if (fallbackFailed || fallbackFD == null) return false;
1163
+ const terminal = encodeFallbackRecord(
1164
+ {
1165
+ protocol: 'preview-phase-fallback-spool-v1',
1166
+ schema_version: 1,
1167
+ record_type: 'terminal',
1168
+ session_id: fallbackSessionID,
1169
+ final_cursor: fallbackBytes,
1170
+ final_seq: fallbackSeq,
1171
+ // Unix epoch milliseconds; never precedes this session's meta record.
1172
+ sealed_at: Math.max(fallbackTimestamp(), fallbackCreatedAt),
1173
+ recovered: false,
1174
+ },
1175
+ 'terminal record'
1176
+ );
1177
+ if (fallbackBytes + terminal.length > maxFallbackBytes) {
1178
+ fallbackFailed = true;
1179
+ closeFallbackFD();
1180
+ return false;
1181
+ }
1182
+ try {
1183
+ writeAll(fallbackFD, terminal);
1184
+ fileSystem.fdatasyncSync(fallbackFD);
1185
+ fallbackBytes += terminal.length;
1186
+ fallbackSealed = true;
1187
+ closeFallbackFD();
1188
+ return true;
1189
+ } catch {
1190
+ fallbackFailed = true;
1191
+ closeFallbackFD();
1192
+ return false;
1193
+ }
1194
+ }
1195
+
592
1196
  function validateProcessIdentityState(state, description) {
593
1197
  if (
594
1198
  !Number.isSafeInteger(state.pid) ||
@@ -623,8 +1227,22 @@ function createPreviewPhaseOutbox(options) {
623
1227
  return busy;
624
1228
  }
625
1229
 
1230
+ function runConflictError(cause) {
1231
+ const conflict = new Error(
1232
+ `preview phase canonical run was published by another writer: ${options.run_id}`,
1233
+ { cause }
1234
+ );
1235
+ conflict.code = 'PREVIEW_PHASE_RUN_CONFLICT';
1236
+ return conflict;
1237
+ }
1238
+
626
1239
  function acquireWriterLock() {
627
- if (writerLockOwned) return;
1240
+ if (ownsSelectedWriterLock()) return;
1241
+ if (writerLockOwned) {
1242
+ throw new Error(
1243
+ 'preview phase writer ownership belongs to another directory'
1244
+ );
1245
+ }
628
1246
  const lock = {
629
1247
  protocol: 'preview-phase-writer-v1',
630
1248
  schema_version: 1,
@@ -649,6 +1267,8 @@ function createPreviewPhaseOutbox(options) {
649
1267
  try {
650
1268
  fileSystem.linkSync(tempPath, writerLockPath);
651
1269
  writerLockOwned = true;
1270
+ writerLockDirectory = runDir;
1271
+ if (runDir === canonicalRunDir) everOwnedCanonicalWriter = true;
652
1272
  syncRunDirectory();
653
1273
  } catch (error) {
654
1274
  if (error?.code !== 'EEXIST') throw error;
@@ -659,12 +1279,234 @@ function createPreviewPhaseOutbox(options) {
659
1279
  throw writerBusyError();
660
1280
  }
661
1281
  } finally {
1282
+ let removed = false;
662
1283
  try {
663
1284
  fileSystem.rmSync(tempPath, { force: true });
1285
+ removed = true;
664
1286
  } catch {
665
1287
  // A stale temp file is harmless and never consumed by the reader.
666
1288
  }
1289
+ if (removed) syncRunDirectory();
1290
+ }
1291
+ }
1292
+
1293
+ function ensureEmptyEventsFile() {
1294
+ if (fileSystem.existsSync(eventsPath)) {
1295
+ const stat = fileSystem.lstatSync(eventsPath);
1296
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1297
+ throw new Error(`unsafe preview phase outbox path: ${eventsPath}`);
1298
+ }
1299
+ return;
1300
+ }
1301
+ const flags =
1302
+ fs.constants.O_CREAT |
1303
+ fs.constants.O_EXCL |
1304
+ fs.constants.O_RDWR |
1305
+ (fs.constants.O_NOFOLLOW || 0);
1306
+ const fd = fileSystem.openSync(eventsPath, flags, 0o600);
1307
+ try {
1308
+ fileSystem.fchmodSync(fd, 0o600);
1309
+ fileSystem.fdatasyncSync(fd);
1310
+ } finally {
1311
+ fileSystem.closeSync(fd);
1312
+ }
1313
+ syncRunDirectory();
1314
+ }
1315
+
1316
+ function validateOwnedWriterLock() {
1317
+ const lock = validateWriterLock(
1318
+ readRegularJSON(writerLockPath, 'writer lock')
1319
+ );
1320
+ if (
1321
+ lock.writer_instance_id !== writerInstanceID ||
1322
+ lock.pid !== process.pid ||
1323
+ (lock.process_start_ticks || '') !== (currentProcessStartTicks || '')
1324
+ ) {
1325
+ throw writerBusyError();
1326
+ }
1327
+ writerLockOwned = true;
1328
+ writerLockDirectory = runDir;
1329
+ }
1330
+
1331
+ let stagingOwned = false;
1332
+
1333
+ function tryAdoptCanonicalWriter() {
1334
+ const previousDirectory = runDir;
1335
+ const previousWriterLockOwned = writerLockOwned;
1336
+ const previousWriterLockDirectory = writerLockDirectory;
1337
+ try {
1338
+ selectRunDirectory(canonicalRunDir);
1339
+ assertExistingSafeDirectory(fileSystem, canonicalRunDir);
1340
+ metadata = readAndValidateMetadata();
1341
+ writerLockOwned = false;
1342
+ writerLockDirectory = null;
1343
+ validateOwnedWriterLock();
1344
+ stagingOwned = false;
1345
+ everOwnedCanonicalWriter = true;
1346
+ return true;
1347
+ } catch {
1348
+ selectRunDirectory(previousDirectory);
1349
+ writerLockOwned = previousWriterLockOwned;
1350
+ writerLockDirectory = previousWriterLockDirectory;
1351
+ return false;
1352
+ }
1353
+ }
1354
+
1355
+ function ensureCanonicalPublicationDurable() {
1356
+ if (canonicalPublicationDurable) return;
1357
+ try {
1358
+ syncRootDirectory();
1359
+ } catch (firstError) {
1360
+ // rename may have committed even when its first parent-directory fsync
1361
+ // failed. Re-prove the exact writer identity, then retry that commit
1362
+ // point before any event or producer marker can be published.
1363
+ if (!tryAdoptCanonicalWriter()) throw firstError;
1364
+ syncRootDirectory();
1365
+ }
1366
+ canonicalPublicationDurable = true;
1367
+ }
1368
+
1369
+ function registerCanonicalWriter(rejectedEvent) {
1370
+ if (producerRegistrationDurable) return;
1371
+ producerStartedAtMs = producerStartedAtMs ?? now();
1372
+ const rejectedEventForRegistration =
1373
+ rejectedEvent?.schema_version === 1 &&
1374
+ typeof rejectedEvent.event_id === 'string' &&
1375
+ rejectedEvent.event_id.startsWith(`${options.run_id}:`) &&
1376
+ rejectedEvent.run_id === options.run_id &&
1377
+ PRODUCER_INSTANCE_ID_PATTERN.test(
1378
+ rejectedEvent.producer_instance_id || ''
1379
+ ) &&
1380
+ rejectedEvent.producer_seq === 1 &&
1381
+ rejectedEvent.transport === 'outbox'
1382
+ ? rejectedEvent
1383
+ : null;
1384
+ const request = {
1385
+ // root/staging_name/started_at_ms are local callback context only. The
1386
+ // default registrar serializes the fixed protocol whitelist below and
1387
+ // never sends a caller-controlled path to shell-server.
1388
+ root,
1389
+ staging_name: stagingName,
1390
+ run_id: options.run_id,
1391
+ generation: metadata.generation,
1392
+ expected_instance_id: expectedInstanceID,
1393
+ producer_epoch: producerEpoch,
1394
+ writer_instance_id: writerInstanceID,
1395
+ pid: process.pid,
1396
+ process_start_ticks: currentProcessStartTicks,
1397
+ started_at_ms: producerStartedAtMs,
1398
+ ...(rejectedEventForRegistration == null
1399
+ ? {}
1400
+ : {
1401
+ producer_instance_id:
1402
+ rejectedEventForRegistration.producer_instance_id,
1403
+ fallback_session_id: fallbackSessionID,
1404
+ rejected_event: rejectedEventForRegistration,
1405
+ }),
1406
+ };
1407
+ if (producerRegistrationAttemptCount >= PRODUCER_REGISTER_ATTEMPTS) {
1408
+ throw producerRegistrationLastError;
1409
+ }
1410
+ while (producerRegistrationAttemptCount < PRODUCER_REGISTER_ATTEMPTS) {
1411
+ producerRegistrationAttemptCount += 1;
1412
+ try {
1413
+ const response = validateProducerRegistrationResponse(
1414
+ registerProducer(request),
1415
+ request
1416
+ );
1417
+ if (response.registration_status === 'rejected') {
1418
+ request.rejected_event.transport = 'fallback_spool';
1419
+ request.rejected_event.fallback_session_id = fallbackSessionID;
1420
+ request.rejected_event.fallback_seq = 1;
1421
+ fallbackRequired = true;
1422
+ fallbackSeq = 1;
1423
+ fallbackSealed = true;
1424
+ sealRequested = true;
1425
+ closed = true;
1426
+ closeResult = true;
1427
+ writerLockOwned = false;
1428
+ writerLockDirectory = null;
1429
+ stagingOwned = false;
1430
+ producerRegistrationDurable = true;
1431
+ selectRunDirectory(canonicalRunDir);
1432
+ return;
1433
+ }
1434
+ if (!tryAdoptCanonicalWriter()) {
1435
+ throw producerRegistrationError(
1436
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
1437
+ 'authoritative registration did not publish the expected canonical writer'
1438
+ );
1439
+ }
1440
+ // A successful authoritative response is issued only after the
1441
+ // canonical rename and root-directory fsync. Re-fsyncing here would
1442
+ // add latency without strengthening the controller's commit proof.
1443
+ canonicalPublicationDurable = true;
1444
+ const marker = readAndValidateProducerMarker();
1445
+ if (!markerBelongsToThisWriter(marker) || marker.state !== 'active') {
1446
+ throw producerRegistrationError(
1447
+ 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN',
1448
+ 'authoritative registration did not publish the expected active marker'
1449
+ );
1450
+ }
1451
+ producerStartedAtMs = marker.started_at_ms;
1452
+ producerMarkerActive = true;
1453
+ producerRegistrationDurable = true;
1454
+ return;
1455
+ } catch (error) {
1456
+ producerRegistrationLastError = error;
1457
+ if (
1458
+ error?.code === 'PREVIEW_PHASE_PRODUCER_EPOCH_CONFLICT' &&
1459
+ tryAdoptCanonicalWriter()
1460
+ ) {
1461
+ canonicalPublicationDurable = true;
1462
+ }
1463
+ if (
1464
+ error?.code === 'PREVIEW_PHASE_PRODUCER_REGISTRATION_ACK_UNKNOWN' &&
1465
+ producerRegistrationAttemptCount < PRODUCER_REGISTER_ATTEMPTS
1466
+ ) {
1467
+ continue;
1468
+ }
1469
+ throw error;
1470
+ }
1471
+ }
1472
+ throw producerRegistrationLastError;
1473
+ }
1474
+
1475
+ function ensureCanonicalWriter(rejectedEvent) {
1476
+ if (producerRegistrationDurable && runDir === canonicalRunDir && metadata) {
1477
+ ensureCanonicalPublicationDurable();
1478
+ return;
1479
+ }
1480
+
1481
+ if (!stagingOwned && fileSystem.existsSync(canonicalRunDir)) {
1482
+ // Existing canonical state is controller-owned. A JS successor may
1483
+ // inspect it to produce a precise fail-closed reason, but it must never
1484
+ // acquire/remove its writer lock or republish it under a captured epoch.
1485
+ selectRunDirectory(canonicalRunDir);
1486
+ assertExistingSafeDirectory(fileSystem, canonicalRunDir);
1487
+ metadata = readAndValidateMetadata();
1488
+ if (fileSystem.existsSync(sealPath)) {
1489
+ assertGenerationIsOpen();
1490
+ }
1491
+ if (fileSystem.existsSync(writerLockPath)) {
1492
+ validateWriterLock(readRegularJSON(writerLockPath, 'writer lock'));
1493
+ throw writerBusyError();
1494
+ }
1495
+ throw runConflictError();
667
1496
  }
1497
+
1498
+ selectRunDirectory(stagingRunDir);
1499
+ if (!stagingOwned) {
1500
+ fileSystem.mkdirSync(stagingRunDir, { mode: 0o700 });
1501
+ stagingOwned = true;
1502
+ syncRootDirectory();
1503
+ }
1504
+ assertSafeDirectory(fileSystem, stagingRunDir);
1505
+ ensureMetadata();
1506
+ if (!ownsSelectedWriterLock()) acquireWriterLock();
1507
+ ensureEmptyEventsFile();
1508
+ syncRunDirectory();
1509
+ registerCanonicalWriter(rejectedEvent);
668
1510
  }
669
1511
 
670
1512
  function assertStateGeneration(state, description) {
@@ -682,7 +1524,7 @@ function createPreviewPhaseOutbox(options) {
682
1524
 
683
1525
  function assertGenerationIsOpen() {
684
1526
  if (!fileSystem.existsSync(sealPath)) return;
685
- const seal = readAndValidateSeal();
1527
+ readAndValidateSeal();
686
1528
  const error = new Error(
687
1529
  `preview phase sealed generation cannot be reopened: ${options.run_id}`
688
1530
  );
@@ -727,6 +1569,16 @@ function createPreviewPhaseOutbox(options) {
727
1569
  return true;
728
1570
  }
729
1571
 
1572
+ function observeFallbackIntent() {
1573
+ if (!fileSystem.existsSync(fallbackIntentPath)) return false;
1574
+ validateFallbackIntent(
1575
+ readRegularJSON(fallbackIntentPath, 'fallback intent'),
1576
+ metadata
1577
+ );
1578
+ fallbackRequired = true;
1579
+ return true;
1580
+ }
1581
+
730
1582
  function assertGenerationIsNotDegraded() {
731
1583
  if (!observeDegradedMarker()) return;
732
1584
  throw degradedError();
@@ -745,6 +1597,7 @@ function createPreviewPhaseOutbox(options) {
745
1597
  }
746
1598
  fileSystem.rmSync(writerLockPath);
747
1599
  writerLockOwned = false;
1600
+ writerLockDirectory = null;
748
1601
  syncRunDirectory();
749
1602
  }
750
1603
 
@@ -800,7 +1653,7 @@ function createPreviewPhaseOutbox(options) {
800
1653
  fallbackRequired = true;
801
1654
  if (degraded) return;
802
1655
  degraded = true;
803
- if (!metadata) return;
1656
+ if (!metadata || !ownsSelectedWriterLock()) return;
804
1657
  const reason =
805
1658
  typeof cause?.code === 'string' && STATE_ID_PATTERN.test(cause.code)
806
1659
  ? cause.code
@@ -812,7 +1665,9 @@ function createPreviewPhaseOutbox(options) {
812
1665
  run_id: options.run_id,
813
1666
  generation: metadata.generation,
814
1667
  first_failed_event_id:
815
- typeof event?.event_id === 'string' ? event.event_id : '',
1668
+ typeof event?.event_id === 'string'
1669
+ ? event.event_id
1670
+ : `${options.run_id}:transport-fallback`,
816
1671
  degraded_at_ms: now(),
817
1672
  reason,
818
1673
  });
@@ -822,6 +1677,153 @@ function createPreviewPhaseOutbox(options) {
822
1677
  }
823
1678
  }
824
1679
 
1680
+ function finalizeUnboundFallback(event, conflict) {
1681
+ fallbackRequired = true;
1682
+ latchDegraded(event, conflict);
1683
+ recoverTornTail();
1684
+ ensureEmptyEventsFile();
1685
+ const fd = fileSystem.openSync(
1686
+ eventsPath,
1687
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)
1688
+ );
1689
+ let finalSize;
1690
+ try {
1691
+ finalSize = fileSystem.fstatSync(fd).size;
1692
+ } finally {
1693
+ fileSystem.closeSync(fd);
1694
+ }
1695
+ const ownedWriter = validateWriterLock(
1696
+ readRegularJSON(writerLockPath, 'writer lock')
1697
+ );
1698
+ if (
1699
+ ownedWriter.writer_instance_id !== writerInstanceID ||
1700
+ ownedWriter.pid !== process.pid ||
1701
+ (ownedWriter.process_start_ticks || '') !==
1702
+ (currentProcessStartTicks || '')
1703
+ ) {
1704
+ throw writerBusyError();
1705
+ }
1706
+ const terminalAt = Math.max(now(), ownedWriter.created_at_ms);
1707
+ if (!fileSystem.existsSync(sealPath)) {
1708
+ publishImmutableState(sealPath, 'sealed', {
1709
+ protocol: 'preview-phase-seal-v1',
1710
+ schema_version: 1,
1711
+ run_id: options.run_id,
1712
+ generation: metadata.generation,
1713
+ final_size_bytes: finalSize,
1714
+ sealed_at_ms: terminalAt,
1715
+ fallback_required: true,
1716
+ });
1717
+ }
1718
+ const observedOwner = readAndValidateProducerMarker();
1719
+ if (!fileSystem.existsSync(unboundFallbackPath)) {
1720
+ publishImmutableState(unboundFallbackPath, 'producer-unbound', {
1721
+ protocol: 'preview-phase-unbound-fallback-v1',
1722
+ schema_version: 1,
1723
+ epoch: producerEpoch,
1724
+ run_id: options.run_id,
1725
+ generation: metadata.generation,
1726
+ writer_instance_id: writerInstanceID,
1727
+ pid: process.pid,
1728
+ process_start_ticks: currentProcessStartTicks,
1729
+ started_at_ms: ownedWriter.created_at_ms,
1730
+ state: 'terminal',
1731
+ terminal_at_ms: terminalAt,
1732
+ observed_owner_run_id: observedOwner.run_id,
1733
+ observed_owner_generation: observedOwner.generation,
1734
+ });
1735
+ }
1736
+ if (ownsSelectedWriterLock()) removeOwnedWriterLock();
1737
+ closed = true;
1738
+ closeResult = true;
1739
+ }
1740
+
1741
+ function finalizeUnpublishedStagingFallback(event, conflict) {
1742
+ if (
1743
+ runDir !== stagingRunDir ||
1744
+ !stagingOwned ||
1745
+ !ownsSelectedWriterLock()
1746
+ ) {
1747
+ return false;
1748
+ }
1749
+ ensureMetadata();
1750
+ fallbackRequired = true;
1751
+ latchDegraded(event, conflict);
1752
+ recoverTornTail();
1753
+ ensureEmptyEventsFile();
1754
+ const fd = fileSystem.openSync(
1755
+ eventsPath,
1756
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)
1757
+ );
1758
+ let finalSize;
1759
+ try {
1760
+ finalSize = fileSystem.fstatSync(fd).size;
1761
+ } finally {
1762
+ fileSystem.closeSync(fd);
1763
+ }
1764
+ const ownedWriter = validateWriterLock(
1765
+ readRegularJSON(writerLockPath, 'writer lock')
1766
+ );
1767
+ if (
1768
+ ownedWriter.writer_instance_id !== writerInstanceID ||
1769
+ ownedWriter.pid !== process.pid ||
1770
+ (ownedWriter.process_start_ticks || '') !==
1771
+ (currentProcessStartTicks || '')
1772
+ ) {
1773
+ throw writerBusyError();
1774
+ }
1775
+ if (!fileSystem.existsSync(sealPath)) {
1776
+ publishImmutableState(sealPath, 'sealed', {
1777
+ protocol: 'preview-phase-seal-v1',
1778
+ schema_version: 1,
1779
+ run_id: options.run_id,
1780
+ generation: metadata.generation,
1781
+ final_size_bytes: finalSize,
1782
+ sealed_at_ms: Math.max(now(), ownedWriter.created_at_ms),
1783
+ fallback_required: true,
1784
+ });
1785
+ }
1786
+ removeOwnedWriterLock();
1787
+ closed = true;
1788
+ closeResult = true;
1789
+ try {
1790
+ const allowed = new Set([
1791
+ 'meta.json',
1792
+ 'events.jsonl',
1793
+ 'degraded.json',
1794
+ 'sealed.json',
1795
+ ]);
1796
+ const entries = readDirectoryEntriesBounded(
1797
+ stagingRunDir,
1798
+ allowed.size,
1799
+ 'preview phase unpublished staging exceeds cleanup entry limit'
1800
+ );
1801
+ for (const entry of entries) {
1802
+ if (!allowed.has(entry.name)) {
1803
+ throw new Error(
1804
+ 'preview phase unpublished staging contains unknown state'
1805
+ );
1806
+ }
1807
+ const entryPath = path.join(stagingRunDir, entry.name);
1808
+ const stat = fileSystem.lstatSync(entryPath);
1809
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1810
+ throw new Error(
1811
+ 'preview phase unpublished staging contains unsafe state'
1812
+ );
1813
+ }
1814
+ fileSystem.rmSync(entryPath);
1815
+ }
1816
+ syncRunDirectory();
1817
+ fileSystem.rmdirSync(stagingRunDir);
1818
+ syncRootDirectory();
1819
+ stagingOwned = false;
1820
+ } catch {
1821
+ // The writer lock is already durably absent. Trusted controller GC can
1822
+ // finish an unexpected cleanup remainder without touching canonical.
1823
+ }
1824
+ return true;
1825
+ }
1826
+
825
1827
  function append(event) {
826
1828
  if (closed) throw new Error('preview phase outbox is closed');
827
1829
  if (degraded) throw degradedError();
@@ -834,89 +1836,144 @@ function createPreviewPhaseOutbox(options) {
834
1836
  throw error;
835
1837
  }
836
1838
  const record = Buffer.from(`${payload}\n`, 'utf8');
837
- try {
838
- assertSafeDirectory(fileSystem, root);
839
- assertRootDirectoryQuota();
840
- assertSafeDirectory(fileSystem, runDir);
841
- ensureMetadata();
842
- assertGenerationIsOpen();
843
- acquireWriterLock();
844
- publishActiveProducerMarker();
845
- // Any existing writer identity is authoritative to JS. Dead-owner
846
- // recovery and torn-tail finalization belong exclusively to shell-server.
847
- assertGenerationIsNotDegraded();
848
- assertRootByteQuota(record.length);
849
- if (eventsFD == null) {
850
- if (fileSystem.existsSync(eventsPath)) {
851
- const stat = fileSystem.lstatSync(eventsPath);
852
- if (!stat.isFile() || stat.isSymbolicLink()) {
853
- throw new Error(`unsafe preview phase outbox path: ${eventsPath}`);
1839
+ for (let attempt = 1; attempt <= MAX_TRANSIENT_ATTEMPTS; attempt += 1) {
1840
+ try {
1841
+ assertSafeDirectory(fileSystem, root);
1842
+ assertRootDirectoryQuota();
1843
+ ensureCanonicalWriter(event);
1844
+ if (
1845
+ closed &&
1846
+ producerRegistrationDurable &&
1847
+ !everOwnedCanonicalWriter
1848
+ ) {
1849
+ return true;
1850
+ }
1851
+ // The authoritative registrar proves the initial writer identity, but
1852
+ // every append must still fail closed if a controller or an unexpected
1853
+ // same-UID actor replaces auxiliary state after registration.
1854
+ validateOwnedWriterLock();
1855
+ assertGenerationIsOpen();
1856
+ publishActiveProducerMarker();
1857
+ // Any existing writer identity is authoritative to JS. Dead-owner
1858
+ // recovery and torn-tail finalization belong exclusively to shell-server.
1859
+ assertGenerationIsNotDegraded();
1860
+ assertRootByteQuota(record.length);
1861
+ if (eventsFD == null) {
1862
+ if (fileSystem.existsSync(eventsPath)) {
1863
+ const stat = fileSystem.lstatSync(eventsPath);
1864
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1865
+ throw new Error(
1866
+ `unsafe preview phase outbox path: ${eventsPath}`
1867
+ );
1868
+ }
854
1869
  }
1870
+ recoverTornTail();
1871
+ const flags =
1872
+ fs.constants.O_CREAT |
1873
+ fs.constants.O_WRONLY |
1874
+ fs.constants.O_APPEND |
1875
+ (fs.constants.O_NOFOLLOW || 0);
1876
+ eventsFD = fileSystem.openSync(eventsPath, flags, 0o600);
1877
+ fileSystem.fchmodSync(eventsFD, 0o600);
1878
+ committedBytes = fileSystem.fstatSync(eventsFD).size;
855
1879
  }
856
- recoverTornTail();
857
- const flags =
858
- fs.constants.O_CREAT |
859
- fs.constants.O_WRONLY |
860
- fs.constants.O_APPEND |
861
- (fs.constants.O_NOFOLLOW || 0);
862
- eventsFD = fileSystem.openSync(eventsPath, flags, 0o600);
863
- fileSystem.fchmodSync(eventsFD, 0o600);
864
- committedBytes = fileSystem.fstatSync(eventsFD).size;
865
- }
866
- if (committedBytes + record.length > maxRunBytes) {
867
- const error = new Error(
868
- `preview phase run quota would exceed ${maxRunBytes} bytes`
869
- );
870
- error.code = 'PREVIEW_PHASE_RUN_QUOTA_EXCEEDED';
871
- throw error;
872
- }
873
- let offset = 0;
874
- while (offset < record.length) {
875
- const written = fileSystem.writeSync(
876
- eventsFD,
877
- record,
878
- offset,
879
- record.length - offset
880
- );
881
- if (!Number.isInteger(written) || written <= 0) {
882
- throw new Error('preview phase outbox write made no progress');
1880
+ if (committedBytes + record.length > maxRunBytes) {
1881
+ const error = new Error(
1882
+ `preview phase run quota would exceed ${maxRunBytes} bytes`
1883
+ );
1884
+ error.code = 'PREVIEW_PHASE_RUN_QUOTA_EXCEEDED';
1885
+ throw error;
883
1886
  }
884
- offset += written;
885
- }
886
- committedBytes += record.length;
887
- return true;
888
- } catch (error) {
889
- if (eventsFD != null) {
890
- try {
891
- fileSystem.closeSync(eventsFD);
892
- } catch {}
893
- eventsFD = null;
894
- committedBytes = null;
895
- recovered = false;
1887
+ let offset = 0;
1888
+ while (offset < record.length) {
1889
+ const written = fileSystem.writeSync(
1890
+ eventsFD,
1891
+ record,
1892
+ offset,
1893
+ record.length - offset
1894
+ );
1895
+ if (!Number.isInteger(written) || written <= 0) {
1896
+ throw new Error('preview phase outbox write made no progress');
1897
+ }
1898
+ offset += written;
1899
+ }
1900
+ committedBytes += record.length;
1901
+ return true;
1902
+ } catch (error) {
1903
+ if (eventsFD != null) {
1904
+ try {
1905
+ fileSystem.closeSync(eventsFD);
1906
+ } catch {
1907
+ // Best-effort fd cleanup after append failure.
1908
+ }
1909
+ eventsFD = null;
1910
+ committedBytes = null;
1911
+ recovered = false;
1912
+ }
1913
+ if (error?.code === 'PREVIEW_PHASE_PRODUCER_EPOCH_CONFLICT') {
1914
+ try {
1915
+ finalizeUnboundFallback(event, error);
1916
+ } catch {
1917
+ // The controller can finish a dead CAS loser from its immutable
1918
+ // writer identity. Preserve the original conflict for fallback.
1919
+ }
1920
+ throw error;
1921
+ }
1922
+ if (error?.code === 'PREVIEW_PHASE_RUN_CONFLICT') {
1923
+ try {
1924
+ finalizeUnpublishedStagingFallback(event, error);
1925
+ } catch {
1926
+ // Preserve the staging writer for controller-owned dead-owner GC.
1927
+ }
1928
+ throw error;
1929
+ }
1930
+ if (
1931
+ isTransientFilesystemError(error) &&
1932
+ attempt < MAX_TRANSIENT_ATTEMPTS
1933
+ ) {
1934
+ continue;
1935
+ }
1936
+ latchDegraded(event, error);
1937
+ throw error;
896
1938
  }
897
- latchDegraded(event, error);
898
- throw error;
899
1939
  }
1940
+ throw new Error('preview phase transient retry loop exhausted');
900
1941
  }
901
1942
 
902
1943
  function flush() {
903
1944
  if (eventsFD == null) return true;
904
- try {
905
- fileSystem.fdatasyncSync(eventsFD);
906
- return true;
907
- } catch (error) {
908
- fallbackRequired = true;
909
- throw error;
1945
+ for (let attempt = 1; attempt <= MAX_TRANSIENT_ATTEMPTS; attempt += 1) {
1946
+ try {
1947
+ fileSystem.fdatasyncSync(eventsFD);
1948
+ return true;
1949
+ } catch (error) {
1950
+ if (
1951
+ isTransientFilesystemError(error) &&
1952
+ attempt < MAX_TRANSIENT_ATTEMPTS
1953
+ ) {
1954
+ continue;
1955
+ }
1956
+ latchDegraded(null, error);
1957
+ throw error;
1958
+ }
910
1959
  }
1960
+ throw new Error('preview phase flush retry loop exhausted');
911
1961
  }
912
1962
 
913
1963
  function pollQuiesce() {
914
- if (closed) return closeResult;
915
- if (sealRequested) return close();
916
- // A reporter that never acquired this generation's writer lock must not
917
- // acknowledge or act on a request intended for the actual owner.
918
- if (!metadata || !writerLockOwned) return false;
919
- if (!fileSystem.existsSync(quiesceRequestPath)) return false;
1964
+ const state = (localSealed, canonicalAcknowledged) => ({
1965
+ local_sealed: localSealed,
1966
+ canonical_acknowledged: canonicalAcknowledged,
1967
+ });
1968
+ if (closed) {
1969
+ return state(closeResult, everOwnedCanonicalWriter && closeResult);
1970
+ }
1971
+ if (sealRequested) {
1972
+ const localSealed = close();
1973
+ return state(localSealed, everOwnedCanonicalWriter && localSealed);
1974
+ }
1975
+ if (!metadata) return state(false, false);
1976
+ if (!fileSystem.existsSync(quiesceRequestPath)) return state(false, false);
920
1977
  const request = readRegularJSON(quiesceRequestPath, 'quiesce request');
921
1978
  assertStateGeneration(request, 'quiesce request');
922
1979
  if (
@@ -930,11 +1987,29 @@ function createPreviewPhaseOutbox(options) {
930
1987
  `invalid preview phase quiesce request: ${quiesceRequestPath}`
931
1988
  );
932
1989
  }
933
- return close();
1990
+ if (!ownsSelectedWriterLock()) {
1991
+ // Do not acknowledge or mutate the canonical owner lifecycle. The
1992
+ // quiesce boundary still terminalizes this producer's own fallback file.
1993
+ sealRequested = true;
1994
+ closeResult = sealFallback();
1995
+ closed = true;
1996
+ return state(closeResult, false);
1997
+ }
1998
+ const localSealed = close();
1999
+ return state(localSealed, localSealed);
934
2000
  }
935
2001
 
936
2002
  function close() {
937
- if (closed) return closeResult;
2003
+ const fallbackCloseResult = sealFallback();
2004
+ // A fallback-only producer never owns the canonical writer lifecycle.
2005
+ // Its open spool fd is sufficient to terminalize after controller rename;
2006
+ // attempting canonical close here could recreate or mutate another owner.
2007
+ if (fallbackStarted && !everOwnedCanonicalWriter) {
2008
+ closed = true;
2009
+ closeResult = fallbackCloseResult;
2010
+ return closeResult;
2011
+ }
2012
+ if (closed) return closeResult && fallbackCloseResult;
938
2013
  sealRequested = true;
939
2014
  let finalSize = null;
940
2015
  try {
@@ -943,18 +2018,17 @@ function createPreviewPhaseOutbox(options) {
943
2018
  // this initialization when the filesystem becomes available again.
944
2019
  if (!metadata && !degraded && !fallbackRequired) {
945
2020
  closed = true;
946
- closeResult = true;
947
- return true;
2021
+ closeResult = fallbackCloseResult;
2022
+ return closeResult;
948
2023
  }
949
2024
  assertSafeDirectory(fileSystem, root);
950
2025
  assertRootDirectoryQuota();
951
- assertSafeDirectory(fileSystem, runDir);
952
- ensureMetadata();
2026
+ ensureCanonicalWriter();
953
2027
 
954
2028
  if (fileSystem.existsSync(sealPath)) {
955
2029
  const seal = readAndValidateSeal();
956
2030
  fallbackRequired ||= seal.fallback_required === true;
957
- if (writerLockOwned) {
2031
+ if (ownsSelectedWriterLock()) {
958
2032
  publishActiveProducerMarker();
959
2033
  publishTerminalProducerMarker();
960
2034
  removeOwnedWriterLock();
@@ -976,14 +2050,15 @@ function createPreviewPhaseOutbox(options) {
976
2050
  producerMarkerTerminal = true;
977
2051
  }
978
2052
  closed = true;
979
- closeResult = true;
980
- return true;
2053
+ closeResult = fallbackCloseResult;
2054
+ return closeResult;
981
2055
  }
982
2056
 
983
- if (!writerLockOwned) {
2057
+ if (!ownsSelectedWriterLock()) {
984
2058
  acquireWriterLock();
985
2059
  }
986
2060
  publishActiveProducerMarker();
2061
+ observeFallbackIntent();
987
2062
  observeDegradedMarker();
988
2063
  if (eventsFD != null) {
989
2064
  fileSystem.fdatasyncSync(eventsFD);
@@ -1021,36 +2096,44 @@ function createPreviewPhaseOutbox(options) {
1021
2096
  });
1022
2097
  publishTerminalProducerMarker();
1023
2098
  removeOwnedWriterLock();
1024
- closeResult = true;
2099
+ closeResult = fallbackCloseResult;
1025
2100
  closed = true;
1026
- } catch {
2101
+ } catch (error) {
1027
2102
  closeResult = false;
1028
- fallbackRequired = true;
2103
+ if (!isTransientFilesystemError(error)) {
2104
+ latchDegraded(null, error);
2105
+ }
1029
2106
  if (eventsFD != null) {
1030
2107
  try {
1031
2108
  fileSystem.closeSync(eventsFD);
1032
- } catch {}
2109
+ } catch {
2110
+ // Best-effort fd cleanup after close failure.
2111
+ }
1033
2112
  eventsFD = null;
1034
2113
  committedBytes = null;
1035
2114
  }
1036
- // Keep the unique writer owner and pending close intent for transient
1037
- // retries. If the process dies, shell-server is the sole authority that
1038
- // verifies PID+starttime, repairs the tail, and seals the generation.
2115
+ // Keep the unique writer owner and pending close intent for retries. If
2116
+ // the process dies, shell-server is the sole authority that verifies
2117
+ // PID+starttime, repairs the tail, and seals the generation.
1039
2118
  }
1040
2119
  return closeResult;
1041
2120
  }
1042
2121
 
1043
2122
  return {
1044
2123
  append,
2124
+ append_fallback: appendFallback,
2125
+ seal_fallback: sealFallback,
1045
2126
  flush,
1046
2127
  close,
1047
2128
  poll_quiesce: pollQuiesce,
2129
+ is_local_sealed: () => closed && closeResult,
1048
2130
  events_path: eventsPath,
1049
2131
  meta_path: metaPath,
1050
2132
  seal_path: sealPath,
1051
2133
  degraded_path: degradedPath,
1052
2134
  quiesce_request_path: quiesceRequestPath,
1053
2135
  producer_epoch_marker_path: producerEpochMarkerPath,
2136
+ fallback_spool_path: fallbackSpoolPath,
1054
2137
  };
1055
2138
  }
1056
2139
 
@@ -1061,6 +2144,11 @@ module.exports = {
1061
2144
  DEFAULT_MAX_ROOT_DIRECTORIES,
1062
2145
  DEFAULT_MAX_ROOT_SCAN_DIRECTORIES,
1063
2146
  DEFAULT_MAX_RUN_SCAN_ENTRIES,
2147
+ DEFAULT_MAX_FALLBACK_FILES,
2148
+ DEFAULT_MAX_FALLBACK_BYTES,
2149
+ DEFAULT_MAX_FALLBACK_EVENTS,
2150
+ MAX_FALLBACK_RECORD_BYTES,
1064
2151
  MAX_EVENT_BYTES,
2152
+ createFallbackSessionID,
1065
2153
  createPreviewPhaseOutbox,
1066
2154
  };