Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1837 lines (1738 loc) · 73.8 KB
/
Copy pathindex.ts
File metadata and controls
1837 lines (1738 loc) · 73.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* JSONL durable session-persistence backend. It stores a header and contiguous
* events in immutable generation files under one directory per session and serves the handle-based
* `SessionPersistence` API: `create`/`open` return per-session handles, and
* every read validates the same fail-closed storage contract.
* @module @deepseek-ai/dsh-session-persistence-jsonl
*/
import { Context, type Fiber } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import {
createSessionFormatCatalogWithChildren,
SessionFormatUnsupportedMigrationError,
sessionFormatCatalog,
} from '@deepseek-ai/dsh-session-format-catalog'
import { readdirSync, type Dirent } from 'node:fs'
import { open, mkdir, readdir, realpath, link, rm, stat, truncate } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { performance } from 'node:perf_hooks'
import { scheduler } from 'node:timers/promises'
import { createHash, randomBytes } from 'node:crypto'
import pLimit, { type LimitFunction } from 'p-limit'
import {
SessionPersistence, SessionPersistenceRevision, SessionFormatUnsupportedError,
SessionPersistenceCorruptionError,
SessionAlreadyExistsError, SessionPersistenceNotFoundError,
assertStoredId, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents,
type SessionAccess, type SessionHandle,
type SessionHandleReadResult,
type SessionLocation, type SessionPersistenceCreateOptions,
type SessionPersistenceListOptions, type SessionPersistenceOpenOptions,
type SessionPersistenceSnapshot, type SessionPersistenceStatOptions,
type SessionPersistenceRevision as PersistenceRevision,
} from '@deepseek-ai/dsh-session-persistence'
import { JsonlBackendTracker, JsonlSessionHandle, type StorageHandleState } from './storage.ts'
import { SessionWriteLease } from './lease.ts'
import { SESSION_FORMAT_VERSION, SessionId as makeSessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionId, SessionHeader, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
import {
assertNoRetiredHeaderFields, encodeSegment, eventLines, generationLogFilename, generationLogPath, logPath, logSuffix,
parseGenerationLogFilename, projectDir, scanLog, sessionDir, SessionLogScanner, toHeaderLine,
type JsonlCompression,
} from './format.ts'
import {
compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, decompressZstdPrefix, scanZstdFrames,
} from './zstd.ts'
import { ensureDurableDirectoryWin32, publishNewFileWin32 } from './win32.ts'
import { verifyCurrentGenerationInWorker } from './migration-verifier.ts'
import { prepareCatalogFacts } from './catalog-migration.ts'
import {
JsonlGenerationSourceChangedError,
JsonlGenerationUnsupportedMigrationError,
prepareJsonlMigration,
readStableJsonlFile,
type JsonlGenerationFormatAdapter,
type JsonlPhysicalIdentity,
type PreparedJsonlMigration,
} from './generation.ts'
export type { JsonlCompression } from './format.ts'
/**
* Internal handoff-reuse policy, not deployment configuration: a cold
* observation and the resume that immediately follows it reuse one parsed
* log, so the memo only needs the sessions in flight between those steps.
*/
const COLD_LOG_MEMO_MAX_ENTRIES = 2
const DEFAULT_COMPRESSION: JsonlCompression = 'zstd'
/**
* Internal scheduling constant, not deployment configuration: balance
* frame-boundary event-loop yields against `setImmediate` overhead. One frame
* remains an indivisible synchronous decode.
*/
const ZSTD_DECODE_YIELD_INTERVAL_MS = 500
/** Assert that the independently decodable first frame contains only the header record. */
function assertZstdHeaderFrame(plaintext: Buffer): void {
if (plaintext.length === 0 || plaintext.indexOf(0x0A) !== plaintext.length - 1) {
throw new Error('corrupt Zstandard session log: first frame is not exactly one header line')
}
}
/** Loader schema for the JSONL artifact's physical encoding. */
export const JsonlCompressionSchema: z<JsonlCompression> = z.union([
z.const('zstd'),
z.const('none'),
]).default(DEFAULT_COMPRESSION)
/** Default maximum listing filesystem operations in flight per backend. */
const DEFAULT_LIST_CONCURRENCY = 3
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
export interface Config {
/**
* Root directory for all session files. Required (no default): a default of
* `process.cwd()` would scatter session files as the process's cwd changes
* (bash calls, subprocesses). Sessions group under human-readable project
* directories, then per-session directories. An existing root must be a
* readable directory; an absent root is created on first materialization.
*/
root: string
/** Physical encoding; defaults to checksummed Zstandard frames. */
compression?: JsonlCompression
/**
* Maximum directory, header, and stat reads in flight across all concurrent
* listings of this backend (`list()`, the root encoding check, and historical
* fingerprints). Defaults to 3.
*/
listConcurrency?: number
}
/** Logical header paired with the catalog's selected physical-generation classification. */
interface GenerationHeader {
readonly header: SessionHeader
readonly formatStatus: NonNullable<SessionPersistenceSnapshot['formatStatus']>
}
/** One stored event graph whose producer has established immutable sharing. */
interface FrozenStoredEvents extends SessionHandleReadResult {
readonly eventState: 'shared-frozen'
}
/** State shared by prepared historical and published current logs. */
interface StoredLogBase extends FrozenStoredEvents {
readonly meta: SessionHeader
readonly tornTruncateTo: number | undefined
/** Complete events recovered from the torn final frame; the write path rewrites them durably. */
readonly recoveredTail: SessionEvent[]
/** Exact fork-inherited prefix length stored in the header line. */
readonly inheritedEventCount: SessionLogOffsetType
readonly revision: PersistenceRevision
}
/** A decoded current generation that is already durable. */
interface CurrentStoredLog extends StoredLogBase {
readonly status: 'current'
}
/** A migrated historical generation retained until an explicit write open publishes it. */
interface PreparedStoredLog extends StoredLogBase {
readonly status: 'prepared'
readonly validateRelatedSources: () => Promise<void>
readonly publication: {
readonly source: ResolvedJsonlGeneration
readonly value: PreparedJsonlMigration
}
}
/** A validated logical log, either durable current state or prepared historical state. */
type StoredLog = CurrentStoredLog | PreparedStoredLog
/** Deep-freeze acyclic stored JSON; its arrays contain only indexed JSON values. */
function freezeStoredEvent(event: SessionEvent): void {
const pending: object[] = [event]
while (pending.length > 0) {
// The non-empty check proves an object remains to visit.
// oxlint-disable-next-line typescript/no-non-null-assertion
const current = pending.pop()!
Object.freeze(current)
if (Array.isArray(current)) {
for (let index = 0; index < current.length; index += 1) {
const child: unknown = current[index]
if (child !== null && typeof child === 'object') pending.push(child)
}
} else {
for (const key in current) {
const child = (current as Record<string, unknown>)[key]
if (child !== null && typeof child === 'object') pending.push(child)
}
}
}
}
/** Establish immutable sharing for one decoded event graph and report that state. */
function freezeStoredEvents(events: SessionEvent[]): FrozenStoredEvents {
for (const event of events) freezeStoredEvent(event)
Object.freeze(events)
return { eventState: 'shared-frozen', events }
}
/** One authoritative immutable generation selected from a Session directory. */
interface ResolvedJsonlGeneration {
readonly sourcePath: string
readonly sourceVersion: number
readonly currentPath: string
}
/** One backend-owned historical preparation shared by its current callers. */
interface MigrationPreparation {
readonly sourcePath: string
readonly sourceRevision: PersistenceRevision
readonly controller: AbortController
readonly promise: Promise<PreparedStoredLog>
settled: boolean
waiters: number
}
/** Build the stat-derived best-effort change token shared by full and lightweight reads. */
function fileRevision(identity: JsonlPhysicalIdentity): PersistenceRevision {
return SessionPersistenceRevision([
identity.dev,
identity.ino,
identity.size,
identity.mtimeNs,
identity.ctimeNs,
].join(':'))
}
/** Whether a filesystem error means absence; every non-ENOENT failure must surface. */
function isENOENT(error: unknown): boolean {
return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
}
/**
* Run `task` over `items` through the backend's shared listing limiter and
* settle every call. Callers consume the outcomes in input order, so the first
* failure they report matches a sequential loop whatever the completion order.
* A limited task must never wait on the same limiter.
* @param limit - the backend's shared listing limiter.
* @param items - inputs in their sequential order.
* @param task - per-item operation.
* @returns one outcome per item, in input order.
*/
function settleLimited<T, R>(
limit: LimitFunction,
items: readonly T[],
task: (item: T) => Promise<R>,
): Promise<PromiseSettledResult<R>[]> {
return Promise.allSettled(items.map(item => limit(() => task(item))))
}
/**
* Unwrap outcomes from {@link settleLimited}, rethrowing the first rejection in input order.
* @param outcomes - outcomes in input order.
* @returns the fulfilled values in input order.
*/
function settledValues<R>(outcomes: readonly PromiseSettledResult<R>[]): R[] {
return outcomes.map((outcome) => {
if (outcome.status === 'rejected') throw outcome.reason
return outcome.value
})
}
/** Whether a filesystem-owned failure should retain its original errno and path. */
function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
return typeof (error as NodeJS.ErrnoException | null)?.code === 'string'
}
/** Preserve an Error abort reason and normalize hostile non-Error reasons. */
function abortError(signal: AbortSignal): Error {
return signal.reason instanceof Error
? signal.reason
: new Error('session migration preparation aborted', { cause: signal.reason })
}
/** Let one caller stop waiting without transferring cancellation ownership to shared work. */
function waitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
if (signal === undefined) return operation
/* v8 ignore next -- requireStoredLog synchronously rechecks the signal immediately before waiting. */
if (signal.aborted) return Promise.reject(abortError(signal))
return new Promise<T>((resolve, reject) => {
const stopWaiting = (): void => {
reject(abortError(signal))
}
signal.addEventListener('abort', stopWaiting, { once: true })
void operation.then(
(value) => {
signal.removeEventListener('abort', stopWaiting)
resolve(value)
},
(error: unknown) => {
signal.removeEventListener('abort', stopWaiting)
/* v8 ignore else -- the preparation owner normalizes every rejection before this waiter sees it. */
if (error instanceof Error) {
reject(error)
} else {
reject(new Error('session migration preparation failed', { cause: error }))
}
},
)
})
}
/**
* The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
* Sessions materialize lazily: a created session is
* visible to this process immediately, reaches disk on its first append or
* flush, and never existed if the process crashes before that.
*/
class JsonlSessionPersistence extends SessionPersistence {
/** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
override readonly name = 'session-persistence-jsonl'
private root: string
private compression: JsonlCompression
/**
* Bounds directory, header, and stat I/O across every concurrent listing of
* this backend (`list()`, the root encoding check, historical fingerprints).
* Queued tasks of a cancelled listing run and reject at their signal check.
*/
private readonly listLimit: LimitFunction
private rootEncodingCheck: Promise<void> | undefined
private readonly generationFormat: Omit<JsonlGenerationFormatAdapter, 'createRestore'>
/**
* Bounded LRU of parsed, validated stored logs keyed by session id and
* guarded by the stat-derived revision, so an immediate cold-read handoff
* (observation then resume) parses the artifact once. Every local mutation
* for an id invalidates its entry; a foreign write misses through the
* revision guard.
*/
private readonly coldLogMemo = new Map<SessionId, StoredLog>()
/** One joinable decode/migration operation per selected historical Session file revision. */
private readonly migrationPreparations = new Map<SessionId, MigrationPreparation>()
constructor(ctx: Context, public config: Config, private readonly tracker: JsonlBackendTracker) {
super(ctx)
/* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) {
throw new Error(
`session-persistence-jsonl: format catalog v${sessionFormatCatalog.currentVersion} `
+ `does not match Session v${SESSION_FORMAT_VERSION}`,
)
}
// Resolve once so later process.cwd() changes cannot split one backend across roots.
this.root = resolve(config.root)
this.compression = config.compression ?? DEFAULT_COMPRESSION
this.listLimit = pLimit(config.listConcurrency ?? DEFAULT_LIST_CONCURRENCY)
this.generationFormat = {
currentVersion: sessionFormatCatalog.currentVersion,
encodeHeader: (header, inheritedEventCount) =>
sessionFormatCatalog.encodeCurrentHeader(header, inheritedEventCount),
encodeEvent: event => sessionFormatCatalog.encodeCurrentEvent(event),
isUnsupportedMigrationError: (error): error is SessionFormatUnsupportedMigrationError =>
error instanceof SessionFormatUnsupportedMigrationError,
}
this.assertUsableRoot()
}
/**
* Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
* @param meta - the stored header naming the session and its cwd.
* @returns the artifact kind and absolute path.
*/
private locate(meta: SessionHeader): SessionLocation {
return { kind: 'jsonl', path: logPath(this.root, meta.cwd, meta.id, this.compression) }
}
// --- SessionPersistence service API ---
/**
* Create a new stored session and take its write ownership. The session is
* visible to this process immediately; the physical artifact appears on the
* first append or flush.
* @param header - the immutable header to store; must be losslessly
* JSON-serializable with a non-negative safe-integer `createdAt`.
* @param options - optional cancellation.
* @returns the owned write handle.
*/
async create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle> {
options?.signal?.throwIfAborted()
const snapshot = materializeCreateHeader(header)
// Fail fast on a seeded/cut mismatch with the exact refusal the header
// line encoder enforces at materialization.
toHeaderLine(snapshot, options?.inheritedEventCount)
const inheritedEventCount = SessionLogOffset(options?.inheritedEventCount ?? 0)
await this.ensureRootEncoding()
options?.signal?.throwIfAborted()
if (this.tracker.hasPending(snapshot.id) || await this.findLog(snapshot.id, options?.signal) !== undefined) {
throw new SessionAlreadyExistsError(snapshot.id)
}
options?.signal?.throwIfAborted()
// No lock yet: before materialization there is no durable artifact for
// another process to contend over, so the handle acquires the lock right
// before its first log bytes publish (ensureLease); an unmaterialized
// session leaves no filesystem footprint at all.
this.tracker.registerCreated(snapshot, inheritedEventCount)
return this.tracker.adopt(new JsonlSessionHandle(this, snapshot.id, snapshot, 'write', { cursor: 0, materialized: false, inheritedEventCount }))
}
/**
* Open an existing stored session for `read` or single-writer `write`.
* @param id - the stored session to open.
* @param access - `read` (no ownership) or `write` (atomic in-process claim).
* @param options - optional cancellation.
* @returns the open handle.
*/
async open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle> {
options?.signal?.throwIfAborted()
await this.ensureRootEncoding()
options?.signal?.throwIfAborted()
const pending = this.tracker.pendingOf(id)
if (access === 'read') {
if (pending !== undefined) {
return this.tracker.adopt(new JsonlSessionHandle(this, id, pending.header, 'read', { cursor: 0, materialized: false, inheritedEventCount: pending.inheritedEventCount }))
}
let stored: StoredLog
try {
stored = await this.requireStoredLog(id, options?.signal)
} catch (error: unknown) {
if (!(error instanceof JsonlGenerationSourceChangedError)) throw error
stored = await this.requireStoredLog(id, options?.signal)
}
let state: StorageHandleState
if (stored.status === 'prepared') {
state = {
cursor: 0,
materialized: true,
inheritedEventCount: stored.inheritedEventCount,
primed: stored,
}
} else {
state = {
cursor: 0,
materialized: true,
inheritedEventCount: stored.inheritedEventCount,
}
}
return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, 'read', state))
}
// A pending entry always belongs to an ACTIVE creator handle (close erases
// it), so the claim below rejects that case as already owned.
this.tracker.claimWrite(id)
let lease: SessionWriteLease | undefined
try {
const resolved = await this.findLog(id, options?.signal)
if (resolved === undefined) throw new SessionPersistenceNotFoundError(id)
lease = await this.acquireLease(id, undefined, dirname(resolved.currentPath))
const prepared = await this.requireStoredLog(id, options?.signal)
options?.signal?.throwIfAborted()
let stored: CurrentStoredLog
if (prepared.status === 'prepared') {
stored = await this.publishStoredMigration(id, prepared)
} else {
stored = prepared
}
options?.signal?.throwIfAborted()
return this.tracker.adopt(new JsonlSessionHandle(this, id, stored.meta, 'write', {
cursor: stored.events.length,
materialized: true,
tornTruncateTo: stored.tornTruncateTo,
recoveredTail: stored.recoveredTail,
inheritedEventCount: stored.inheritedEventCount,
primed: stored,
}, lease))
} catch (error) {
// Free the in-process claim no matter how the kernel-lock release
// fares, and keep the original diagnostic: a release failure joins it
// instead of replacing it.
/* v8 ignore next -- typed backends and fs reject with Error */
const failure = error instanceof Error ? error : new Error(String(error))
let releaseFailure: Error | undefined
try {
await lease?.release()
} catch (raw: unknown) {
/* v8 ignore next -- lock releases reject with Error */
releaseFailure = raw instanceof Error ? raw : new Error(String(raw))
}
this.tracker.releaseClaim(id)
if (releaseFailure !== undefined) {
throw new AggregateError([failure, releaseFailure], `session "${id}": write open failed and its lock release failed`)
}
throw failure
}
}
/**
* Flush every active write handle in one durability barrier; see the seam
* contract.
* @returns resolution once every write handle active at the call has flushed.
*/
flush(): Promise<void> {
return this.tracker.flushAll()
}
/**
* Observe one stored session without reading its event log.
* @param id - the stored session to observe.
* @param options - optional cancellation.
* @returns the snapshot (`sizeBytes` carries the physical artifact size), or
* `undefined` when the session does not exist.
*/
async stat(
id: SessionId,
options?: SessionPersistenceStatOptions,
): Promise<SessionPersistenceSnapshot | undefined> {
options?.signal?.throwIfAborted()
await this.ensureRootEncoding()
options?.signal?.throwIfAborted()
const pending = this.tracker.pendingOf(id)
if (pending !== undefined) {
return { header: pending.header, revision: pending.revision }
}
const selected = await this.findLog(id, options?.signal)
if (selected === undefined) return undefined
const metadata = await this.readGenerationHeader(selected, id, options?.signal)
if (metadata === undefined) return undefined
try {
const identity = await stat(selected.sourcePath, { bigint: true })
options?.signal?.throwIfAborted()
return {
...metadata,
revision: selected.sourceVersion < SESSION_FORMAT_VERSION
? SessionPersistenceRevision(`${fileRevision(identity)}:${await this.historicalCorpusRevision(options?.signal)}`)
: fileRevision(identity),
sizeBytes: Number(identity.size),
}
} catch (error: unknown) {
options?.signal?.throwIfAborted()
if (isENOENT(error)) return undefined
throw error
}
}
/**
* List every stored session visible to this process: materialized artifacts
* plus this process's created-but-unmaterialized sessions.
* @param options - optional cancellation.
* @returns one snapshot per session, in no promised order.
*/
async list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]> {
const signal = options?.signal
const snapshots: SessionPersistenceSnapshot[] = []
const listed = new Set<SessionId>()
// Snapshot pending entries BEFORE scanning storage: a session whose first
// append lands mid-scan is then still in this snapshot (its artifact may
// predate the scan), so create-to-list visibility never has a hole.
const pending = [...this.tracker.pendingEntries()]
const artifacts = await this.listArtifacts(signal)
const corpusRevision = artifacts.some(artifact => artifact.sourceVersion < SESSION_FORMAT_VERSION)
? await this.historicalCorpusRevision(signal) : undefined
const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => {
signal?.throwIfAborted()
try {
const identity = await stat(artifact.path, { bigint: true })
signal?.throwIfAborted()
return { artifact, identity }
} catch (error: unknown) {
signal?.throwIfAborted()
if (!isENOENT(error)) throw error
return undefined
}
}))
for (const entry of statted) {
if (entry === undefined) continue
const { artifact, identity } = entry
listed.add(artifact.header.id)
snapshots.push({
header: artifact.header,
formatStatus: artifact.formatStatus,
revision: artifact.sourceVersion < SESSION_FORMAT_VERSION
? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`)
: fileRevision(identity),
sizeBytes: Number(identity.size),
})
}
for (const [id, entry] of pending) {
if (!listed.has(id)) snapshots.push({ header: entry.header, revision: entry.revision })
}
signal?.throwIfAborted()
return snapshots
}
// --- handle-facing storage internals (package-private via the handle class below) ---
/** Resolve and read one stored log, refusing loudly when the artifact is absent. */
private async requireStoredLog(id: SessionId, signal?: AbortSignal): Promise<StoredLog> {
const selected = await this.findLog(id, signal)
if (selected === undefined) throw new SessionPersistenceNotFoundError(id)
if (selected.sourceVersion < SESSION_FORMAT_VERSION) {
const sourceRevision = fileRevision(await stat(selected.sourcePath, { bigint: true }))
signal?.throwIfAborted()
let preparation = this.migrationPreparations.get(id)
if (preparation === undefined
|| preparation.sourcePath !== selected.sourcePath
|| preparation.sourceRevision !== sourceRevision) {
const controller = new AbortController()
const promise = this.loadStoredMigration(id, selected, sourceRevision, controller.signal)
preparation = {
sourcePath: selected.sourcePath,
sourceRevision,
controller,
promise,
settled: false,
waiters: 0,
}
this.migrationPreparations.set(id, preparation)
const created = preparation
const release = (): void => {
created.settled = true
if (this.migrationPreparations.get(id) === created) {
this.migrationPreparations.delete(id)
}
}
void promise.then(release, release)
}
signal?.throwIfAborted()
return this.waitForPreparation(id, preparation, signal)
}
if (selected.sourceVersion > SESSION_FORMAT_VERSION) {
const header = await this.readGenerationHeader(selected, id, signal)
/* v8 ignore else -- a readable future header is rejected inside readGenerationHeader. */
if (header === undefined) {
throw new SessionPersistenceCorruptionError(
`session "${id}": stored log has a malformed header (raw log: ${selected.sourcePath})`,
{ cause: new Error('malformed Session header') },
)
}
/* v8 ignore next -- readGenerationHeader rejects every future version. */
throw new SessionFormatUnsupportedError(
`${sessionFormatVersionRefusal(id, selected.sourceVersion)} (raw log: ${selected.sourcePath})`,
{ kind: 'jsonl', path: selected.sourcePath },
)
}
const probe = fileRevision(await stat(selected.sourcePath, { bigint: true }))
const memoized = this.coldLogMemo.get(id)
if (memoized?.status === 'current' && memoized.revision === probe) {
this.coldLogMemo.delete(id)
this.coldLogMemo.set(id, memoized)
return memoized
}
const current = await readStableJsonlFile(selected.sourcePath, signal)
return this.decodeStoredLog(
selected.sourcePath,
id,
current.bytes,
fileRevision(current.identity),
signal,
)
}
/** Probe the memo and otherwise decode one historical generation under backend cancellation. */
private async loadStoredMigration(
id: SessionId,
selected: ResolvedJsonlGeneration,
sourceRevision: PersistenceRevision,
signal: AbortSignal,
): Promise<PreparedStoredLog> {
signal.throwIfAborted()
const memoized = this.coldLogMemo.get(id)
if (memoized?.status === 'prepared' && memoized.revision === sourceRevision) {
try {
await memoized.validateRelatedSources()
} catch (error: unknown) {
this.coldLogMemo.delete(id)
throw this.generationFailure(id, selected, error)
}
this.coldLogMemo.delete(id)
this.coldLogMemo.set(id, memoized)
return memoized
}
return this.prepareStoredMigration(id, selected, signal)
}
/** Await shared preparation for one caller and abort it only after its last waiter leaves. */
private async waitForPreparation(
id: SessionId,
preparation: MigrationPreparation,
signal?: AbortSignal,
): Promise<PreparedStoredLog> {
preparation.waiters += 1
try {
return await waitWithAbort(preparation.promise, signal)
} finally {
preparation.waiters -= 1
if (preparation.waiters === 0 && !preparation.settled) {
/* v8 ignore else -- a newer selected source may already own this id's preparation slot. */
if (this.migrationPreparations.get(id) === preparation) {
this.migrationPreparations.delete(id)
}
preparation.controller.abort()
}
}
}
/** Decode one historical generation without publishing a successor. */
private async prepareStoredMigration(
id: SessionId,
selected: ResolvedJsonlGeneration,
signal: AbortSignal,
): Promise<PreparedStoredLog> {
let prepared: Awaited<ReturnType<typeof prepareJsonlMigration>>
let validateRelatedSources: () => Promise<void>
try {
const children = async () => (await this.listArtifacts(signal))
.filter(source => source.header.origin === 'subagent' && source.header.parentSession === id)
const sources = await children()
const related = await prepareCatalogFacts(id, sources, this.compression, signal)
for (const failure of related.failures) {
this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
}
const membership = sources.map(source => source.path).sort()
validateRelatedSources = async () => {
const current = (await children()).map(source => source.path).sort()
const before = new Set(membership)
const after = new Set(current)
const changed = current.find(path => !before.has(path)) ?? membership.find(path => !after.has(path))
if (changed !== undefined) throw new JsonlGenerationSourceChangedError(changed)
await related.validate()
}
prepared = await prepareJsonlMigration({
sourcePath: selected.sourcePath,
sourceVersion: selected.sourceVersion,
currentPath: selected.currentPath,
compression: this.compression,
format: {
...this.generationFormat,
createRestore: header => createSessionFormatCatalogWithChildren(related.facts).createRestore(header, {
recovery: 'recoverable', validation: 'transformed',
}),
},
validateRelatedSources,
verifyCurrentFile: verifyCurrentGenerationInWorker,
validateHistoricalHeader: headerValue => this.validateSourceIdentity(
selected,
headerValue,
id,
signal,
),
signal,
})
} catch (error: unknown) {
throw this.generationFailure(id, selected, error)
}
const meta = this.currentHeader(prepared.artifact.header)
assertStoredId(id, meta)
const events = prepared.artifact.events as SessionEvent[]
validateStoredEvents(meta, events, { kind: 'jsonl', path: selected.sourcePath })
const stored: PreparedStoredLog = {
status: 'prepared',
validateRelatedSources,
meta,
...freezeStoredEvents(events),
tornTruncateTo: undefined,
recoveredTail: [],
inheritedEventCount: SessionLogOffset(prepared.artifact.inheritedEventCount),
revision: fileRevision(prepared.sourceIdentity),
publication: { source: selected, value: prepared },
}
this.memoizeStoredLog(id, stored)
return stored
}
/** Publish a prepared historical log before granting write access. */
private async publishStoredMigration(id: SessionId, stored: PreparedStoredLog): Promise<CurrentStoredLog> {
const migration = stored.publication
let identity: JsonlPhysicalIdentity
try {
identity = await migration.value.publish()
} catch (error: unknown) {
/* v8 ignore else -- a newer preparation may have replaced this stale cache entry. */
if (this.coldLogMemo.get(id) === stored) this.coldLogMemo.delete(id)
throw this.generationFailure(id, migration.source, error)
}
const published: CurrentStoredLog = {
status: 'current',
meta: stored.meta,
eventState: stored.eventState,
events: stored.events,
tornTruncateTo: stored.tornTruncateTo,
recoveredTail: stored.recoveredTail,
inheritedEventCount: stored.inheritedEventCount,
revision: fileRevision(identity),
}
this.memoizeStoredLog(id, published)
return published
}
/** Translate generation-layer failures into the persistence seam's error vocabulary. */
private generationFailure(
id: SessionId,
selected: ResolvedJsonlGeneration,
error: unknown,
): Error {
if (error instanceof JsonlGenerationUnsupportedMigrationError) {
return new SessionFormatUnsupportedError(
`${error.message}; source v${error.fromVersion} artifact remains unchanged (raw log: ${selected.sourcePath})`,
{ kind: 'jsonl', path: selected.sourcePath },
)
}
if (error instanceof JsonlGenerationSourceChangedError) return error
if (error instanceof SessionFormatUnsupportedError
|| error instanceof SessionPersistenceCorruptionError
|| isErrnoException(error)
|| error instanceof DOMException && error.name === 'AbortError') return error
return new SessionPersistenceCorruptionError(
`session "${id}": stored log is corrupt: ${String(error)} (raw log: ${selected.sourcePath})`,
{ cause: error },
)
}
/**
* Read, parse, and validate one stored log as the current logical prefix.
* @param path - the artifact file to read.
* @param expectedId - the session identity the artifact must carry.
* @param signal - optional cancellation for the stat/read/decode work.
* @returns the validated stored log with any torn-tail truncation point.
*/
async readStoredLog(path: string, expectedId: SessionId, signal?: AbortSignal): Promise<CurrentStoredLog> {
signal?.throwIfAborted()
const probe = fileRevision(await stat(path, { bigint: true }))
const memoized = this.coldLogMemo.get(expectedId)
if (memoized?.status === 'current' && memoized.revision === probe) {
this.coldLogMemo.delete(expectedId)
this.coldLogMemo.set(expectedId, memoized)
return memoized
}
const { bytes, identity } = await readStableJsonlFile(path, signal)
return this.decodeStoredLog(path, expectedId, bytes, fileRevision(identity), signal)
}
/** Decode and memoize one already-stable current physical snapshot. */
private async decodeStoredLog(
path: string,
expectedId: SessionId,
buffer: Buffer,
revision: PersistenceRevision,
signal?: AbortSignal,
): Promise<CurrentStoredLog> {
let parsed: {
meta: SessionHeader
inheritedEventCount: SessionLogOffsetType
events: SessionEvent[]
tornTruncateTo: number | undefined
recoveredTail: SessionEvent[]
}
try {
if (this.compression === 'zstd') {
parsed = await this.readZstdPrefix(buffer, signal)
} else {
signal?.throwIfAborted()
const { meta, inheritedEventCount, events, committedBytes } = scanLog(buffer)
signal?.throwIfAborted()
parsed = {
meta,
inheritedEventCount,
events,
tornTruncateTo: committedBytes < buffer.byteLength ? committedBytes : undefined,
// A torn raw tail is one incomplete JSONL line; it holds no complete
// record to recover.
recoveredTail: [],
}
}
} catch (error: unknown) {
signal?.throwIfAborted()
// A parse-time format refusal predates any SessionHeader, so attach the
// artifact this read actually refused; every other parse failure is
// committed bytes the decoder cannot interpret — damage, classified for
// the seam's stable error vocabulary.
if (error instanceof SessionFormatUnsupportedError) {
throw new SessionFormatUnsupportedError(`${error.message} (raw log: ${path})`, { kind: 'jsonl', path })
}
throw new SessionPersistenceCorruptionError(`session "${expectedId}": stored log is corrupt: ${String(error)} (raw log: ${path})`, { cause: error })
}
signal?.throwIfAborted()
await this.assertStoredIdentity(path, SESSION_FORMAT_VERSION, parsed.meta, expectedId, signal)
signal?.throwIfAborted()
assertStoredId(expectedId, parsed.meta)
const location = this.locate(parsed.meta)
validateStoredEvents(parsed.meta, parsed.events, location)
const { events, ...rest } = parsed
const stored: CurrentStoredLog = {
status: 'current',
...rest,
...freezeStoredEvents(events),
revision,
}
this.memoizeStoredLog(expectedId, stored)
return stored
}
/** Insert one parsed log into the bounded handoff cache. */
private memoizeStoredLog(id: SessionId, stored: StoredLog): void {
this.coldLogMemo.delete(id)
this.coldLogMemo.set(id, stored)
for (const oldest of this.coldLogMemo.keys()) {
if (this.coldLogMemo.size <= COLD_LOG_MEMO_MAX_ENTRIES) break
this.coldLogMemo.delete(oldest)
}
}
/**
* Resolve a session's current-generation log path.
* @param id - the stored session to locate.
* @param signal - optional cancellation for the directory scans.
* @returns the current artifact path, or `undefined` while only a historical generation exists.
*/
async resolveCurrentLog(id: SessionId, signal?: AbortSignal): Promise<string | undefined> {
await this.ensureRootEncoding()
signal?.throwIfAborted()
const selected = await this.findLog(id, signal)
if (selected === undefined) return undefined
if (selected.sourceVersion === SESSION_FORMAT_VERSION) return selected.sourcePath
if (selected.sourceVersion < SESSION_FORMAT_VERSION) return undefined
const reason = sessionFormatVersionRefusal(id, selected.sourceVersion)
throw new SessionFormatUnsupportedError(
`${reason} (raw log: ${selected.sourcePath})`,
{ kind: 'jsonl', path: selected.sourcePath },
)
}
/**
* Durably append one validated batch; lazily materializes on the first write.
* @param header - the session's stored header.
* @param events - the validated contiguous batch, in seq order.
* @param isMaterialized - whether the session already has a durable artifact.
* @param inheritedEventCount - the exact fork-inherited prefix length written into a materializing header line.
*/
async persistBatch(
header: SessionHeader,
events: readonly SessionEvent[],
isMaterialized: boolean,
inheritedEventCount: SessionLogOffsetType,
): Promise<void> {
this.coldLogMemo.delete(header.id)
await this.ensureRootEncoding()
if (isMaterialized) {
await this.appendLines(header, events)
} else {
await this.materialize(header, inheritedEventCount, events)
this.tracker.materialized(header.id)
}
}
/**
* Materialize a header-only artifact for an explicitly durable empty session.
* @param header - the session's stored header.
* @param inheritedEventCount - the exact fork-inherited prefix length written into the header line.
*/
async persistHeader(header: SessionHeader, inheritedEventCount: SessionLogOffsetType): Promise<void> {
this.coldLogMemo.delete(header.id)
await this.ensureRootEncoding()
await this.materialize(header, inheritedEventCount, [])
this.tracker.materialized(header.id)
}
/**
* Truncate a torn physical tail durably before this session's first new append.
* @param header - the session's stored header.
* @param truncateTo - the byte offset the artifact is truncated to.
*/
async truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void> {
this.coldLogMemo.delete(header.id)
await this.repair(header, truncateTo)
this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
}
/**
* Whether this process still tracks a created-but-unmaterialized session.
* @param id - the session to test.
* @returns true while the pending entry exists.
*/
hasPendingSession(id: SessionId): boolean {
return this.tracker.hasPending(id)
}
/**
* Release one handle's backend bookkeeping on close.
* @param handle - the closing handle.
* @param materialized - whether the session reached durable storage.
*/
releaseHandle(handle: JsonlSessionHandle, materialized: boolean): void {
this.tracker.release(handle, materialized)
}
/**
* Acquire the session directory's kernel write lock; the kernel holds it
* until the handle's close releases the descriptor, including on process death.
* @param id - the session the lock guards.
* @param cwd - header cwd used to derive the directory for a fresh session.
* @param dir - the resolved directory of an existing artifact, when known.
* @returns the held lock.
*/
private acquireLease(id: SessionId, cwd: string | undefined, dir = sessionDir(this.root, cwd, id)): Promise<SessionWriteLease> {
return SessionWriteLease.acquire(dir, id)
}
/**
* Acquire the cross-process write lock for a materializing created session,
* called by its handle immediately before the first log bytes publish.
* @param header - the session's stored header (its cwd derives the directory).
* @returns the held lock.
*/
async acquireWriteLease(header: SessionHeader): Promise<SessionWriteLease> {
// Refuse an opposite-encoding artifact before the lock's mkdir publishes
// the session directory — the last moment the directory can be absent.
await this.rejectOppositeArtifact(header.cwd, header.id)
return this.acquireLease(header.id, header.cwd)
}
/** Decode complete frames and retain complete JSONL records from a torn final frame. */
private async readZstdPrefix(
buffer: Buffer,
signal?: AbortSignal,
): Promise<{
meta: SessionHeader
inheritedEventCount: SessionLogOffsetType
events: SessionEvent[]
tornTruncateTo: number | undefined
recoveredTail: SessionEvent[]