@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-alpha.3 → 0.2.2-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/types/catalog-migration.d.ts.map +1 -0
- package/lib/types/catalog-migration.js.map +1 -0
- package/lib/types/format.d.ts.map +1 -0
- package/lib/types/format.js.map +1 -0
- package/lib/types/generation.d.ts.map +1 -0
- package/lib/types/generation.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/lease.d.ts.map +1 -0
- package/lib/types/lease.js.map +1 -0
- package/lib/types/migration-verifier.d.ts.map +1 -0
- package/lib/types/migration-verifier.js.map +1 -0
- package/lib/types/storage.d.ts.map +1 -0
- package/lib/types/storage.js.map +1 -0
- package/lib/types/testing/generation.d.ts.map +1 -0
- package/lib/types/testing/generation.js.map +1 -0
- package/lib/types/win32.d.ts.map +1 -0
- package/lib/types/win32.js.map +1 -0
- package/lib/types/worker.d.ts.map +1 -0
- package/lib/types/worker.js.map +1 -0
- package/lib/types/zstd-private-decoder.d.ts.map +1 -0
- package/lib/types/zstd-private-decoder.js.map +1 -0
- package/lib/types/zstd-public-decoder.d.ts.map +1 -0
- package/lib/types/zstd-public-decoder.js.map +1 -0
- package/lib/types/zstd.d.ts.map +1 -0
- package/lib/types/zstd.js.map +1 -0
- package/lib/worker.cjs +300 -103
- package/package.json +17 -14
- package/src/catalog-migration.ts +92 -0
- package/src/format.ts +538 -0
- package/src/generation.ts +1059 -0
- package/src/index.ts +1839 -0
- package/src/lease.ts +135 -0
- package/src/migration-verifier.ts +198 -0
- package/src/storage.ts +571 -0
- package/src/testing/generation.ts +16 -0
- package/src/win32.ts +208 -0
- package/src/worker.ts +56 -0
- package/src/zstd-private-decoder.ts +178 -0
- package/src/zstd-public-decoder.ts +40 -0
- package/src/zstd.ts +156 -0
package/src/lease.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-process write-ownership lock for one session's artifact directory,
|
|
3
|
+
* held for the whole life of a write handle. The arbiter is the kernel:
|
|
4
|
+
* POSIX takes a non-blocking `flock(2)` via native system support on `session.lock`
|
|
5
|
+
* beside the log, and Windows holds a named kernel semaphore derived from
|
|
6
|
+
* that path — never a file lock or handle, so readers, searches, and
|
|
7
|
+
* directory removal proceed freely while the lock is held. Contention maps
|
|
8
|
+
* to `SessionAlreadyOwnedError`; the kernel releases the lock when the
|
|
9
|
+
* holder's descriptor or last object handle closes, including on any process
|
|
10
|
+
* death, so a crashed holder never blocks a successor. A live but wedged
|
|
11
|
+
* holder keeps the lock until its process exits: there is deliberately no
|
|
12
|
+
* expiry that could expropriate a stalled writer whose resumed appends would
|
|
13
|
+
* tear the log.
|
|
14
|
+
* A POSIX lock names an inode, not a path, so after locking the holder
|
|
15
|
+
* verifies the locked inode is still the file at the lock path and retries
|
|
16
|
+
* otherwise: an unlinked-and-recreated lock file carries a fresh inode, and
|
|
17
|
+
* a lock on the orphaned one proves nothing. Removing a live session's lock
|
|
18
|
+
* file therefore forfeits exclusion on POSIX (nothing in the harness does
|
|
19
|
+
* so); Windows has no lock file at all. Readers never touch the lock.
|
|
20
|
+
* The lock is acquired at write-open of an existing artifact and, for a
|
|
21
|
+
* created session, only right before its first materializing write — an
|
|
22
|
+
* unmaterialized session has no filesystem footprint. Release never removes
|
|
23
|
+
* the POSIX lock file: every acquired lock belongs to a materialized or
|
|
24
|
+
* materializing session, and the surviving file keeps the stable inode later
|
|
25
|
+
* lockers verify against. The browser worker stubs the native flock entry to
|
|
26
|
+
* immediate success: it is single-process, so the in-process write claim
|
|
27
|
+
* already excludes every writer.
|
|
28
|
+
* @module @deepseek-ai/dsh-session-persistence-jsonl/lease
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { mkdir, open, stat } from 'node:fs/promises'
|
|
32
|
+
import type { FileHandle } from 'node:fs/promises'
|
|
33
|
+
import { join } from 'node:path'
|
|
34
|
+
import { tryLockExclusive } from '@deepseek-ai/node-addon-system/flock'
|
|
35
|
+
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
|
36
|
+
import type { SessionId } from '@deepseek-ai/dsh-session'
|
|
37
|
+
import { acquireLockHandleWin32, releaseLockHandleWin32 } from './win32.ts'
|
|
38
|
+
|
|
39
|
+
/** Base name of the kernel lock file inside a session's directory. */
|
|
40
|
+
export const LEASE_FILENAME = 'session.lock'
|
|
41
|
+
|
|
42
|
+
/** The held kernel lock: a POSIX descriptor or a Win32 semaphore handle. */
|
|
43
|
+
type HeldLock =
|
|
44
|
+
| { readonly kind: 'posix'; readonly handle: FileHandle }
|
|
45
|
+
| { readonly kind: 'win32'; readonly handle: number }
|
|
46
|
+
|
|
47
|
+
/** Whether a flock failure means another descriptor holds the lock. */
|
|
48
|
+
function isLockContention(error: unknown): boolean {
|
|
49
|
+
const code = (error as NodeJS.ErrnoException | null)?.code
|
|
50
|
+
// flock(2) reports EAGAIN; some libcs spell it EWOULDBLOCK.
|
|
51
|
+
return code === 'EAGAIN' || code === 'EWOULDBLOCK'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* One held write lock. Constructed only by {@link SessionWriteLease.acquire};
|
|
56
|
+
* `release` closes the descriptor or handle, which is what releases the lock.
|
|
57
|
+
*/
|
|
58
|
+
export class SessionWriteLease {
|
|
59
|
+
private released = false
|
|
60
|
+
|
|
61
|
+
private constructor(private readonly held: HeldLock) {}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Acquire the session directory's kernel write lock.
|
|
65
|
+
* @param dir - the session's artifact directory (created if absent).
|
|
66
|
+
* @param id - the session the lock guards, for error identities.
|
|
67
|
+
* @returns the held lock.
|
|
68
|
+
* @throws {SessionAlreadyOwnedError} while another holder keeps the lock.
|
|
69
|
+
*/
|
|
70
|
+
static async acquire(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
|
71
|
+
const path = join(dir, LEASE_FILENAME)
|
|
72
|
+
// Owner-only like materializePosix's directories: the lock may create the
|
|
73
|
+
// session directory first, and both creators must agree on the mode.
|
|
74
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
75
|
+
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
|
76
|
+
if (process.platform === 'win32') {
|
|
77
|
+
let handle: number
|
|
78
|
+
try {
|
|
79
|
+
handle = await acquireLockHandleWin32(path)
|
|
80
|
+
} catch (error: unknown) {
|
|
81
|
+
// Sharing violation: another handle already holds the write exclusion.
|
|
82
|
+
if ((error as NodeJS.ErrnoException | null)?.code === 'EBUSY') throw new SessionAlreadyOwnedError(id)
|
|
83
|
+
throw error
|
|
84
|
+
}
|
|
85
|
+
return new SessionWriteLease({ kind: 'win32', handle })
|
|
86
|
+
}
|
|
87
|
+
/* v8 ignore stop */
|
|
88
|
+
// Bounded retry: locking an inode a releasing creator just unlinked (or a
|
|
89
|
+
// recreated path) re-opens the fresh file; steady state needs one pass.
|
|
90
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
91
|
+
const handle = await open(path, 'w')
|
|
92
|
+
try {
|
|
93
|
+
try {
|
|
94
|
+
await tryLockExclusive(handle.fd)
|
|
95
|
+
} catch (error: unknown) {
|
|
96
|
+
if (isLockContention(error)) throw new SessionAlreadyOwnedError(id)
|
|
97
|
+
throw error
|
|
98
|
+
}
|
|
99
|
+
const held = await handle.stat({ bigint: true })
|
|
100
|
+
const current = await stat(path, { bigint: true }).catch((error: unknown) => {
|
|
101
|
+
if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return undefined
|
|
102
|
+
throw error
|
|
103
|
+
})
|
|
104
|
+
if (current !== undefined && current.ino === held.ino && current.dev === held.dev) {
|
|
105
|
+
return new SessionWriteLease({ kind: 'posix', handle })
|
|
106
|
+
}
|
|
107
|
+
} catch (error: unknown) {
|
|
108
|
+
await handle.close()
|
|
109
|
+
throw error
|
|
110
|
+
}
|
|
111
|
+
// The locked inode is no longer the file at the lock path: start over
|
|
112
|
+
// against whatever now stands there.
|
|
113
|
+
await handle.close()
|
|
114
|
+
}
|
|
115
|
+
throw new SessionAlreadyOwnedError(id)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Release the kernel lock by closing its descriptor or handle. The POSIX
|
|
120
|
+
* lock file is never removed: every acquired lock belongs to a
|
|
121
|
+
* materialized or materializing session, and keeping the file preserves
|
|
122
|
+
* the stable inode later lockers verify against. Idempotent.
|
|
123
|
+
*/
|
|
124
|
+
async release(): Promise<void> {
|
|
125
|
+
if (this.released) return
|
|
126
|
+
this.released = true
|
|
127
|
+
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
|
128
|
+
if (this.held.kind === 'win32') {
|
|
129
|
+
await releaseLockHandleWin32(this.held.handle)
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
/* v8 ignore stop */
|
|
133
|
+
await this.held.handle.close()
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** Isolated verification for a staged or competing current JSONL generation. */
|
|
2
|
+
|
|
3
|
+
import { Worker } from 'node:worker_threads'
|
|
4
|
+
import type { WorkerOptions } from 'node:worker_threads'
|
|
5
|
+
import type { JsonlCompression } from './format.ts'
|
|
6
|
+
import type { JsonlExpectedPrefix, JsonlVerifiedGeneration } from './generation.ts'
|
|
7
|
+
|
|
8
|
+
interface VerificationRequest {
|
|
9
|
+
readonly path: string
|
|
10
|
+
readonly compression: JsonlCompression
|
|
11
|
+
readonly expectedId: string
|
|
12
|
+
readonly expectedEventCount: number
|
|
13
|
+
readonly expectedPrefix?: JsonlExpectedPrefix
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type VerificationResponse =
|
|
17
|
+
| { readonly ok: true; readonly result: JsonlVerifiedGeneration }
|
|
18
|
+
| { readonly ok: false; readonly message: string; readonly stack?: string }
|
|
19
|
+
|
|
20
|
+
/** Process-wide memory bound for full-generation verification isolates. */
|
|
21
|
+
const MAX_CONCURRENT_VERIFIERS = 2
|
|
22
|
+
|
|
23
|
+
class VerificationScheduler {
|
|
24
|
+
private active = 0
|
|
25
|
+
private readonly waiting: Array<{ grant(): void }> = []
|
|
26
|
+
|
|
27
|
+
async run<T>(operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
28
|
+
const permit = this.acquire(signal)
|
|
29
|
+
if (permit !== undefined) await permit
|
|
30
|
+
try {
|
|
31
|
+
signal?.throwIfAborted()
|
|
32
|
+
return await operation()
|
|
33
|
+
} finally {
|
|
34
|
+
this.release()
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private acquire(signal?: AbortSignal): Promise<void> | undefined {
|
|
39
|
+
signal?.throwIfAborted()
|
|
40
|
+
if (this.active < MAX_CONCURRENT_VERIFIERS) {
|
|
41
|
+
this.active += 1
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
return new Promise<void>((resolve, reject) => {
|
|
45
|
+
const waiter = {
|
|
46
|
+
grant: (): void => {
|
|
47
|
+
signal?.removeEventListener('abort', abort)
|
|
48
|
+
resolve()
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
const abort = (): void => {
|
|
52
|
+
const index = this.waiting.indexOf(waiter)
|
|
53
|
+
this.waiting.splice(index, 1)
|
|
54
|
+
reject(verifierAbortError(signal))
|
|
55
|
+
}
|
|
56
|
+
this.waiting.push(waiter)
|
|
57
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private release(): void {
|
|
62
|
+
const next = this.waiting.shift()
|
|
63
|
+
if (next === undefined) {
|
|
64
|
+
this.active -= 1
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
next.grant()
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const verificationScheduler = new VerificationScheduler()
|
|
72
|
+
|
|
73
|
+
function workerSpawn(request: VerificationRequest): { readonly entry: string | URL; readonly options: WorkerOptions } {
|
|
74
|
+
/* v8 ignore next 3 -- built-worker coverage owns the bundled path. */
|
|
75
|
+
if (!import.meta.url.endsWith('.ts')) {
|
|
76
|
+
return {
|
|
77
|
+
entry: new URL('./worker.cjs', import.meta.url),
|
|
78
|
+
options: { workerData: request, execArgv: [] },
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const workerEntry = new URL('./worker.ts', import.meta.url)
|
|
82
|
+
const bootstrap = [
|
|
83
|
+
`import { register as registerEsm } from ${JSON.stringify(import.meta.resolve('tsx/esm/api'))}`,
|
|
84
|
+
`import { register as registerCjs } from ${JSON.stringify(import.meta.resolve('tsx/cjs/api'))}`,
|
|
85
|
+
'registerCjs()',
|
|
86
|
+
'registerEsm()',
|
|
87
|
+
`await import(${JSON.stringify(workerEntry.href)})`,
|
|
88
|
+
].join('\n')
|
|
89
|
+
return {
|
|
90
|
+
entry: new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`),
|
|
91
|
+
options: {
|
|
92
|
+
workerData: request,
|
|
93
|
+
execArgv: [],
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Verify one current generation in a fresh Worker Thread.
|
|
100
|
+
* @param path - staged or competing current-generation path.
|
|
101
|
+
* @param compression - configured physical encoding.
|
|
102
|
+
* @param expectedId - Session id expected in the decoded header.
|
|
103
|
+
* @param expectedEventCount - exact logical event count expected after decoding.
|
|
104
|
+
* @param expectedPrefix - verified physical prefix; an append tail may be present and is not validated.
|
|
105
|
+
* @param signal - optional cancellation for scheduler wait and Worker execution.
|
|
106
|
+
* @returns the worker's physical identity and digest after its natural zero exit.
|
|
107
|
+
*/
|
|
108
|
+
export function verifyCurrentGenerationInWorker(
|
|
109
|
+
path: string,
|
|
110
|
+
compression: JsonlCompression,
|
|
111
|
+
expectedId: string,
|
|
112
|
+
expectedEventCount: number,
|
|
113
|
+
expectedPrefix?: JsonlExpectedPrefix,
|
|
114
|
+
signal?: AbortSignal,
|
|
115
|
+
): Promise<JsonlVerifiedGeneration> {
|
|
116
|
+
return verificationScheduler.run(() => runVerificationWorker(
|
|
117
|
+
path,
|
|
118
|
+
compression,
|
|
119
|
+
expectedId,
|
|
120
|
+
expectedEventCount,
|
|
121
|
+
expectedPrefix,
|
|
122
|
+
signal,
|
|
123
|
+
), signal)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function runVerificationWorker(
|
|
127
|
+
path: string,
|
|
128
|
+
compression: JsonlCompression,
|
|
129
|
+
expectedId: string,
|
|
130
|
+
expectedEventCount: number,
|
|
131
|
+
expectedPrefix?: JsonlExpectedPrefix,
|
|
132
|
+
signal?: AbortSignal,
|
|
133
|
+
): Promise<JsonlVerifiedGeneration> {
|
|
134
|
+
signal?.throwIfAborted()
|
|
135
|
+
const request: VerificationRequest = {
|
|
136
|
+
path, compression, expectedId, expectedEventCount,
|
|
137
|
+
...(expectedPrefix === undefined ? {} : { expectedPrefix }),
|
|
138
|
+
}
|
|
139
|
+
const { entry, options } = workerSpawn(request)
|
|
140
|
+
const worker = new Worker(entry, options)
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
let settled = false
|
|
143
|
+
let success: Extract<VerificationResponse, { ok: true }> | undefined
|
|
144
|
+
const cleanup = (): void => {
|
|
145
|
+
signal?.removeEventListener('abort', abort)
|
|
146
|
+
}
|
|
147
|
+
const fail = (error: Error): void => {
|
|
148
|
+
/* v8 ignore next -- a late error/exit races only after another terminal callback settled. */
|
|
149
|
+
if (settled) return
|
|
150
|
+
settled = true
|
|
151
|
+
cleanup()
|
|
152
|
+
void worker.terminate().then(
|
|
153
|
+
() => { reject(error) },
|
|
154
|
+
(cleanup: unknown) => {
|
|
155
|
+
reject(new AggregateError([error, cleanup], 'migration verifier termination failed'))
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
worker.once('message', (value: unknown) => {
|
|
160
|
+
/* v8 ignore next -- a duplicate message races only after another terminal callback settled. */
|
|
161
|
+
if (settled) return
|
|
162
|
+
if (typeof value !== 'object' || value === null || typeof (value as { ok?: unknown }).ok !== 'boolean') {
|
|
163
|
+
fail(new Error('migration verifier returned an invalid response'))
|
|
164
|
+
return
|
|
165
|
+
}
|
|
166
|
+
const response = value as VerificationResponse
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
const error = new Error(response.message)
|
|
169
|
+
if (response.stack !== undefined) error.stack = response.stack
|
|
170
|
+
fail(error)
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
success = response
|
|
174
|
+
})
|
|
175
|
+
worker.once('error', fail)
|
|
176
|
+
worker.once('exit', (code) => {
|
|
177
|
+
if (settled) return
|
|
178
|
+
settled = true
|
|
179
|
+
cleanup()
|
|
180
|
+
if (success === undefined) {
|
|
181
|
+
reject(new Error(`migration verifier exited before reporting a result (code ${code})`))
|
|
182
|
+
} else if (code !== 0) {
|
|
183
|
+
reject(new Error(`migration verifier exited after reporting a result (code ${code})`))
|
|
184
|
+
} else {
|
|
185
|
+
resolve(success.result)
|
|
186
|
+
}
|
|
187
|
+
})
|
|
188
|
+
const abort = (): void => { fail(verifierAbortError(signal)) }
|
|
189
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function verifierAbortError(signal?: AbortSignal): Error {
|
|
194
|
+
const reason: unknown = signal?.reason
|
|
195
|
+
return reason instanceof Error
|
|
196
|
+
? reason
|
|
197
|
+
: new Error('migration verifier aborted', { cause: reason })
|
|
198
|
+
}
|