forked from cflmy/deepseek-harness
fix(session): retain JSONL internals and remove SQLite plugin settings
This commit is contained in:
1 parent
1409dde45a
commit
75b3dbc9d8
32 files changed
+5907
-1568
No files matched your search
@@ -118,30 +118,10 @@ export class JsonlGenerationSourceChangedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Stable JSONL source decoding and related history facts, independent of the destination. */
|
||||
export interface PrepareJsonlSourceOptions<T> {
|
||||
readonly sourcePath: string
|
||||
/** Decode or migrate the selected bytes into the destination's logical input. */
|
||||
readonly decode: (bytes: Buffer) => Promise<T>
|
||||
readonly validateRelatedSources?: () => Promise<void>
|
||||
readonly signal?: AbortSignal
|
||||
}
|
||||
|
||||
/** Prepared source whose commit rechecks the history observed during decoding. */
|
||||
export interface PreparedJsonlSource<T> {
|
||||
/** Current logical state prepared independently from durable publication. */
|
||||
export interface PreparedJsonlMigration {
|
||||
readonly sourceIdentity: JsonlPhysicalIdentity
|
||||
readonly artifact: T
|
||||
/**
|
||||
* Recheck source and related histories, then invoke the destination's atomic write.
|
||||
* The caller retains Session write ownership until this operation settles.
|
||||
* @param publish - destination-owned commit of the prepared logical input.
|
||||
* @returns the destination's committed result.
|
||||
*/
|
||||
commit<R>(publish: (artifact: T) => Promise<R>): Promise<R>
|
||||
}
|
||||
|
||||
/** Current logical state prepared independently from durable JSONL publication. */
|
||||
export interface PreparedJsonlMigration extends PreparedJsonlSource<SessionFormatArtifact> {
|
||||
readonly artifact: SessionFormatArtifact
|
||||
/** Encode, verify, and exclusively publish once; every call shares the same success or failure. */
|
||||
publish(): Promise<JsonlPhysicalIdentity>
|
||||
}
|
||||
@@ -223,7 +203,6 @@ export type JsonlGenerationRuntimeOverrides = Partial<Omit<JsonlGenerationIntern
|
||||
/** Bound generation operations used by production defaults and deterministic tests. */
|
||||
export interface JsonlGenerationRuntime {
|
||||
readStable(path: string, signal?: AbortSignal): Promise<StablePhysicalFile>
|
||||
prepareSource<T>(options: PrepareJsonlSourceOptions<T>): Promise<PreparedJsonlSource<T>>
|
||||
prepare(options: PrepareJsonlMigrationOptions): Promise<PreparedJsonlMigration>
|
||||
verify(
|
||||
path: string,
|
||||
@@ -429,17 +408,7 @@ async function consumeMigrationBytes(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode JSONL bytes through the selected codec and its adjacent version migration chain.
|
||||
* @param bytes - stable physical source snapshot.
|
||||
* @param compression - physical source encoding.
|
||||
* @param sourceVersion - version selected from the source filename.
|
||||
* @param format - source codec and logical migration factory.
|
||||
* @param validateHistoricalHeader - optional source identity check.
|
||||
* @param signal - optional cancellation during decoding.
|
||||
* @returns current logical header, inheritance count, and events.
|
||||
*/
|
||||
export async function decodeJsonlSource(
|
||||
async function decodeStreamingMigration(
|
||||
bytes: Buffer,
|
||||
compression: JsonlCompression,
|
||||
sourceVersion: number,
|
||||
@@ -915,12 +884,12 @@ function withOverrides(overrides: JsonlGenerationRuntimeOverrides): JsonlGenerat
|
||||
async function publishPreparedMigration(
|
||||
options: PrepareJsonlMigrationOptions,
|
||||
suffix: string,
|
||||
source: PreparedJsonlSource<SessionFormatArtifact>,
|
||||
artifact: SessionFormatArtifact,
|
||||
sourceIdentity: JsonlPhysicalIdentity,
|
||||
internals: JsonlGenerationInternals,
|
||||
): Promise<JsonlPhysicalIdentity> {
|
||||
await scheduler.yield()
|
||||
const { currentPath, compression, verifyCurrentFile } = options
|
||||
const artifact = source.artifact
|
||||
const { sourcePath, currentPath, compression, verifyCurrentFile } = options
|
||||
const eventCount = artifact.events.length
|
||||
let staged = await writeSyncedTemp(currentPath, suffix, compression, artifact, options.format, undefined, internals)
|
||||
try {
|
||||
@@ -934,7 +903,12 @@ async function publishPreparedMigration(
|
||||
throw new Error('staged session generation changed during verification')
|
||||
}
|
||||
await internals.barrier('before-source-check', 1)
|
||||
const published = await source.commit(() => publishCurrentExclusive(staged.path, currentPath, internals))
|
||||
await options.validateRelatedSources?.()
|
||||
const beforePublish = await internals.fs.stat(sourcePath)
|
||||
if (identity(beforePublish) !== identity(sourceIdentity)) {
|
||||
throw new JsonlGenerationSourceChangedError(sourcePath)
|
||||
}
|
||||
const published = await publishCurrentExclusive(staged.path, currentPath, internals)
|
||||
if (published && internals.platform === 'win32') staged = { ...staged, path: '' }
|
||||
await internals.barrier('after-publication', 1)
|
||||
let currentIdentity: JsonlPhysicalIdentity
|
||||
@@ -969,30 +943,6 @@ async function publishPreparedMigration(
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareSource<T>(
|
||||
options: PrepareJsonlSourceOptions<T>,
|
||||
internals: JsonlGenerationInternals,
|
||||
): Promise<PreparedJsonlSource<T>> {
|
||||
const { sourcePath, signal } = options
|
||||
const source = await readStableSnapshot(sourcePath, signal, internals.fs)
|
||||
const artifact = await options.decode(source.bytes)
|
||||
signal?.throwIfAborted()
|
||||
await options.validateRelatedSources?.()
|
||||
return {
|
||||
sourceIdentity: source.identity,
|
||||
artifact,
|
||||
async commit<R>(publish: (artifact: T) => Promise<R>): Promise<R> {
|
||||
signal?.throwIfAborted()
|
||||
await options.validateRelatedSources?.()
|
||||
if (identity(await internals.fs.stat(sourcePath)) !== identity(source.identity)) {
|
||||
throw new JsonlGenerationSourceChangedError(sourcePath)
|
||||
}
|
||||
signal?.throwIfAborted()
|
||||
return publish(artifact)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareMigration(
|
||||
options: PrepareJsonlMigrationOptions,
|
||||
internals: JsonlGenerationInternals,
|
||||
@@ -1008,35 +958,39 @@ async function prepareMigration(
|
||||
if (sourceVersion >= format.currentVersion) {
|
||||
throw new Error(`migration preparation requires a historical source, got v${sourceVersion}`)
|
||||
}
|
||||
const source = await prepareSource<SessionFormatArtifact>({
|
||||
sourcePath,
|
||||
...signal === undefined ? {} : { signal },
|
||||
...options.validateRelatedSources === undefined ? {} : { validateRelatedSources: options.validateRelatedSources },
|
||||
async decode(bytes) {
|
||||
let artifact: SessionFormatArtifact
|
||||
try {
|
||||
artifact = await decodeJsonlSource(bytes, compression, sourceVersion, format, options.validateHistoricalHeader, signal)
|
||||
} catch (error: unknown) {
|
||||
if (format.isUnsupportedMigrationError?.(error) === true) {
|
||||
throw new JsonlGenerationUnsupportedMigrationError(sourceVersion, error)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (artifact.header.version !== format.currentVersion) {
|
||||
throw new Error(`format migration returned v${artifact.header.version}, expected v${format.currentVersion}`)
|
||||
}
|
||||
return artifact
|
||||
},
|
||||
}, internals)
|
||||
const source = await readStableSnapshot(sourcePath, signal, internals.fs)
|
||||
let artifact: SessionFormatArtifact
|
||||
try {
|
||||
artifact = await decodeStreamingMigration(
|
||||
source.bytes,
|
||||
compression,
|
||||
sourceVersion,
|
||||
format,
|
||||
options.validateHistoricalHeader,
|
||||
signal,
|
||||
)
|
||||
} catch (error: unknown) {
|
||||
if (format.isUnsupportedMigrationError?.(error) === true) {
|
||||
throw new JsonlGenerationUnsupportedMigrationError(sourceVersion, error)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (artifact.header.version !== format.currentVersion) {
|
||||
throw new Error(`format migration returned v${artifact.header.version}, expected v${format.currentVersion}`)
|
||||
}
|
||||
await options.validateRelatedSources?.()
|
||||
const sourceIdentity = source.identity
|
||||
let publication: Promise<JsonlPhysicalIdentity> | undefined
|
||||
return {
|
||||
...source,
|
||||
sourceIdentity,
|
||||
artifact,
|
||||
publish() {
|
||||
if (publication === undefined) {
|
||||
publication = publishPreparedMigration(
|
||||
options,
|
||||
suffix,
|
||||
source,
|
||||
artifact,
|
||||
sourceIdentity,
|
||||
internals,
|
||||
)
|
||||
}
|
||||
@@ -1045,15 +999,6 @@ async function prepareMigration(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a stable JSONL snapshot for a destination-owned commit without writing another JSONL generation.
|
||||
* @param options - source path, logical decoder, related-source checks, and cancellation.
|
||||
* @returns decoded input and a commit operation that rechecks its source snapshot.
|
||||
*/
|
||||
export function prepareJsonlSource<T>(options: PrepareJsonlSourceOptions<T>): Promise<PreparedJsonlSource<T>> {
|
||||
return defaultGenerationRuntime.prepareSource(options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode and migrate one historical generation without writing its successor.
|
||||
* @param options - resolved source, current target, format adapter, and load cancellation.
|
||||
@@ -1076,7 +1021,6 @@ export function createJsonlGenerationRuntime(
|
||||
const internals = withOverrides(overrides)
|
||||
return {
|
||||
readStable: (path, signal) => readStableSnapshot(path, signal, internals.fs),
|
||||
prepareSource: options => prepareSource(options, internals),
|
||||
prepare: options => prepareMigration(options, internals),
|
||||
verify: (path, compression, expectedId, expectedEventCount, expectedPrefix) => verifyCurrentGeneration(
|
||||
path, compression, expectedId, expectedEventCount, internals.fs, expectedPrefix,
|
||||
@@ -1106,7 +1050,7 @@ export async function readDecodedJsonlSource(
|
||||
const source = await readStableJsonlFile(path, signal)
|
||||
let artifact: SessionFormatArtifact
|
||||
try {
|
||||
artifact = await decodeJsonlSource(source.bytes, compression, version, format, undefined, signal)
|
||||
artifact = await decodeStreamingMigration(source.bytes, compression, version, format, undefined, signal)
|
||||
} catch (error: unknown) {
|
||||
if (signal?.aborted || error instanceof SessionFormatError) throw error
|
||||
throw new SessionFormatError(String(error), { cause: error })
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -52,12 +52,11 @@ function isLockContention(error: unknown): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* One artifact write lock and an optional root-wide creation guard.
|
||||
* `release` attempts both locks, preserving independent release failures.
|
||||
* One held write lock. Constructed only by {@link SessionWriteLease.acquire};
|
||||
* `release` closes the descriptor or handle, which is what releases the lock.
|
||||
*/
|
||||
export class SessionWriteLease {
|
||||
private released = false
|
||||
private guard: SessionWriteLease | undefined
|
||||
|
||||
private constructor(private readonly held: HeldLock) {}
|
||||
|
||||
@@ -65,24 +64,10 @@ export class SessionWriteLease {
|
||||
* Acquire the session directory's kernel write lock.
|
||||
* @param dir - the session's artifact directory (created if absent).
|
||||
* @param id - the session the lock guards, for error identities.
|
||||
* @param guardDir - optional root-wide creation lock, acquired before the artifact lock and held until release.
|
||||
* @returns the held lock.
|
||||
* @throws {SessionAlreadyOwnedError} while another holder keeps the lock.
|
||||
*/
|
||||
static async acquire(dir: string, id: SessionId, guardDir?: string): Promise<SessionWriteLease> {
|
||||
const guard = guardDir === undefined ? undefined : await SessionWriteLease.acquireDirectory(guardDir, id)
|
||||
try {
|
||||
const lease = await SessionWriteLease.acquireDirectory(dir, id)
|
||||
lease.guard = guard
|
||||
return lease
|
||||
} catch (error: unknown) {
|
||||
try { await guard?.release() }
|
||||
catch (releaseError: unknown) { throw new AggregateError([error, releaseError], 'Session lock acquisition and rollback failed') }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private static async acquireDirectory(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
||||
static async acquire(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
||||
const path = join(dir, LEASE_FILENAME)
|
||||
// Owner-only like materializePosix's directories: the lock may create the
|
||||
// session directory first, and both creators must agree on the mode.
|
||||
@@ -139,16 +124,12 @@ export class SessionWriteLease {
|
||||
async release(): Promise<void> {
|
||||
if (this.released) return
|
||||
this.released = true
|
||||
const failures: unknown[] = []
|
||||
try {
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (this.held.kind === 'win32') await releaseLockHandleWin32(this.held.handle)
|
||||
else await this.held.handle.close()
|
||||
/* v8 ignore stop */
|
||||
} catch (error: unknown) { failures.push(error) }
|
||||
try { await this.guard?.release() }
|
||||
catch (error: unknown) { failures.push(error) }
|
||||
if (failures.length > 1) throw new AggregateError(failures, 'Session write locks failed to release')
|
||||
if (failures.length === 1) throw failures[0]
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (this.held.kind === 'win32') {
|
||||
await releaseLockHandleWin32(this.held.handle)
|
||||
return
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
await this.held.handle.close()
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/** Shared bounded filesystem scheduling for Session listings. @module */
|
||||
import type { LimitFunction } from 'p-limit'
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export 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.
|
||||
*/
|
||||
export function settledValues<R>(outcomes: readonly PromiseSettledResult<R>[]): R[] {
|
||||
return outcomes.map((outcome) => {
|
||||
if (outcome.status === 'rejected') throw outcome.reason
|
||||
return outcome.value
|
||||
})
|
||||
}
|
||||
+2
-2
@@ -12,10 +12,10 @@ export interface LegacySessionSnapshot {
|
||||
readonly events: readonly SessionEvent[]
|
||||
}
|
||||
|
||||
/** Prepared logical history with source revalidation shared by destination commits. */
|
||||
/** Prepared logical history retained under Session ownership until import. */
|
||||
export interface PreparedLegacySession extends LegacySessionSnapshot {
|
||||
/**
|
||||
* Recheck the prepared source before the destination transaction while Session ownership remains held.
|
||||
* Commit the prepared history while Session ownership remains held.
|
||||
* @param publish - destination-owned atomic import of the prepared snapshot.
|
||||
* @returns completed destination commit.
|
||||
*/
|
||||
+11
-34
@@ -4,39 +4,20 @@ import { link, mkdir, open, readFile, readdir, rm } from 'node:fs/promises'
|
||||
import { join, resolve } from 'node:path'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { z } from 'zod'
|
||||
import { settleLimited, settledValues } from '../listing.ts'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-llm'
|
||||
import { SessionPersistence, SessionAlreadyExistsError, SessionPersistenceNotFoundError, materializeCreateHeader } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionAccess, SessionPersistenceCreateOptions, SessionPersistenceOpenOptions,
|
||||
SessionPersistenceStatOptions, SessionPersistenceListOptions } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { publishNewFileWin32, ensureDurableDirectoryWin32 } from '../win32.ts'
|
||||
import { publishNewFileWin32, ensureDurableDirectoryWin32 } from './win32.ts'
|
||||
import { SqliteLogs } from '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
import { SessionWriteLease } from '../lease.ts'
|
||||
import { sessionDir } from '../format.ts'
|
||||
import { SessionWriteLease } from './lease.ts'
|
||||
import { sessionDir } from './format.ts'
|
||||
import { LegacySessionMigration } from './migration.ts'
|
||||
import type { JsonlBackend } from './migration.ts'
|
||||
export type { JsonlBackend } from './migration.ts'
|
||||
|
||||
/** Tuning defaults shared by the plugin schema and direct provider construction. */
|
||||
export const SEGMENT_STORAGE_DEFAULTS = { busyTimeoutMs: 5000, flushDelayMs: 200, maxBufferedEvents: 256 } as const
|
||||
|
||||
/** SQLite storage location and scheduling. */
|
||||
export interface SegmentStorageConfig {
|
||||
/**
|
||||
* SQLite file, defaulting to `.segments/sessions.sqlite` beneath the JSONL root;
|
||||
* a relative path resolves against the process working directory.
|
||||
*/
|
||||
path?: string
|
||||
/** Milliseconds to wait for a locked database before failing; an integer of at least 0. Default 5000. */
|
||||
busyTimeoutMs?: number
|
||||
/** Maximum intentional batching wait in milliseconds; an integer of at least 1. Default 200. */
|
||||
flushDelayMs?: number
|
||||
/** Admitted live events that start a write before the delay; an integer of at least 1, not a memory limit. Default 256. */
|
||||
maxBufferedEvents?: number
|
||||
}
|
||||
|
||||
const marker = z.object({ id: z.string().transform(SessionId), database: z.string() }).strict()
|
||||
|
||||
/** Routes the existing logical Session API; Segment identifiers never cross this service. */
|
||||
@@ -47,17 +28,13 @@ export class TracePersistence extends SessionPersistence {
|
||||
private readonly rootPath: string
|
||||
private readonly jsonl: JsonlBackend
|
||||
constructor(ctx: Context, owner: Context, root: string,
|
||||
jsonl: JsonlBackend,
|
||||
config?: SegmentStorageConfig) {
|
||||
jsonl: JsonlBackend) {
|
||||
super(ctx)
|
||||
this.rootPath = resolve(root)
|
||||
this.directory = join(this.rootPath, '.segments')
|
||||
this.sqlite = new SqliteLogs({
|
||||
path: resolve(config?.path ?? join(this.directory, 'sessions.sqlite')),
|
||||
path: join(this.directory, 'sessions.sqlite'),
|
||||
legacyRoot: this.rootPath,
|
||||
busyTimeoutMs: config?.busyTimeoutMs ?? SEGMENT_STORAGE_DEFAULTS.busyTimeoutMs,
|
||||
flushDelayMs: config?.flushDelayMs ?? SEGMENT_STORAGE_DEFAULTS.flushDelayMs,
|
||||
maxBufferedEvents: config?.maxBufferedEvents ?? SEGMENT_STORAGE_DEFAULTS.maxBufferedEvents,
|
||||
publish: id => this.publish(id),
|
||||
acquireCreationLease: header => this.acquireCreationLease(header),
|
||||
report: (id, error) => { owner.logger.error(`Segment persistence failed for ${id}; durability checkpoint will reject: ${String(error)}`) },
|
||||
@@ -76,13 +53,12 @@ export class TracePersistence extends SessionPersistence {
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim a new identity across backends before its first write, retaining both locks until handle close.
|
||||
* Claim the existing artifact lock before a new Session first commits.
|
||||
* @param header - pending Session metadata.
|
||||
* @returns the artifact lock and its root-wide creation guard.
|
||||
* @returns the held artifact lock.
|
||||
*/
|
||||
protected async acquireCreationLease(header: SessionHeader): Promise<SessionWriteLease> {
|
||||
const guard = join(this.rootPath, '.creation-locks', createHash('sha256').update(header.id).digest('hex'))
|
||||
const lease = await SessionWriteLease.acquire(sessionDir(this.rootPath, header.cwd, header.id), header.id, guard)
|
||||
const lease = await SessionWriteLease.acquire(sessionDir(this.rootPath, header.cwd, header.id), header.id)
|
||||
try {
|
||||
if (await this.jsonl.hasStoredJsonl(header.id)) {
|
||||
throw new SessionAlreadyExistsError(header.id)
|
||||
@@ -209,7 +185,7 @@ export class TracePersistence extends SessionPersistence {
|
||||
// A row omitted for its header is still stored; only a routing record without a row is lost state.
|
||||
const known = new Set([...segmented.map(entry => entry.header.id), ...omitted])
|
||||
const entries = await this.jsonl.list(options, known)
|
||||
settledValues(await settleLimited(this.jsonl.listLimit, names.filter(name => name.endsWith('.json')), async (name) => {
|
||||
const routes = await Promise.allSettled(names.filter(name => name.endsWith('.json')).map(name => this.jsonl.listLimit(async () => {
|
||||
options?.signal?.throwIfAborted()
|
||||
const path = join(this.directory, name)
|
||||
const text = await readFile(path, { encoding: 'utf8', signal: options?.signal })
|
||||
@@ -221,7 +197,8 @@ export class TracePersistence extends SessionPersistence {
|
||||
if (!known.has(stored.id)) {
|
||||
throw new HarnessError('Recorded Segment Session is missing; restore its database before listing Sessions', 'SESSION_STORAGE_MISSING')
|
||||
}
|
||||
}))
|
||||
})))
|
||||
for (const route of routes) if (route.status === 'rejected') throw route.reason
|
||||
options?.signal?.throwIfAborted()
|
||||
return [...entries.filter(entry => !known.has(entry.header.id)), ...segmented]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,572 @@
|
||||
/**
|
||||
* The JSONL provider's session storage runtime: its concrete write/read
|
||||
* handle with a per-handle mutation chain and a routed live write-behind
|
||||
* buffer, the in-process bookkeeping that enforces one active writer per
|
||||
* session id, and the backend's live event routing and teardown. Deliberately
|
||||
* provider-local: the persistence seam exposes only the service and handle
|
||||
* contracts, and the shared contract suites pin equivalent observable
|
||||
* behavior across providers.
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { errorChain } from '@deepseek-ai/dsh-llm'
|
||||
import type { Session, SessionEvent, SessionHeader, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import {
|
||||
assertContiguous,
|
||||
SessionAlreadyExistsError,
|
||||
materializeAppendBatch,
|
||||
SessionAlreadyOwnedError,
|
||||
SessionHandleClosedError,
|
||||
SessionPersistenceNotFoundError,
|
||||
type SessionPersistenceRevision,
|
||||
SessionReadOnlyError,
|
||||
} from '@deepseek-ai/dsh-session-persistence'
|
||||
import type {
|
||||
SessionAccess,
|
||||
SessionHandle,
|
||||
SessionHandleAppendOptions,
|
||||
SessionHandleFlushOptions,
|
||||
SessionHandleReadOptions,
|
||||
SessionHandleReadResult,
|
||||
} from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionWriteLease } from './lease.ts'
|
||||
|
||||
/** Maximum intentional wait before a routed live session batch starts writing. */
|
||||
export const LIVE_WRITE_BATCH_MAX_DELAY_MS = 200
|
||||
|
||||
/** The file-storage primitives the handle drives on its owning service. */
|
||||
export interface JsonlHandleStorage {
|
||||
/** Append encoded lines; `isMaterialized` selects create-vs-extend publication. */
|
||||
persistBatch(
|
||||
header: SessionHeader,
|
||||
events: readonly SessionEvent[],
|
||||
isMaterialized: boolean,
|
||||
inheritedEventCount: SessionLogOffset,
|
||||
): Promise<void>
|
||||
/** Materialize the header-only artifact for an explicitly flushed empty session. */
|
||||
persistHeader(header: SessionHeader, inheritedEventCount: SessionLogOffset): Promise<void>
|
||||
/** Truncate a torn physical tail before the first new append lands. */
|
||||
truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void>
|
||||
/** Resolve the current-generation artifact path, or `undefined` when absent. */
|
||||
resolveCurrentLog(id: SessionId, signal?: AbortSignal): Promise<string | undefined>
|
||||
/** Read and validate the stored log at `path`, including its established event aliasing state. */
|
||||
readStoredLog(path: string, expectedId: SessionId, signal?: AbortSignal): Promise<SessionHandleReadResult>
|
||||
/** Whether the id is still a created-but-unmaterialized session here. */
|
||||
hasPendingSession(id: SessionId): boolean
|
||||
/** Acquire the session's cross-process write lock in its artifact directory. */
|
||||
acquireWriteLease(header: SessionHeader): Promise<SessionWriteLease>
|
||||
/** Drop the handle's bookkeeping on close. */
|
||||
releaseHandle(handle: JsonlSessionHandle, materialized: boolean): void
|
||||
}
|
||||
|
||||
/** Mutable per-handle log state; a write handle is its session's single mutator. */
|
||||
export interface StorageHandleState {
|
||||
/** The stored next-seq (the logical end this handle knows). */
|
||||
cursor: number
|
||||
/** Whether the session has a durable artifact yet. */
|
||||
materialized: boolean
|
||||
/** Torn-tail truncation point, consumed by the first new append. */
|
||||
tornTruncateTo?: number | undefined
|
||||
/** Complete events recovered from the torn final frame; the first mutation rewrites them durably. */
|
||||
recoveredTail?: SessionEvent[] | undefined
|
||||
/** Exact fork-inherited prefix length stored with the log; `0` when unseeded. */
|
||||
inheritedEventCount: SessionLogOffset
|
||||
/** The validated stored prefix from a write open, served to reads until the first append. */
|
||||
primed?: SessionHandleReadResult | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The JSONL session handle. Mutations serialize on a per-handle promise
|
||||
* chain; reads re-scan the artifact on demand and never observe a shorter log
|
||||
* than a prior read on this handle. Routed live events buffer in a bounded
|
||||
* window and drain through the same chain as explicit appends.
|
||||
*/
|
||||
export class JsonlSessionHandle implements SessionHandle {
|
||||
private chain: Promise<unknown> = Promise.resolve()
|
||||
private closing: Promise<void> | undefined
|
||||
private observedLength = 0
|
||||
/** Routed live events awaiting their batching deadline (persistence-owned copies). */
|
||||
private buffered: SessionEvent[] = []
|
||||
private batchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
/** Set when a drain failed; the automatic timer stays quiet until the next drain. */
|
||||
private drainPaused = false
|
||||
private draining: Promise<void> | undefined
|
||||
|
||||
constructor(
|
||||
private readonly storage: JsonlHandleStorage,
|
||||
readonly id: SessionId,
|
||||
readonly header: SessionHeader,
|
||||
readonly access: SessionAccess,
|
||||
private readonly state: StorageHandleState,
|
||||
/** The cross-process write lock; a create handle acquires it lazily at first materialization. */
|
||||
private lease?: SessionWriteLease,
|
||||
) {}
|
||||
|
||||
/** Exact fork-inherited prefix length stored with this session's log. */
|
||||
get inheritedEventCount(): SessionLogOffset {
|
||||
return this.state.inheritedEventCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a slice of the valid contiguous logical log; see the seam contract.
|
||||
* @param offset - first logical seq to include (default 0).
|
||||
* @param length - maximum events returned (default: the rest).
|
||||
* @param options - optional cancellation.
|
||||
* @returns a slice carrying the aliasing state established by its producer.
|
||||
*/
|
||||
async read(offset = 0, length = Number.MAX_SAFE_INTEGER, options?: SessionHandleReadOptions): Promise<SessionHandleReadResult> {
|
||||
// Closed-handle refusal precedes argument validation: a closed handle
|
||||
// rejects SessionHandleClosedError regardless of the arguments.
|
||||
this.assertOpen('read')
|
||||
if (!Number.isSafeInteger(offset) || offset < 0) {
|
||||
throw new TypeError(`read offset must be a non-negative safe integer, got ${String(offset)}`)
|
||||
}
|
||||
if (!Number.isSafeInteger(length) || length < 0) {
|
||||
throw new TypeError(`read length must be a non-negative safe integer, got ${String(length)}`)
|
||||
}
|
||||
options?.signal?.throwIfAborted()
|
||||
let result: SessionHandleReadResult
|
||||
const primed = this.state.primed
|
||||
if (primed !== undefined) {
|
||||
if (this.access === 'write') {
|
||||
result = this.readPrimed(primed, offset, length)
|
||||
} else {
|
||||
const currentPath = await this.storage.resolveCurrentLog(this.id, options?.signal)
|
||||
if (currentPath === undefined) {
|
||||
result = this.readPrimed(primed, offset, length)
|
||||
} else {
|
||||
this.state.primed = undefined
|
||||
result = await this.readCurrent(currentPath, offset, length, options?.signal)
|
||||
}
|
||||
}
|
||||
} else if (this.access === 'write' && !this.state.materialized) {
|
||||
result = { eventState: 'detached', events: [] }
|
||||
} else {
|
||||
const currentPath = await this.storage.resolveCurrentLog(this.id, options?.signal)
|
||||
if (currentPath !== undefined) {
|
||||
result = await this.readCurrent(currentPath, offset, length, options?.signal)
|
||||
} else if (this.storage.hasPendingSession(this.id)) {
|
||||
result = { eventState: 'detached', events: [] }
|
||||
} else {
|
||||
throw new SessionPersistenceNotFoundError(this.id)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** Read one slice from the prepared historical prefix retained by this handle. */
|
||||
private readPrimed(source: SessionHandleReadResult, offset: number, length: number): SessionHandleReadResult {
|
||||
this.observedLength = Math.max(this.observedLength, source.events.length)
|
||||
return { eventState: source.eventState, events: source.events.slice(offset, offset + length) }
|
||||
}
|
||||
|
||||
/** Read one current physical generation and enforce this handle's monotonic view. */
|
||||
private async readCurrent(
|
||||
path: string,
|
||||
offset: number,
|
||||
length: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SessionHandleReadResult> {
|
||||
const source = await this.storage.readStoredLog(path, this.id, signal)
|
||||
if (source.events.length < this.observedLength) {
|
||||
throw new Error(`session "${this.id}": stored log shrank below a previously observed prefix (${source.events.length} < ${this.observedLength})`)
|
||||
}
|
||||
this.observedLength = source.events.length
|
||||
return {
|
||||
eventState: source.eventState,
|
||||
events: source.events.slice(offset, offset + length),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Durably append a contiguous batch; see the seam contract.
|
||||
* @param events - the contiguous batch in seq order.
|
||||
* @param options - optional cancellation observed before the write starts.
|
||||
*/
|
||||
async append(events: readonly SessionEvent[], options?: SessionHandleAppendOptions): Promise<void> {
|
||||
this.assertOpen('append')
|
||||
// Validate and deep-snapshot the batch HERE, before queueing behind the
|
||||
// chain, so the checked value is exactly the value persisted.
|
||||
const batch = materializeAppendBatch(events)
|
||||
return this.run('append', async () => {
|
||||
options?.signal?.throwIfAborted()
|
||||
await this.persistContiguous(batch)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Durability barrier; materializes the artifact when nothing has been
|
||||
* appended yet, so an explicitly flushed empty session survives this process.
|
||||
* @param options - optional cancellation observed before the barrier starts.
|
||||
*/
|
||||
flush(options?: SessionHandleFlushOptions): Promise<void> {
|
||||
return this.run('flush', async () => {
|
||||
options?.signal?.throwIfAborted()
|
||||
if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush')
|
||||
if (this.state.materialized) return // appends are durable on resolution
|
||||
await this.ensureLease()
|
||||
await this.storage.persistHeader(this.header, this.state.inheritedEventCount)
|
||||
this.state.materialized = true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the handle; see the seam contract. Idempotent and uncancellable.
|
||||
* A write handle first drains its routed live buffer through the still-open
|
||||
* storage, so backend teardown loses nothing regardless of which fiber
|
||||
* unwinds first; a drain or lock-release failure still frees the in-process
|
||||
* claim, then rejects — both failures together reject as one
|
||||
* `AggregateError`.
|
||||
* @returns settlement of the release.
|
||||
*/
|
||||
close(): Promise<void> {
|
||||
return this.closing ??= (async () => {
|
||||
let drainFailure: unknown
|
||||
// Producers on other fibers may still publish while close waits for
|
||||
// in-flight mutations (root disposal is concurrent), so drain again
|
||||
// until a full pass leaves the routed buffer empty. The chain never
|
||||
// rejects because run() swallows each operation's rejection after its
|
||||
// caller observed it.
|
||||
for (;;) {
|
||||
try {
|
||||
await this.drainLive()
|
||||
} catch (error: unknown) {
|
||||
drainFailure = error
|
||||
break
|
||||
}
|
||||
await this.chain
|
||||
if (this.buffered.length === 0) break
|
||||
}
|
||||
// After a drain failure the chain may still hold in-flight mutations.
|
||||
await this.chain
|
||||
// Free the in-process claim no matter how the kernel-lock release
|
||||
// fares: a skipped releaseHandle would wedge the id in this process
|
||||
// behind a lock the kernel may already have dropped.
|
||||
const failures: Error[] = []
|
||||
if (drainFailure !== undefined) {
|
||||
failures.push(drainFailure instanceof Error ? drainFailure : new Error(errorChain(drainFailure)))
|
||||
}
|
||||
try {
|
||||
await this.lease?.release()
|
||||
} catch (releaseFailure: unknown) {
|
||||
/* v8 ignore next -- lock releases reject with Error */
|
||||
failures.push(releaseFailure instanceof Error ? releaseFailure : new Error(errorChain(releaseFailure)))
|
||||
}
|
||||
this.storage.releaseHandle(this, this.state.materialized)
|
||||
if (failures.length > 1) throw new AggregateError(failures, `session "${this.id}": close failed to drain and to release its write lock`)
|
||||
if (failures[0] !== undefined) throw failures[0]
|
||||
})()
|
||||
}
|
||||
|
||||
/** `await using` support: delegates to {@link close}. */
|
||||
[Symbol.asyncDispose](): Promise<void> {
|
||||
return this.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer one published live session event and arm the bounded batching
|
||||
* window when it is idle. The routing installer is the only caller.
|
||||
* @param event - the live event, retained as a persistence-owned copy.
|
||||
* @param reportBackgroundFailure - observes a deadline-driven drain failure
|
||||
* (the events stay buffered; the next {@link drainLive} retries loudly).
|
||||
*/
|
||||
enqueueLive(event: SessionEvent, reportBackgroundFailure: (error: unknown) => void): void {
|
||||
this.buffered.push(structuredClone(event))
|
||||
if (this.batchTimer !== undefined || this.drainPaused) return
|
||||
this.batchTimer = setTimeout(() => {
|
||||
this.batchTimer = undefined
|
||||
this.drainLive().catch(reportBackgroundFailure)
|
||||
}, LIVE_WRITE_BATCH_MAX_DELAY_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Durably drain the routed live buffer through the mutation chain;
|
||||
* concurrent callers join one drain, and a failure retains the batch in
|
||||
* order so `session/flush` can retry and reject loudly.
|
||||
*/
|
||||
drainLive(): Promise<void> {
|
||||
return this.draining ??= this.drainBuffered().finally(() => {
|
||||
this.draining = undefined
|
||||
})
|
||||
}
|
||||
|
||||
private async drainBuffered(): Promise<void> {
|
||||
if (this.batchTimer !== undefined) {
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = undefined
|
||||
}
|
||||
this.drainPaused = false
|
||||
while (this.buffered.length > 0) {
|
||||
// Capture inside the chained turn so events landing while an earlier
|
||||
// batch writes coalesce into the next one, in order.
|
||||
await this.enqueueChain(async () => {
|
||||
// Only this single-flight drain splices the buffer, so the batch the
|
||||
// while-guard saw is still here when the chained turn runs.
|
||||
const batch = this.buffered.splice(0)
|
||||
try {
|
||||
await this.persistContiguous(materializeAppendBatch(batch))
|
||||
} catch (error: unknown) {
|
||||
this.buffered = batch.concat(this.buffered)
|
||||
this.drainPaused = true
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** The shared durable-append body: contiguity, ownership, torn-tail repair, storage write, state advance. */
|
||||
private async persistContiguous(batch: readonly SessionEvent[]): Promise<void> {
|
||||
if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'append')
|
||||
if (batch.length === 0) return
|
||||
await this.ensureLease()
|
||||
assertContiguous(this.id, batch, this.state.cursor)
|
||||
// Commit any pending torn-tail repair first, clearing each step's state
|
||||
// only once it lands so a failed step retries on the next mutation:
|
||||
// truncate the torn bytes, then durably rewrite the complete events
|
||||
// recovered from them (already counted in the primed cursor).
|
||||
if (this.state.tornTruncateTo !== undefined) {
|
||||
await this.storage.truncateTornTail(this.header, this.state.tornTruncateTo)
|
||||
this.state.tornTruncateTo = undefined
|
||||
}
|
||||
if (this.state.recoveredTail !== undefined) {
|
||||
if (this.state.recoveredTail.length > 0) {
|
||||
await this.storage.persistBatch(this.header, this.state.recoveredTail, this.state.materialized, this.state.inheritedEventCount)
|
||||
}
|
||||
this.state.recoveredTail = undefined
|
||||
}
|
||||
await this.storage.persistBatch(this.header, batch, this.state.materialized, this.state.inheritedEventCount)
|
||||
this.state.materialized = true
|
||||
this.state.cursor += batch.length
|
||||
this.state.primed = undefined
|
||||
this.observedLength = this.state.cursor
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold the cross-process write lock before this session's first durable
|
||||
* write. An open write handle holds it from construction; a create handle
|
||||
* acquires it here — immediately before the first log bytes publish — and
|
||||
* keeps it through close even when materialization then fails, so a
|
||||
* materializing session stays exclusively owned across retries.
|
||||
*/
|
||||
private async ensureLease(): Promise<void> {
|
||||
this.lease ??= await this.storage.acquireWriteLease(this.header)
|
||||
}
|
||||
|
||||
/** Serialize one operation onto the chain without the closed-handle refusal (drain-from-close). */
|
||||
private enqueueChain(op: () => Promise<void>): Promise<void> {
|
||||
const next = this.chain.then(op)
|
||||
this.chain = next.catch(() => {})
|
||||
return next
|
||||
}
|
||||
|
||||
/** Serialize one public mutating operation onto this handle's chain. */
|
||||
private async run(operation: string, op: () => Promise<void>): Promise<void> {
|
||||
this.assertOpen(operation)
|
||||
return this.enqueueChain(async () => {
|
||||
this.assertOpen(operation)
|
||||
return op()
|
||||
})
|
||||
}
|
||||
|
||||
private assertOpen(operation: string): void {
|
||||
if (this.closing !== undefined) throw new SessionHandleClosedError(this.id, operation)
|
||||
}
|
||||
}
|
||||
|
||||
/** One created-but-unmaterialized session tracked in this process only. */
|
||||
export interface PendingSession {
|
||||
readonly header: SessionHeader
|
||||
readonly revision: SessionPersistenceRevision
|
||||
/** Exact fork-inherited prefix length supplied at create. */
|
||||
readonly inheritedEventCount: SessionLogOffset
|
||||
}
|
||||
|
||||
/**
|
||||
* The JSONL backend's in-process bookkeeping: the single active writer per
|
||||
* session id (doubling as the live event router), the open-handle set the
|
||||
* teardown sweep closes, and the created-but-unmaterialized sessions this
|
||||
* process can already observe.
|
||||
*/
|
||||
export class JsonlBackendTracker {
|
||||
/** Every open handle; teardown closes what remains. */
|
||||
readonly openHandles = new Set<SessionHandle>()
|
||||
/** `null` marks a claim whose handle is still being constructed. */
|
||||
private readonly writers = new Map<SessionId, JsonlSessionHandle | null>()
|
||||
private readonly pending = new Map<SessionId, PendingSession>()
|
||||
private counter = 0
|
||||
|
||||
/** @param name - backend label used in in-memory revision tokens and teardown errors. */
|
||||
constructor(private readonly name: string) {}
|
||||
|
||||
/**
|
||||
* Claim write ownership and record the created session as pending, making
|
||||
* it observable to this process before it materializes. Before
|
||||
* materialization this registration is the only guard — session ids do not
|
||||
* collide across processes, and no durable artifact exists for another
|
||||
* process to open; the handle takes the cross-process lock at its first
|
||||
* materializing write.
|
||||
* @param header - the validated detached header.
|
||||
* @param inheritedEventCount - the exact fork-inherited prefix length.
|
||||
* @throws {SessionAlreadyExistsError} when a concurrent create or an open
|
||||
* write handle holds the id — for create, the duplicate is the fact.
|
||||
*/
|
||||
registerCreated(header: SessionHeader, inheritedEventCount: SessionLogOffset): void {
|
||||
if (this.writers.has(header.id)) throw new SessionAlreadyExistsError(header.id)
|
||||
this.writers.set(header.id, null)
|
||||
this.pending.set(header.id, {
|
||||
header,
|
||||
revision: brandString<SessionPersistenceRevision>(`memory:${this.name}:${++this.counter}`),
|
||||
inheritedEventCount,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim write ownership for an existing session.
|
||||
* @param id - the session to claim.
|
||||
* @throws {SessionAlreadyOwnedError} when an active write handle exists.
|
||||
*/
|
||||
claimWrite(id: SessionId): void {
|
||||
if (this.writers.has(id)) throw new SessionAlreadyOwnedError(id)
|
||||
this.writers.set(id, null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Roll a failed write open back.
|
||||
* @param id - the session whose claim is dropped.
|
||||
*/
|
||||
releaseClaim(id: SessionId): void {
|
||||
this.writers.delete(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* The pending entry for a created-but-unmaterialized session, if any.
|
||||
* @param id - the session to look up.
|
||||
* @returns the pending header and in-memory revision.
|
||||
*/
|
||||
pendingOf(id: SessionId): PendingSession | undefined {
|
||||
return this.pending.get(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this process still tracks a created-but-unmaterialized session.
|
||||
* @param id - the session to test.
|
||||
* @returns true while the pending entry exists.
|
||||
*/
|
||||
hasPending(id: SessionId): boolean {
|
||||
return this.pending.has(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the pending sessions for listing.
|
||||
* @returns the pending entries, keyed by session id.
|
||||
*/
|
||||
pendingEntries(): IterableIterator<[SessionId, PendingSession]> {
|
||||
return this.pending.entries()
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a pending entry once the session materialized durably.
|
||||
* @param id - the session that reached durable storage.
|
||||
*/
|
||||
materialized(id: SessionId): void {
|
||||
this.pending.delete(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Track one open handle for teardown and, for a write handle, bind it as
|
||||
* the session's live event route.
|
||||
* @param handle - the just-constructed handle.
|
||||
* @returns the same handle, for construction-site chaining.
|
||||
*/
|
||||
adopt(handle: JsonlSessionHandle): JsonlSessionHandle {
|
||||
this.openHandles.add(handle)
|
||||
if (handle.access === 'write') this.writers.set(handle.id, handle)
|
||||
return handle
|
||||
}
|
||||
|
||||
/**
|
||||
* Release one handle's bookkeeping on close. A write handle drops its
|
||||
* ownership claim; a creator that never materialized leaves nothing behind —
|
||||
* the session never existed.
|
||||
* @param handle - the closing handle.
|
||||
* @param materialized - whether the session reached durable storage.
|
||||
*/
|
||||
release(handle: JsonlSessionHandle, materialized: boolean): void {
|
||||
this.openHandles.delete(handle)
|
||||
if (handle.access !== 'write') return
|
||||
this.writers.delete(handle.id)
|
||||
if (!materialized) this.pending.delete(handle.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain and flush every active write handle — the service-wide durability
|
||||
* barrier behind `SessionPersistence.flush`.
|
||||
* @throws {AggregateError} naming each session whose flush failed; the
|
||||
* remaining handles still flush.
|
||||
*/
|
||||
async flushAll(): Promise<void> {
|
||||
const errors: unknown[] = []
|
||||
for (const writer of [...this.writers.values()]) {
|
||||
if (writer === null) continue // a claim mid-construction routes nothing yet
|
||||
try {
|
||||
await writer.drainLive()
|
||||
await writer.flush()
|
||||
} catch (error: unknown) {
|
||||
// A handle closed during the sweep counts as flushed: close itself
|
||||
// drained the routed buffer durably before refusing this flush.
|
||||
if (error instanceof SessionHandleClosedError) continue
|
||||
errors.push(error)
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) throw new AggregateError(errors, `${this.name} flush failed`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the backend's live session routing and teardown. Persistence
|
||||
* enforces one active write handle per id, so the listeners route published
|
||||
* sessions' events by id; the teardown effect closes every open handle —
|
||||
* close drains the routed buffer — and aggregates failures. This provider
|
||||
* owns no separate storage connection, so closing handles is the complete
|
||||
* teardown. The returned effect removes listeners before closing handles.
|
||||
* @param ctx - the backend's resource-owning context.
|
||||
* @returns the disposer to run after persistence consumers finish unloading.
|
||||
*/
|
||||
install(ctx: Context): () => Promise<void> {
|
||||
const { writers, openHandles, name } = this
|
||||
return ctx.effect(function* () {
|
||||
yield async () => {
|
||||
const errors: unknown[] = []
|
||||
for (const handle of [...openHandles]) {
|
||||
try {
|
||||
await handle.close()
|
||||
} catch (error: unknown) {
|
||||
errors.push(error)
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) throw new AggregateError(errors, `${name} dispose failed`)
|
||||
}
|
||||
yield ctx.on('session/event', (session: Session, event) => {
|
||||
writers.get(session.id)?.enqueueLive(event, (error) => {
|
||||
ctx.logger.warn(`session-persistence: background write for session "${session.id}" failed (buffered events retained): ${String(error)}`)
|
||||
})
|
||||
})
|
||||
yield ctx.on('session/flush', (session: Session) => {
|
||||
const writer = writers.get(session.id)
|
||||
if (writer === null || writer === undefined) return undefined
|
||||
return (async () => {
|
||||
await writer.drainLive()
|
||||
await writer.flush()
|
||||
})()
|
||||
})
|
||||
yield ctx.on('session/disposed', (session: Session) => {
|
||||
const writer = writers.get(session.id)
|
||||
if (writer === null || writer === undefined) return
|
||||
writer.close().catch((error: unknown) => {
|
||||
ctx.logger.warn(`session-persistence: final drain for session "${session.id}" failed: ${String(error)}`)
|
||||
})
|
||||
})
|
||||
}, `${this.name} live routing and open handles`)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Windows durable namespace helpers for Session persistence backends.
|
||||
* Windows durable namespace helpers for the JSONL backend.
|
||||
*
|
||||
* POSIX publishes a newly-created log by creating a directory entry and then
|
||||
* fsyncing the parent directory. Windows does not expose that parent-directory
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { SessionId, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { SessionFormatUnsupportedError, SessionPersistenceCorruptionError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import * as JsonlSessionPersistence from './fixtures/legacy-persistence.ts'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { generationLogPath } from '../src/format.ts'
|
||||
import { prepareCatalogFacts } from '../src/catalog-migration.ts'
|
||||
import { importedRows } from './fixtures/segments.ts'
|
||||
import { compressZstdFrame } from '../src/zstd.ts'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
@@ -81,7 +80,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
expect(await f.read()).toMatchObject(expected)
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
try { expect((await writer.read()).events).toMatchObject(expected) } finally { await writer.close() }
|
||||
expect(importedRows(f.root, f.parent).slice(1)).toMatchObject(expected)
|
||||
expect(await readFile(generationLogPath(f.root, undefined, f.parent, 4, compression))).not.toHaveLength(0)
|
||||
for (const access of ['read', 'write'] as const) {
|
||||
await expect(f.ctx.sessionPersistence.open(brandString<SessionId>('unrelated'), access)).rejects.toThrow()
|
||||
}
|
||||
@@ -122,9 +121,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
expect((await f.ctx.sessionPersistence.list()).find(row => row.header.id === f.parent)?.revision).toBe(first)
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
await writer.close()
|
||||
const imported = (await f.ctx.sessionPersistence.stat(f.parent))!.revision
|
||||
expect(imported).not.toBe(first)
|
||||
expect((await f.ctx.sessionPersistence.stat(f.parent))!.revision).toBe(imported)
|
||||
expect((await f.ctx.sessionPersistence.stat(f.parent))!.revision).toBe(first)
|
||||
})
|
||||
|
||||
it('invalidates historical revisions when selected children disappear or gain an opaque successor', async () => {
|
||||
@@ -256,7 +253,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
try { expect((await child.read()).events).toEqual(events) } finally { await child.close() }
|
||||
expect(await Promise.all([readFile(parentPath), readFile(childPath)])).toEqual(original)
|
||||
expect((await readdir(dirname(parentPath))).filter(name => name !== 'session.lock').sort())
|
||||
.toEqual(compression === 'none' ? ['session.v3.jsonl'] : ['session.v3.jsonl.zstd'])
|
||||
.toEqual(compression === 'none' ? ['session.v3.jsonl', 'session.v4.jsonl'] : ['session.v3.jsonl.zstd', 'session.v4.jsonl.zstd'])
|
||||
})
|
||||
|
||||
it.each([false, true])('omits an unsupported child generation (prepared=%s)', async (prepared) => {
|
||||
@@ -264,7 +261,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
await f.write('child', [f.descriptor], true)
|
||||
if (prepared) expect(await f.read()).toHaveLength(1)
|
||||
await f.write('child', [], true, 5)
|
||||
expect(await f.read()).toHaveLength(prepared ? 1 : 0)
|
||||
expect(await f.read()).toEqual([])
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
await writer.close()
|
||||
await expect(f.ctx.sessionPersistence.open(brandString<SessionId>('child'), 'read')).rejects.toBeInstanceOf(SessionFormatUnsupportedError)
|
||||
@@ -310,14 +307,37 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
await writer.close()
|
||||
})
|
||||
|
||||
it('keeps the imported parent catalog fixed when legacy child files subsequently change', async () => {
|
||||
it('detects children added after preparation instead of publishing incomplete membership', async () => {
|
||||
const f = await fixture()
|
||||
expect(await f.read()).toEqual([])
|
||||
await f.write('child', [f.descriptor], true)
|
||||
await expect(f.ctx.sessionPersistence.open(f.parent, 'write')).rejects.toThrow(generationLogPath(f.root, undefined, brandString<SessionId>('child'), 3, compression))
|
||||
expect(await f.read()).toHaveLength(1)
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
try { expect((await writer.read()).events).toEqual([]) } finally { await writer.close() }
|
||||
const child = await f.ctx.sessionPersistence.open(brandString<SessionId>('child'), 'read')
|
||||
try { expect((await child.read()).events).toEqual([f.descriptor]) } finally { await child.close() }
|
||||
await writer.close()
|
||||
})
|
||||
|
||||
it('recollects newly available discovery fields before publishing a prepared parent', async () => {
|
||||
const f = await fixture()
|
||||
const childPath = await f.write('child', [], true)
|
||||
expect(await f.read()).toMatchObject([{ type: 'subagent/catalog', data: { childId: 'child', mode: 'unknown' } }])
|
||||
await f.write('child', [f.descriptor], true)
|
||||
await expect(f.ctx.sessionPersistence.open(f.parent, 'write')).rejects.toThrow(childPath)
|
||||
const parentPath = generationLogPath(f.root, undefined, f.parent, 3, compression)
|
||||
expect((await readdir(dirname(parentPath))).filter(name => name !== 'session.lock'))
|
||||
.toEqual([compression === 'none' ? 'session.v3.jsonl' : 'session.v3.jsonl.zstd'])
|
||||
expect(await f.read()).toMatchObject([{ type: 'subagent/catalog', data: { childId: 'child', label: 'old child' } }])
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
await writer.close()
|
||||
})
|
||||
|
||||
it('reads current children without recursive migration and preserves current parent fast reads', async () => {
|
||||
const f = await fixture()
|
||||
await f.write('child', [f.descriptor], true, 4)
|
||||
expect(await f.read()).toHaveLength(1)
|
||||
await f.write(f.parent, [], false, 4)
|
||||
await f.write('child', [], true, 4)
|
||||
expect(await f.read()).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses publication when a related child disappears', async () => {
|
||||
@@ -354,7 +374,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
await writer.close()
|
||||
expect(await Promise.all([readFile(parentPath), readFile(childPath)])).toEqual(before)
|
||||
expect((await readdir(dirname(parentPath))).filter(name => name !== 'session.lock')).toHaveLength(1)
|
||||
expect((await readdir(dirname(parentPath))).filter(name => name !== 'session.lock')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('lists historical headers, prepares read-only membership, and publishes an unchanged-prefix successor', async () => {
|
||||
@@ -388,7 +408,7 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
expect(expected).toEqual([{ type: 'subagent/catalog', seq: 0, time: 1, data: {
|
||||
version: 0, childId: child, childCreatedAt: 2, mode: 'one-shot', label: 'old child',
|
||||
} }])
|
||||
expect((await readdir(dirname(sourcePaths[0]!))).filter(name => name !== 'session.lock')).toEqual([compression === 'none' ? 'session.v3.jsonl' : 'session.v3.jsonl.zstd'])
|
||||
expect(await readdir(dirname(sourcePaths[0]!))).toEqual([compression === 'none' ? 'session.v3.jsonl' : 'session.v3.jsonl.zstd'])
|
||||
} finally { await reader.close() }
|
||||
const writer = await ctx.sessionPersistence.open(parent, 'write')
|
||||
try { expect((await writer.read()).events).toEqual(expected) } finally { await writer.close() }
|
||||
@@ -412,12 +432,13 @@ describe.each(['none', 'zstd'] as const)('historical catalog publication (%s)',
|
||||
await f.write('child', [{ type: 'future/required', seq: 0, time: 2, data: {} }], true)
|
||||
const writer = await f.ctx.sessionPersistence.open(f.parent, 'write')
|
||||
await writer.close()
|
||||
const published = importedRows(f.root, f.parent)
|
||||
const current = generationLogPath(f.root, undefined, f.parent, 4, compression)
|
||||
const published = await readFile(current)
|
||||
await f.write('child', [f.descriptor], true)
|
||||
const child = await f.ctx.sessionPersistence.open(brandString<SessionId>('child'), 'read')
|
||||
try { expect((await child.read()).events).toEqual([f.descriptor]) } finally { await child.close() }
|
||||
expect(await f.read()).toMatchObject([{ data: { childId: 'child', mode: 'unknown' } }])
|
||||
expect(importedRows(f.root, f.parent)).toEqual(published)
|
||||
expect(await readFile(current)).toEqual(published)
|
||||
})
|
||||
|
||||
it('completes only the opened parent catalog and defers its child catalog', async () => {
|
||||
|
||||
@@ -9,9 +9,9 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
|
||||
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
|
||||
const [root, sessionId, storage, pending, database] = process.argv.slice(2)
|
||||
const [root, sessionId, storage, pending] = process.argv.slice(2)
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none', segmentStorage: { ...database === undefined ? {} : { path: database } } })
|
||||
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
|
||||
const handle = await ctx.sessionPersistence.create({
|
||||
version: SESSION_FORMAT_VERSION,
|
||||
id: sessionId,
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/** Mount the retained JSONL backend for its existing storage tests. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { vi } from 'vitest'
|
||||
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SqliteLogs } from '@deepseek-ai/dsh-session-persistence-sqlite/src/sqlite.ts'
|
||||
import { JsonlBackendTracker } from '../../src/storage.ts'
|
||||
import * as persistence from '../../src/index.ts'
|
||||
import type { Config } from '../../src/index.ts'
|
||||
|
||||
export { Config, JsonlCompressionSchema } from '../../src/index.ts'
|
||||
|
||||
/** Test provider label. */
|
||||
export const name = 'session-persistence-jsonl-legacy-tests'
|
||||
|
||||
/**
|
||||
* Register the existing JSONL implementation without materializing SQLite.
|
||||
* @param ctx - test provider owner.
|
||||
* @param config - original JSONL settings.
|
||||
* @returns resolves when the JSONL provider and its event routing are available.
|
||||
*/
|
||||
export async function apply(ctx: Context, config: Config): Promise<void> {
|
||||
const source = ctx.isolate('sessionPersistence')
|
||||
const start = vi.spyOn(SqliteLogs.prototype, 'start').mockResolvedValueOnce()
|
||||
try { await persistence.apply(source, config) } finally { start.mockRestore() }
|
||||
const provider = source.reflect.get('sessionPersistence', false) as SessionPersistence
|
||||
const legacy = Reflect.get(provider, 'jsonl') as SessionPersistence
|
||||
const tracker = Reflect.get(legacy, 'tracker') as JsonlBackendTracker
|
||||
ctx.provide('sessionPersistence', legacy)
|
||||
tracker.install(ctx)
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
appendFile,
|
||||
link,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
@@ -24,8 +23,6 @@ import {
|
||||
JsonlGenerationTargetConflictError,
|
||||
JsonlGenerationUnsupportedMigrationError,
|
||||
prepareJsonlMigration,
|
||||
prepareJsonlSource,
|
||||
decodeJsonlSource,
|
||||
readDecodedJsonlSource,
|
||||
verifyJsonlCurrentGeneration,
|
||||
type JsonlGenerationFormatAdapter,
|
||||
@@ -1653,18 +1650,3 @@ describe('JSONL immutable generation publication', () => {
|
||||
expect(await readdir(root)).toEqual(['session.jsonl'])
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a destination commit when an append advanced the source after preparation', async () => {
|
||||
const path = join(await tempRoot(), `session.v${SESSION_FORMAT_VERSION}.jsonl`)
|
||||
await writeFile(path, line(header(SESSION_FORMAT_VERSION)) + line(event0))
|
||||
const source = await prepareJsonlSource({
|
||||
sourcePath: path,
|
||||
decode: bytes => decodeJsonlSource(bytes, 'none', SESSION_FORMAT_VERSION, {
|
||||
createRestore: value => sessionFormatCatalog.createRestore(value, { recovery: 'strict', validation: 'transformed' }),
|
||||
}, undefined),
|
||||
})
|
||||
await appendFile(path, line(event1))
|
||||
const destination = vi.fn(async (_artifact: SessionFormatArtifact) => {})
|
||||
await expect(source.commit(destination)).rejects.toBeInstanceOf(JsonlGenerationSourceChangedError)
|
||||
expect(destination).not.toHaveBeenCalled()
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,9 +11,8 @@
|
||||
* pinned by lease.two-process.e2e.ts.
|
||||
*/
|
||||
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdtemp, readdir, rm } from 'node:fs/promises'
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
@@ -26,10 +25,9 @@ import {
|
||||
SessionPersistenceNotFoundError,
|
||||
} from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
|
||||
import * as JsonlSessionPersistence from '../src/index.ts'
|
||||
import * as JsonlSessionPersistence from './fixtures/legacy-persistence.ts'
|
||||
import { LEASE_FILENAME, SessionWriteLease } from '../src/lease.ts'
|
||||
import { SessionWriteLease as SqliteWriteLease } from '@deepseek-ai/dsh-session-persistence-sqlite/src/lease.ts'
|
||||
import type { SqliteTrace } from '@deepseek-ai/dsh-session-persistence-sqlite/src/sqlite.ts'
|
||||
import type { JsonlSessionHandle } from '../src/storage.ts'
|
||||
import { sessionDir } from '../src/format.ts'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
@@ -144,8 +142,8 @@ function lockPath(root: string, id: string, cwd = '/work'): string {
|
||||
* close(2) that freed the descriptor but returned EIO would.
|
||||
*/
|
||||
function failReleaseOnce(): void {
|
||||
const spy = vi.spyOn(SqliteWriteLease.prototype, 'release')
|
||||
spy.mockImplementationOnce(async function (this: SqliteWriteLease) {
|
||||
const spy = vi.spyOn(SessionWriteLease.prototype, 'release')
|
||||
spy.mockImplementationOnce(async function (this: SessionWriteLease) {
|
||||
spy.mockRestore()
|
||||
await this.release()
|
||||
throw Object.assign(new Error('EIO: injected release failure'), { code: 'EIO' })
|
||||
@@ -203,8 +201,6 @@ describe('cross-process write lock', () => {
|
||||
// The documented escape hatch for a live-but-stuck holder: deleting the
|
||||
// lock file orphans the held inode, and a successor locks the fresh one.
|
||||
await rm(lockPath(root, 'wedged'))
|
||||
await expect(second.open(brandString<SessionId>('wedged'), 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
await wedged.close()
|
||||
const successor = await second.open(brandString<SessionId>('wedged'), 'write')
|
||||
await successor.append([{ type: 'turn/start', seq: SessionSeq(2), time: 3, data: { turn: 2 } }])
|
||||
await successor.close()
|
||||
@@ -371,10 +367,12 @@ describe('cross-process write lock', () => {
|
||||
const writer = await backend.create(meta('open-and-release-fail'))
|
||||
await writer.append([...EVENTS])
|
||||
await writer.close()
|
||||
const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite'))
|
||||
try {
|
||||
db.exec("DROP TRIGGER events_no_update; UPDATE events SET payload = 'null'")
|
||||
} finally { db.close() }
|
||||
// Corrupt the stored header line so the open fails after the lock is
|
||||
// acquired (a garbled tail would be recovered as torn, not refused).
|
||||
const dir = join(lockPath(root, 'open-and-release-fail'), '..')
|
||||
const log = (await readdir(dir)).find(name => name.endsWith('.jsonl'))
|
||||
const stored = await readFile(join(dir, String(log)), 'utf8')
|
||||
await writeFile(join(dir, String(log)), `#${stored.slice(1)}`)
|
||||
|
||||
failReleaseOnce()
|
||||
const outcome = await backend.open(brandString<SessionId>('open-and-release-fail'), 'write').then(() => undefined, (error: unknown) => error)
|
||||
@@ -385,18 +383,18 @@ describe('cross-process write lock', () => {
|
||||
expect(String(errors[1])).toMatch(/injected release failure/)
|
||||
// The original diagnostic survives, and the claim is freed: the next
|
||||
// attempt reports the corruption again rather than a phantom owner.
|
||||
await expect(backend.open(brandString<SessionId>('open-and-release-fail'), 'write')).rejects.toThrow(/invalid/i)
|
||||
await expect(backend.open(brandString<SessionId>('open-and-release-fail'), 'write')).rejects.toThrow(/corrupt/i)
|
||||
})
|
||||
|
||||
it('a drain failure and a release failure reject close as one AggregateError', async () => {
|
||||
const root = await freshRoot()
|
||||
const backend = await mount(root)
|
||||
const holder = await backend.create(meta('drain-and-release-fail')) as SqliteTrace
|
||||
const holder = await backend.create(meta('drain-and-release-fail')) as JsonlSessionHandle
|
||||
await holder.append([...EVENTS])
|
||||
|
||||
vi.spyOn(Reflect.get(backend, 'sqlite') as { append: () => Promise<void> }, 'append')
|
||||
vi.spyOn(backend as unknown as { persistBatch: () => Promise<void> }, 'persistBatch')
|
||||
.mockRejectedValueOnce(new Error('injected drain refusal'))
|
||||
await holder.receive({ type: 'turn/start', seq: SessionSeq(2), time: 3, data: { turn: 2 } })
|
||||
holder.enqueueLive({ type: 'turn/start', seq: SessionSeq(2), time: 3, data: { turn: 2 } }, () => {})
|
||||
failReleaseOnce()
|
||||
const outcome = await holder.close().then(() => undefined, (error: unknown) => error)
|
||||
expect(outcome).toBeInstanceOf(AggregateError)
|
||||
@@ -421,58 +419,6 @@ describe('cross-process write lock', () => {
|
||||
})
|
||||
|
||||
|
||||
it('releases a creation guard when the artifact lock is already owned', async () => {
|
||||
const root = await freshRoot(), dir = join(root, 'artifact'), guard = join(root, 'guard'), id = brandString<SessionId>('guard-rollback')
|
||||
const holder = await SessionWriteLease.acquire(dir, id)
|
||||
try {
|
||||
await expect(SessionWriteLease.acquire(dir, id, guard)).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
const available = await SessionWriteLease.acquire(guard, id)
|
||||
await available.release()
|
||||
} finally { await holder.release() }
|
||||
})
|
||||
|
||||
it('preserves acquisition and guard-release failures while freeing the guard', async () => {
|
||||
const root = await freshRoot(), dir = join(root, 'artifact'), guard = join(root, 'guard'), id = brandString<SessionId>('guard-release')
|
||||
const holder = await SessionWriteLease.acquire(dir, id)
|
||||
const failure = new Error('guard release failed')
|
||||
const spy = vi.spyOn(SessionWriteLease.prototype, 'release').mockImplementationOnce(async function (this: SessionWriteLease) {
|
||||
spy.mockRestore()
|
||||
await this.release()
|
||||
throw failure
|
||||
})
|
||||
try {
|
||||
await expect(SessionWriteLease.acquire(dir, id, guard)).rejects.toMatchObject({
|
||||
errors: [expect.any(SessionAlreadyOwnedError), failure],
|
||||
})
|
||||
} finally { spy.mockRestore(); await holder.release() }
|
||||
const available = await SessionWriteLease.acquire(guard, id)
|
||||
await available.release()
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('attempts both lock releases and preserves both failures', async () => {
|
||||
const root = await freshRoot(), dir = join(root, 'artifact'), guard = join(root, 'guard'), id = brandString<SessionId>('two-releases')
|
||||
const fs = await import('node:fs/promises'), open = fs.open
|
||||
const failures: Error[] = []
|
||||
const spy = vi.spyOn(fs, 'open').mockImplementation(async (...args) => {
|
||||
const handle = await open(...args), close = handle.close.bind(handle)
|
||||
handle.close = async () => {
|
||||
await close()
|
||||
const failure = new Error('lock descriptor close failed')
|
||||
failures.push(failure)
|
||||
throw failure
|
||||
}
|
||||
return handle
|
||||
})
|
||||
let lease: SessionWriteLease
|
||||
try { lease = await SessionWriteLease.acquire(dir, id, guard) }
|
||||
finally { spy.mockRestore() }
|
||||
await expect(lease.release()).rejects.toMatchObject({ errors: failures })
|
||||
expect(failures).toHaveLength(2)
|
||||
await lease.release()
|
||||
const available = await SessionWriteLease.acquire(dir, id, guard)
|
||||
await available.release()
|
||||
})
|
||||
|
||||
it('keeps distinct sessions independently lockable', async () => {
|
||||
const root = await freshRoot()
|
||||
const backend = await mount(root)
|
||||
|
||||
@@ -45,7 +45,7 @@ async function storedFiles(root: string): Promise<{ jsonl: boolean; database: bo
|
||||
}
|
||||
|
||||
describe('two-process SQLite write lock (built lib)', () => {
|
||||
it('excludes an pending creator in another project and releases the guard on crash', async () => {
|
||||
it('excludes a pending creator in another project and releases the Session lock on crash', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-create-2proc-'))
|
||||
dirs.push(root)
|
||||
const ctx = new Context()
|
||||
@@ -168,25 +168,3 @@ describe('two-process Segment database writers (built lib)', () => {
|
||||
expect(await storedFiles(root)).toEqual({ jsonl: false, database: true })
|
||||
})
|
||||
})
|
||||
|
||||
it('excludes a second process with another root sharing the same database, then releases ownership on crash', async () => {
|
||||
const base = await mkdtemp(join(tmpdir(), 'dsh-db-lease-2proc-'))
|
||||
dirs.push(base)
|
||||
const path = join(base, 'shared.sqlite')
|
||||
const ctx = new Context()
|
||||
contexts.push(ctx)
|
||||
await ctx.plugin(JsonlSessionPersistence, { root: join(base, 'reader-root'), compression: 'none',
|
||||
segmentStorage: { path } })
|
||||
const holder = spawn(process.execPath, [HOLDER, join(base, 'writer-root'), SESSION, 'segments', '', path],
|
||||
{ stdio: ['pipe', 'pipe', 'inherit'] })
|
||||
const exited = new Promise<void>((resolve) => { holder.once('exit', () => { resolve() }) })
|
||||
try {
|
||||
await Promise.race([once(holder.stdout, 'data'), exited.then(() => { throw new Error('Writer exited before acquiring its lease') })])
|
||||
await expect(ctx.sessionPersistence.open(SessionId(SESSION), 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
holder.kill('SIGKILL')
|
||||
await exited
|
||||
const resumed = await ctx.sessionPersistence.open(SessionId(SESSION), 'write')
|
||||
try { expect((await resumed.read()).events.map(event => event.type)).toEqual(['turn/start', 'turn/end']) }
|
||||
finally { await resumed.close() }
|
||||
} finally { holder.kill('SIGKILL'); await exited }
|
||||
})
|
||||
@@ -11,7 +11,7 @@ import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionWriteLease } from '../src/lease.ts'
|
||||
import { SqliteLogs, SqliteTrace } from '@deepseek-ai/dsh-session-persistence-sqlite/src/sqlite.ts'
|
||||
import * as persistence from '../src/index.ts'
|
||||
import { JsonlReader } from '../src/reader.ts'
|
||||
import type { JsonlBackend } from '../src/migration.ts'
|
||||
import { eventLines, generationLogPath, sessionDir, toHeaderLine } from '../src/format.ts'
|
||||
import { compressZstdFrame } from '../src/zstd.ts'
|
||||
import { oneTurnLog, meta } from '../../session-persistence/tests/contract.ts'
|
||||
@@ -121,11 +121,11 @@ it('refuses import while a legacy writer owns the artifact and succeeds after re
|
||||
it('excludes another provider during import, then serves the committed Session without reimporting', async () => {
|
||||
const b = await fixture(), other = await b.mount()
|
||||
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with the reader receiver below.
|
||||
const prepare = JsonlReader.prototype.prepare
|
||||
const spy = vi.spyOn(JsonlReader.prototype, 'prepare').mockImplementationOnce(async function (this: JsonlReader, ...args) {
|
||||
const legacy = Reflect.get(b.ctx.sessionPersistence, 'jsonl') as JsonlBackend
|
||||
const prepare = legacy.prepare.bind(legacy)
|
||||
const spy = vi.spyOn(legacy, 'prepare').mockImplementationOnce(async (...args) => {
|
||||
entered.resolve(undefined); await release.promise
|
||||
return prepare.call(this, ...args)
|
||||
return prepare(...args)
|
||||
})
|
||||
const opening = b.ctx.sessionPersistence.open(b.header.id, 'read')
|
||||
try {
|
||||
@@ -140,11 +140,11 @@ it('excludes another provider during import, then serves the committed Session w
|
||||
it.each(['read', 'write'] as const)('cancels a %s import before commit, releasing ownership for a later open', async (access: SessionAccess) => {
|
||||
const b = await fixture(), controller = new AbortController()
|
||||
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with the reader receiver below.
|
||||
const prepare = JsonlReader.prototype.prepare
|
||||
vi.spyOn(JsonlReader.prototype, 'prepare').mockImplementationOnce(async function (this: JsonlReader, ...args) {
|
||||
const legacy = Reflect.get(b.ctx.sessionPersistence, 'jsonl') as JsonlBackend
|
||||
const prepare = legacy.prepare.bind(legacy)
|
||||
vi.spyOn(legacy, 'prepare').mockImplementationOnce(async (...args) => {
|
||||
entered.resolve(undefined); await release.promise
|
||||
return prepare.call(this, ...args)
|
||||
return prepare(...args)
|
||||
})
|
||||
const pending = b.ctx.sessionPersistence.open(b.header.id, access, { signal: controller.signal })
|
||||
const refused = expect(pending).rejects.toMatchObject({ name: 'AbortError' })
|
||||
@@ -202,11 +202,11 @@ it.each(['missing database', 'missing row', 'corrupt database'] as const)('refus
|
||||
it('waits for an admitted import before provider teardown closes SQLite', async () => {
|
||||
const b = await fixture()
|
||||
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with the reader receiver below.
|
||||
const prepare = JsonlReader.prototype.prepare
|
||||
vi.spyOn(JsonlReader.prototype, 'prepare').mockImplementationOnce(async function (this: JsonlReader, ...args) {
|
||||
const legacy = Reflect.get(b.ctx.sessionPersistence, 'jsonl') as JsonlBackend
|
||||
const prepare = legacy.prepare.bind(legacy)
|
||||
vi.spyOn(legacy, 'prepare').mockImplementationOnce(async (...args) => {
|
||||
entered.resolve(undefined); await release.promise
|
||||
return prepare.call(this, ...args)
|
||||
return prepare(...args)
|
||||
})
|
||||
const opening = b.ctx.sessionPersistence.open(b.header.id, 'read')
|
||||
await entered.promise
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Durable EOF refusals preserve historical generations and never fall back from the selected generation. */
|
||||
|
||||
import { JsonlReader } from '../src/reader.ts'
|
||||
import type { JsonlBackend } from '../src/migration.ts'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { SESSION_FORMAT_VERSION, type SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { createSessionFormatCatalogWithChildren } from '@deepseek-ai/dsh-session-format-catalog'
|
||||
@@ -497,7 +497,8 @@ describe.each(modes)('EOF migration refusal ($compression, $access)', ({ compres
|
||||
const lowerPath = await store(2, compression, prefix)
|
||||
const lower = await observe(lowerPath)
|
||||
const ctx = await mount(compression)
|
||||
const preview = await new JsonlReader(ctx, { root, compression }).prepare(id)
|
||||
const legacy = Reflect.get(ctx.sessionPersistence, 'jsonl') as JsonlBackend
|
||||
const preview = await legacy.prepare(id)
|
||||
expect(preview.header.version).toBe(SESSION_FORMAT_VERSION)
|
||||
expect(preview.events.map(event => event.type)).toEqual([
|
||||
'turn/start', 'step/start', 'system/message', 'user/message', 'system/message', 'request/header',
|
||||
|
||||
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { generationLogPath, toHeaderLine } from '../src/format.ts'
|
||||
import { JsonlReader } from '../src/reader.ts'
|
||||
import * as persistence from '../src/index.ts'
|
||||
import { meta } from '../../session-persistence/tests/contract.ts'
|
||||
|
||||
const probe = vi.hoisted(() => ({ path: '', opens: 0 }))
|
||||
@@ -27,7 +27,8 @@ async function fixture() {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
probe.path = path
|
||||
probe.opens = 0
|
||||
return { path, header, reader: new JsonlReader(ctx, { root, compression: 'none' }) }
|
||||
await ctx.plugin(persistence, { root, compression: 'none' })
|
||||
return { path, header, reader: ctx.sessionPersistence }
|
||||
}
|
||||
|
||||
it('reuses unchanged legacy headers and detaches each returned header from its cache', async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Session creation identity and consumer teardown across persistence instances. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
@@ -26,19 +26,6 @@ async function fixture() {
|
||||
return { root, mount }
|
||||
}
|
||||
|
||||
it('ignores lock and database directories when scanning JSONL Sessions', async () => {
|
||||
const { mount, root } = await fixture()
|
||||
const ctx = await mount(), writer = await ctx.sessionPersistence.create(header)
|
||||
await writer.append([event(1)]); await writer.close()
|
||||
for (const name of ['.creation-locks', '.segments']) {
|
||||
const dir = join(root, name, 'private')
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`), 'metadata is not a Session')
|
||||
}
|
||||
const restarted = await mount()
|
||||
expect((await restarted.sessionPersistence.list()).map(entry => entry.header.id)).toEqual([header.id])
|
||||
})
|
||||
|
||||
it('preserves the identity refusal and release failure without retaining either lock', async () => {
|
||||
const { mount, root } = await fixture()
|
||||
const a = await mount(), b = await mount()
|
||||
@@ -59,7 +46,7 @@ it('preserves the identity refusal and release failure without retaining either
|
||||
await second.close()
|
||||
})
|
||||
|
||||
it('excludes another provider while the first creation holds a root-wide identity lock', async () => {
|
||||
it('excludes another provider while the first creation holds the Session write lock', async () => {
|
||||
const { mount, root } = await fixture()
|
||||
const a = await mount(), b = await mount()
|
||||
const first = await a.sessionPersistence.create(header)
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
/** SQLite Session ownership across roots sharing one database. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { mkdtemp, rm, symlink } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { SESSION_FORMAT_VERSION, SessionId, SessionSeq, type SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { SessionAlreadyExistsError, SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionWriteLease } from '../src/lease.ts'
|
||||
import { SessionWriteLease as SqliteWriteLease } from '@deepseek-ai/dsh-session-persistence-sqlite/src/lease.ts'
|
||||
import * as persistence from '../src/index.ts'
|
||||
|
||||
async function fixture() {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'dsh-shared-database-'))
|
||||
onTestFinished(() => rm(directory, { recursive: true, force: true }))
|
||||
const path = join(directory, 'sessions.sqlite')
|
||||
const mount = async (root: string, database = path) => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(persistence, { root: join(directory, root), compression: 'none', segmentStorage: { path: database } })
|
||||
return ctx.sessionPersistence
|
||||
}
|
||||
const a = await mount('a'), b = await mount('b')
|
||||
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('shared'), createdAt: 0, isSeeded: false }
|
||||
return { directory, path, mount, a, b, header }
|
||||
}
|
||||
|
||||
it('excludes a second writer across roots while allowing readers and other Sessions', async () => {
|
||||
const { a, b, header } = await fixture()
|
||||
const first = await a.create(header)
|
||||
await first.append([{ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn: 1 } }])
|
||||
await expect(b.open(header.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
const reader = await b.open(header.id, 'read')
|
||||
try { expect((await reader.read()).events).toEqual((await first.read()).events) } finally { await reader.close() }
|
||||
const other = await b.create({ ...header, id: SessionId('independent') })
|
||||
await other.flush(); await other.close()
|
||||
await first.close()
|
||||
const resumed = await b.open(header.id, 'write')
|
||||
await resumed.append([{ type: 'turn/end', seq: SessionSeq(1), time: 1, data: { turn: 1, reason: { kind: 'completed' } } }])
|
||||
await resumed.close()
|
||||
const stored = await a.open(header.id, 'read')
|
||||
try { expect((await stored.read()).events.map(event => event.type)).toEqual(['turn/start', 'turn/end']) } finally { await stored.close() }
|
||||
})
|
||||
|
||||
it('excludes competing first commits across roots and releases a losing creation', async () => {
|
||||
const { a, b, header } = await fixture()
|
||||
const first = await a.create(header), second = await b.create(header)
|
||||
await first.flush()
|
||||
await expect(second.flush()).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
await first.close()
|
||||
await expect(second.flush()).rejects.toBeInstanceOf(SessionAlreadyExistsError)
|
||||
await second.close()
|
||||
const reopened = await a.open(header.id, 'write')
|
||||
await reopened.close()
|
||||
})
|
||||
|
||||
// Windows database symlink creation requires developer mode or elevated privileges.
|
||||
it.skipIf(process.platform === 'win32')('shares ownership through a database symlink alias', async () => {
|
||||
const { directory, path, mount, a, header } = await fixture()
|
||||
const alias = join(directory, 'alias.sqlite')
|
||||
await symlink(path, alias)
|
||||
const b = await mount('alias-root', alias)
|
||||
const first = await a.create(header)
|
||||
await first.flush()
|
||||
await expect(b.open(header.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
await first.close()
|
||||
const resumed = await b.open(header.id, 'write')
|
||||
await resumed.close()
|
||||
})
|
||||
|
||||
it.each([1, 2])('releases both ownership locks when %i releases report failure', async (count) => {
|
||||
const { a, b, header } = await fixture()
|
||||
const first = await a.create(header)
|
||||
await first.flush()
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with its lease receiver.
|
||||
const release = SessionWriteLease.prototype.release
|
||||
let failures = count
|
||||
const fault = vi.spyOn(SessionWriteLease.prototype, 'release').mockImplementation(async function (this: SessionWriteLease) {
|
||||
await release.call(this)
|
||||
if (failures > 0) { failures--; throw new Error('lease release failed') }
|
||||
})
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with its lease receiver.
|
||||
const sqliteRelease = SqliteWriteLease.prototype.release
|
||||
const sqliteFault = vi.spyOn(SqliteWriteLease.prototype, 'release').mockImplementation(async function (this: SqliteWriteLease) {
|
||||
await sqliteRelease.call(this)
|
||||
if (failures > 0) { failures--; throw new Error('lease release failed') }
|
||||
})
|
||||
try { await expect(first.close()).rejects.toThrow(count === 1 ? 'lease release failed' : 'SQLite write ownership release failed') }
|
||||
finally { fault.mockRestore(); sqliteFault.mockRestore() }
|
||||
const resumed = await b.open(header.id, 'write')
|
||||
await resumed.close()
|
||||
})
|
||||
|
||||
it('preserves acquisition and rollback failures while releasing database ownership', async () => {
|
||||
const { a, b, header } = await fixture()
|
||||
const first = await a.create(header)
|
||||
const acquire = SqliteWriteLease.acquire.bind(SqliteWriteLease)
|
||||
const acquisitionFailure = new Error('artifact acquisition failed')
|
||||
const releaseFailure = new Error('shared lease rollback failed')
|
||||
const fault = vi.spyOn(SqliteWriteLease, 'acquire').mockImplementationOnce(async (...args) => {
|
||||
const shared = await acquire(...args)
|
||||
const release = shared.release.bind(shared)
|
||||
vi.spyOn(shared, 'release').mockImplementationOnce(async () => { await release(); throw releaseFailure })
|
||||
return shared
|
||||
})
|
||||
const artifactFault = vi.spyOn(SessionWriteLease, 'acquire').mockRejectedValueOnce(acquisitionFailure)
|
||||
try { await expect(first.flush()).rejects.toMatchObject({ errors: [acquisitionFailure, releaseFailure] }) }
|
||||
finally { fault.mockRestore(); artifactFault.mockRestore() }
|
||||
const winner = await b.create(header)
|
||||
await winner.flush(); await winner.close(); await first.close()
|
||||
})
|
||||
@@ -13,7 +13,7 @@ import { z } from 'zod'
|
||||
import * as plugin from '../src/index.ts'
|
||||
import { sessionDir } from '../src/format.ts'
|
||||
import { SessionWriteLease } from '@deepseek-ai/dsh-session-persistence-sqlite/src/lease.ts'
|
||||
import { TracePersistence } from '../src/trace/index.ts'
|
||||
import { TracePersistence } from '../src/persistence.ts'
|
||||
import { SqliteLogs, SqliteTrace } from '@deepseek-ai/dsh-session-persistence-sqlite/src/sqlite.ts'
|
||||
import { forkTrace, routeOf, sqliteLogs } from './fixtures/segments.ts'
|
||||
|
||||
|
||||
@@ -25,23 +25,18 @@ vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('unpublished'), createdAt: 0, isSeeded: false }
|
||||
const event = (seq: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } })
|
||||
|
||||
async function mount(root: string, path: string | undefined) {
|
||||
async function mount(root: string) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(plugin, { root, compression: 'none', segmentStorage: { ...path === undefined ? {} : { path } } })
|
||||
await ctx.plugin(plugin, { root, compression: 'none' })
|
||||
return ctx
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ database: 'default' },
|
||||
{ database: 'custom' },
|
||||
] as const)('serves a committed Session without its routing record to a fresh provider with a $database database path', async ({ database }) => {
|
||||
it('serves a committed Session without its routing record to a fresh provider', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-segment-publication-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
onTestFinished(() => { faults.routes = false })
|
||||
// A custom database lives outside the routing directory.
|
||||
const path = database === 'custom' ? join(root, 'database', 'sessions.sqlite') : undefined
|
||||
const first = await mount(root, path)
|
||||
const first = await mount(root)
|
||||
const writer = await first.sessionPersistence.create(header)
|
||||
faults.routes = true
|
||||
const failure = await writer.append([event(0)]).then(() => undefined, (error: unknown) => error)
|
||||
@@ -53,7 +48,7 @@ it.each([
|
||||
expect((await readdir(join(root, '.segments'))).filter(name => name.endsWith('.json'))).toEqual([])
|
||||
|
||||
// The committed row selects SQLite without a routing record.
|
||||
const fresh = await mount(root, path)
|
||||
const fresh = await mount(root)
|
||||
expect(await fresh.sessionPersistence.stat(header.id)).toMatchObject({ header, eventCount: 1 })
|
||||
expect((await fresh.sessionPersistence.list()).map(entry => [entry.header.id, entry.eventCount])).toEqual([[header.id, 1]])
|
||||
const reopened = await fresh.sessionPersistence.open(header.id, 'write')
|
||||
|
||||
@@ -3,8 +3,7 @@ import pLimit from 'p-limit'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
|
||||
import { TracePersistence } from '../src/trace/index.ts'
|
||||
import type { SegmentStorageConfig } from '../src/trace/index.ts'
|
||||
import { TracePersistence } from '../src/persistence.ts'
|
||||
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
@@ -58,7 +57,7 @@ vi.mock('../src/win32.ts', async (importOriginal) => {
|
||||
|
||||
class Adapter extends TracePersistence {
|
||||
readonly fileFlush: ReturnType<typeof vi.fn<SessionPersistence['flush']>>
|
||||
constructor(ctx: Context, root: string, config?: SegmentStorageConfig) {
|
||||
constructor(ctx: Context, root: string) {
|
||||
const fileFlush = vi.fn<SessionPersistence['flush']>(async () => {})
|
||||
super(ctx, ctx, root, {
|
||||
listLimit: pLimit(3),
|
||||
@@ -66,7 +65,7 @@ class Adapter extends TracePersistence {
|
||||
async stat() { return undefined },
|
||||
async list() { return [] },
|
||||
async hasStoredJsonl() { return false },
|
||||
}, config)
|
||||
})
|
||||
this.fileFlush = fileFlush
|
||||
}
|
||||
publishRoute(id: SessionId) { return this.publish(id) }
|
||||
@@ -76,12 +75,12 @@ afterEach(() => {
|
||||
faults.directory = ''; faults.directorySyncs = 0; faults.directoryCloses = 0
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
async function fixture(config?: SegmentStorageConfig) {
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-segment-routing-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const storage = new Adapter(ctx, root, config)
|
||||
const storage = new Adapter(ctx, root)
|
||||
return { root, ctx, storage }
|
||||
}
|
||||
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('selected'), createdAt: 0, isSeeded: false }
|
||||
@@ -94,14 +93,14 @@ it('uses the resolved defaults for SQLite creation', async () => {
|
||||
})
|
||||
|
||||
it('validates routing read failures rather than treating them as absence', async () => {
|
||||
const { storage } = await fixture({ })
|
||||
const { storage } = await fixture()
|
||||
faults.op = 'readFile'; faults.error = Object.assign(new Error('routing denied'), { code: 'EACCES' })
|
||||
await expect(storage.stat(header.id)).rejects.toThrow('routing denied')
|
||||
faults.op = ''
|
||||
})
|
||||
|
||||
it('rejects an unreadable routing directory and preserves explicit absence', async () => {
|
||||
const { storage } = await fixture({ })
|
||||
const { storage } = await fixture()
|
||||
faults.op = 'readdir'; faults.error = Object.assign(new Error('directory denied'), { code: 'EACCES' })
|
||||
await expect(storage.list()).rejects.toThrow('directory denied')
|
||||
faults.op = ''
|
||||
@@ -110,7 +109,7 @@ it('rejects an unreadable routing directory and preserves explicit absence', asy
|
||||
})
|
||||
|
||||
it('propagates routing directory read failures during create', async () => {
|
||||
const { storage } = await fixture({ })
|
||||
const { storage } = await fixture()
|
||||
faults.op = 'readdir'
|
||||
faults.error = Object.assign(new Error('routing directory denied'), { code: 'EACCES' })
|
||||
await expect(storage.create(header)).rejects.toThrow('routing directory denied')
|
||||
@@ -131,7 +130,7 @@ it.each(['linux', 'win32'])('publishes routing using the %s durable namespace',
|
||||
})
|
||||
|
||||
it.each(['identity', 'parse', 'race', 'link-failure'] as const)('retains routing publication failure for %s', async (fault) => {
|
||||
const { root, storage } = await fixture({ })
|
||||
const { root, storage } = await fixture()
|
||||
const writer = await storage.create(header); await writer.flush(); await writer.close()
|
||||
const { readdir, readFile } = await import('node:fs/promises')
|
||||
const directory = join(root, '.segments')
|
||||
|
||||
@@ -93,7 +93,7 @@ it('retains the published settlement event under an immediate-close interleaving
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(persistence, { root, compression: 'none', segmentStorage: { maxBufferedEvents: 1 } })
|
||||
await ctx.plugin(persistence, { root, compression: 'none' })
|
||||
const session = ctx.sessions.create(SessionId('settlement-parity'))
|
||||
const writer = await ctx.sessionPersistence.create(session.header)
|
||||
if (!(writer instanceof SqliteTrace)) throw new Error('Missing provider handle')
|
||||
|
||||
@@ -17,7 +17,7 @@ async function fixture(_sqlite: boolean) {
|
||||
finally { await rm(root, { recursive: true, force: true }) }
|
||||
})
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(plugin, { root, compression: 'none', segmentStorage: { maxBufferedEvents: 1 } })
|
||||
await ctx.plugin(plugin, { root, compression: 'none' })
|
||||
return { ctx, root }
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as persistence from '../src/index.ts'
|
||||
import { generationLogPath } from '../src/format.ts'
|
||||
import { SEGMENT_STORAGE_DEFAULTS } from '../src/trace/index.ts'
|
||||
import { SCHEMA_VERSION, SqliteLogs } from '@deepseek-ai/dsh-session-persistence-sqlite/src/sqlite.ts'
|
||||
import { runPersistenceContract } from '../../session-persistence/tests/contract.ts'
|
||||
import { runLiveWritePathContract } from '../../session-persistence/tests/live-write-contract.ts'
|
||||
@@ -26,7 +25,7 @@ runPersistenceContract('segments', async () => {
|
||||
dispose: async () => { try { await primary.dispose() } finally { await rm(root, { recursive: true, force: true }) } } }
|
||||
})
|
||||
|
||||
runLiveWritePathContract('segments', SEGMENT_STORAGE_DEFAULTS.flushDelayMs, {
|
||||
runLiveWritePathContract('segments', 200, {
|
||||
failWrites: (_ctx, failure, sessionId) => {
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted store as receiver below.
|
||||
const original = SqliteLogs.prototype.append
|
||||
@@ -65,7 +64,7 @@ it('creates the SQLite schema when the provider mounts with new Sessions enabled
|
||||
} finally { db.close() }
|
||||
})
|
||||
|
||||
it('creates SQLite events when segmentStorage is omitted', async () => {
|
||||
it('creates SQLite events with the original plugin configuration', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-segment-lazy-jsonl-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const ctx = new Context()
|
||||
|
||||
@@ -1,13 +1,143 @@
|
||||
/** Released JSONL Zstandard framing and decoder interoperability. @module */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { appendFile, mkdir, mkdtemp, open, readFile, readdir, rm, stat, utimes, writeFile } from 'node:fs/promises'
|
||||
import type { FileHandle } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { SessionSeq, type SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
|
||||
import * as JsonlSessionPersistence from './fixtures/legacy-persistence.ts'
|
||||
import {
|
||||
compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, scanZstdFrames,
|
||||
generationLogPath, logPath, scanLog, sessionDir, toHeaderLine, type JsonlCompression,
|
||||
} from '../src/format.ts'
|
||||
import {
|
||||
compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, decompressZstdPrefix, scanZstdFrames,
|
||||
type ZstdFrameDecoder,
|
||||
} from '../src/zstd.ts'
|
||||
import { NodePrivateZstdFrameDecoder } from '../src/zstd-private-decoder.ts'
|
||||
import { PublicZstdFrameDecoder } from '../src/zstd-public-decoder.ts'
|
||||
import {
|
||||
runPersistenceContract, meta, oneTurnLog, releasedV1OneTurnLog,
|
||||
} from '../../session-persistence/tests/contract.ts'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
const MAGIC = Buffer.from([0x28, 0xB5, 0x2F, 0xFD])
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
const roots: string[] = []
|
||||
const contexts: Context[] = []
|
||||
|
||||
interface ZstdReaderInternals {
|
||||
readZstdPrefix(buffer: Buffer, signal?: AbortSignal): Promise<{ events: SessionEvent[] }>
|
||||
}
|
||||
|
||||
type HeaderRead = (
|
||||
this: FileHandle,
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
position: number | null,
|
||||
) => Promise<{ bytesRead: number; buffer: Buffer }>
|
||||
|
||||
async function freshRoot(prefix = 'dsh-jsonl-zstd-'): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), prefix))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
async function mount(root: string, compression?: JsonlCompression): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
contexts.push(ctx)
|
||||
await ctx.plugin(JsonlSessionPersistence, {
|
||||
root,
|
||||
...(compression === undefined ? {} : { compression }),
|
||||
})
|
||||
return ctx
|
||||
}
|
||||
|
||||
/** Create + append + close: persist one whole log through the write handle. */
|
||||
async function writeLog(persistence: SessionPersistence, m: SessionHeader, events: readonly SessionEvent[]): Promise<void> {
|
||||
const handle = await persistence.create(m)
|
||||
try {
|
||||
await handle.append(events)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** Open a read handle, read the whole log, and close. */
|
||||
async function readAll(persistence: SessionPersistence, id: SessionId): Promise<{ meta: SessionHeader; events: readonly SessionEvent[] }> {
|
||||
const handle = await persistence.open(id, 'read')
|
||||
try {
|
||||
return { meta: handle.header, events: (await handle.read()).events }
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** Append one contiguous batch through a temporary write handle. */
|
||||
async function appendBatch(persistence: SessionPersistence, id: SessionId, events: readonly SessionEvent[]): Promise<void> {
|
||||
const handle = await persistence.open(id, 'write')
|
||||
try {
|
||||
await handle.append(events)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function decodeCompleteFrames(buffer: Buffer): Promise<Buffer> {
|
||||
const { frames, tornStart } = scanZstdFrames(buffer)
|
||||
expect(tornStart).toBeUndefined()
|
||||
const plaintext: Buffer[] = []
|
||||
for (const frame of frames) {
|
||||
plaintext.push(await decompressZstdFrame(buffer.subarray(frame.start, frame.end)))
|
||||
}
|
||||
return Buffer.concat(plaintext)
|
||||
}
|
||||
|
||||
function releasedV0Header(header: SessionHeader): Record<string, unknown> {
|
||||
return {
|
||||
type: 'session',
|
||||
version: 0,
|
||||
id: header.id,
|
||||
createdAt: header.createdAt,
|
||||
...(header.cwd === undefined ? {} : { cwd: header.cwd }),
|
||||
delegationDepth: header.delegationDepth ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** Truncate one compressed frame so a scan reports it torn and the recovered plaintext satisfies `accepts`. */
|
||||
async function tornFrame(plaintext: string, accepts: (decoded: string) => boolean = () => true): Promise<Buffer> {
|
||||
const frame = await compressZstdFrame(plaintext)
|
||||
const candidateEnds = [
|
||||
frame.length - 1,
|
||||
frame.length - 4,
|
||||
...[0.9, 0.75, 0.6, 0.5, 0.4, 0.25].map(ratio => Math.floor(frame.length * ratio)),
|
||||
]
|
||||
for (const end of candidateEnds) {
|
||||
const candidate = frame.subarray(0, end)
|
||||
if (scanZstdFrames(candidate).tornStart !== 0) continue
|
||||
try {
|
||||
const decoded = (await decompressZstdPrefix(candidate)).toString('utf8')
|
||||
if (accepts(decoded)) return candidate
|
||||
} catch {
|
||||
// Some early cuts precede the first decodable block; keep searching for
|
||||
// a cut that exercises partial-plaintext recovery.
|
||||
}
|
||||
}
|
||||
throw new Error('test fixture could not produce the requested torn Zstandard frame')
|
||||
}
|
||||
|
||||
function deterministicNoise(length: number): string {
|
||||
let state = 0x12345678
|
||||
let output = ''
|
||||
for (let index = 0; index < length; index++) {
|
||||
state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0
|
||||
output += String.fromCharCode(33 + (state % 90))
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
function emptyStructuralFrame(descriptor: number): Buffer {
|
||||
const contentSizeFlag = descriptor >>> 6
|
||||
const singleSegment = (descriptor & 0x20) !== 0
|
||||
@@ -19,6 +149,45 @@ function emptyStructuralFrame(descriptor: number): Buffer {
|
||||
return Buffer.concat([MAGIC, Buffer.from([descriptor]), variableHeader, lastEmptyRawBlock, checksum])
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks()
|
||||
for (const ctx of contexts.splice(0).reverse()) await ctx.fiber.dispose()
|
||||
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
runPersistenceContract('jsonl-zstd', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-zstd-contract-'))
|
||||
const instance = async (): Promise<{ persistence: SessionPersistence; dispose: () => Promise<void> }> => {
|
||||
const ctx = new Context()
|
||||
const fiber = await ctx.plugin(JsonlSessionPersistence, { root })
|
||||
return {
|
||||
persistence: ctx.sessionPersistence,
|
||||
dispose: async () => { await fiber.dispose() },
|
||||
}
|
||||
}
|
||||
const primary = await instance()
|
||||
return {
|
||||
persistence: primary.persistence,
|
||||
dispose: async () => {
|
||||
await primary.dispose()
|
||||
await rm(root, { recursive: true, force: true })
|
||||
},
|
||||
reopen: instance,
|
||||
// A torn final frame: the batch's append never resolved, so the whole
|
||||
// frame is an uncommitted crash fragment for the write path to truncate.
|
||||
corruptTail: async (id, cwd) => {
|
||||
const line = JSON.stringify({
|
||||
type: 'assistant/chunk',
|
||||
seq: SessionSeq(8),
|
||||
time: 9,
|
||||
data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: deterministicNoise(300_000) } },
|
||||
}) + '\n'
|
||||
const partial = await tornFrame(line, decoded => !decoded.includes('\n'))
|
||||
await appendFile(logPath(root, cwd, id, 'zstd'), partial)
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('Zstandard frame structure', () => {
|
||||
it('scans concatenated checksummed frames and honors a frame limit', async () => {
|
||||
const first = await compressZstdFrame('header\n')
|
||||
@@ -205,3 +374,514 @@ describe('Zstandard frame structure', () => {
|
||||
expect(scanZstdFrames(checksummed)).toEqual({ frames: [{ start: 0, end: checksummed.length }] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('JsonlSessionPersistence: default Zstandard encoding', () => {
|
||||
it('materializes an explicitly durable empty session as one header frame', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const m = meta('empty-zstd', '/work')
|
||||
const handle = await ctx.sessionPersistence.create(m)
|
||||
await handle.flush()
|
||||
await handle.close()
|
||||
|
||||
const buffer = await readFile(logPath(root, '/work', m.id, 'zstd'))
|
||||
expect(scanZstdFrames(buffer).frames).toHaveLength(1)
|
||||
expect((await decodeCompleteFrames(buffer)).toString()).toBe(`${JSON.stringify(toHeaderLine(m))}\n`)
|
||||
await expect(readAll(ctx.sessionPersistence, m.id)).resolves.toMatchObject({ events: [] })
|
||||
})
|
||||
|
||||
it('writes .jsonl.zstd by default with one header frame and one first-batch frame', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('default-zstd', '/work')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const buffer = await readFile(path)
|
||||
expect(buffer.subarray(0, 4)).toEqual(MAGIC)
|
||||
await expect(stat(logPath(root, header.cwd, header.id, 'none'))).rejects.toThrow()
|
||||
|
||||
const scan = scanZstdFrames(buffer)
|
||||
expect(scan.frames).toHaveLength(2)
|
||||
const plaintext = await decodeCompleteFrames(buffer)
|
||||
expect(plaintext.toString()).toBe([
|
||||
JSON.stringify(toHeaderLine(header)),
|
||||
...oneTurnLog().map(e => JSON.stringify(e)),
|
||||
'',
|
||||
].join('\n'))
|
||||
expect((await readAll(ctx.sessionPersistence, header.id)).events).toEqual(oneTurnLog())
|
||||
})
|
||||
|
||||
it('serves a migrated compressed v0 read without publishing a successor', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('zstd-v0-read', '/work')
|
||||
const sourcePath = generationLogPath(root, header.cwd, header.id, 0, 'zstd')
|
||||
const currentPath = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const [turn, user, step, ...tail] = releasedV1OneTurnLog()
|
||||
// Synthetic historical input opens its step before any surface so V3 can reserve the system head.
|
||||
const historical = [turn!, step!, user!, ...tail].map((event, seq) => ({
|
||||
...event, seq: SessionSeq(seq), time: seq < 3 ? seq + 1 : event.time,
|
||||
}))
|
||||
const source = Buffer.concat([
|
||||
await compressZstdFrame(`${JSON.stringify(releasedV0Header(header))}\n`),
|
||||
await compressZstdFrame(`${historical.map(event => JSON.stringify(event)).join('\n')}\n`),
|
||||
])
|
||||
await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true })
|
||||
await writeFile(sourcePath, source)
|
||||
|
||||
await expect(readAll(ctx.sessionPersistence, header.id)).resolves.toEqual({
|
||||
meta: { ...header, delegationDepth: 0 },
|
||||
events: [
|
||||
historical[0],
|
||||
historical[1],
|
||||
{
|
||||
type: 'system/message', seq: 2, time: 2, surfaceOp: 'append',
|
||||
data: {
|
||||
turn: 1, step: 1,
|
||||
message: {
|
||||
id: 'v2-to-v3-system-fc06c3f7720f3bc94ea7a2b7fadde6a5b100c6ab6ca342d2222bd017184a0b67',
|
||||
role: 'system', source: { kind: 'system-prompt' }, content: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ ...historical[2], seq: 3 },
|
||||
...oneTurnLog().slice(3).map(event => ({ ...event, seq: event.seq + 1 })),
|
||||
],
|
||||
})
|
||||
expect(await readFile(sourcePath)).toEqual(source)
|
||||
await expect(readFile(currentPath)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
})
|
||||
|
||||
|
||||
it('a read rejects a present zstd artifact that carries no frame', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('raw-zero-frame', '/work')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
// The path still exists, so zero frames is corruption rather than absence.
|
||||
await writeFile(logPath(root, '/work', header.id, 'zstd'), Buffer.alloc(0))
|
||||
await expect(readAll(ctx.sessionPersistence, header.id)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('resolves the default when a programmatic wrapper bypasses Loader schema normalization', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = new Context()
|
||||
contexts.push(ctx)
|
||||
await ctx.plugin((inner: Context) => JsonlSessionPersistence.apply(inner, { root }))
|
||||
const backend = ctx.sessionPersistence
|
||||
const header = meta('direct-default')
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
|
||||
const events = oneTurnLog()
|
||||
await writeLog(backend, header, events)
|
||||
|
||||
const plaintext = (await decodeCompleteFrames(await readFile(path))).toString()
|
||||
const recordTypes = plaintext.trimEnd().split('\n')
|
||||
.map(line => (JSON.parse(line) as { type: string }).type)
|
||||
expect(recordTypes).not.toContain('text-chunks')
|
||||
const assistant = plaintext.trimEnd().split('\n')
|
||||
.map(line => JSON.parse(line) as { type: string; data?: { stream?: Array<{ type: string }> } })
|
||||
.find(record => record.type === 'assistant/message')
|
||||
expect(assistant?.data?.stream?.some(record => record.type === 'text-chunks')).toBe(true)
|
||||
expect((await readAll(backend, header.id)).events).toEqual(events)
|
||||
})
|
||||
|
||||
it('appends one frame per durable batch without rewriting prior bytes', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('append-frame')
|
||||
const handle = await ctx.sessionPersistence.create(header)
|
||||
await handle.append(oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const before = await readFile(path)
|
||||
const secondTurn: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 7, data: { turn: 2 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(7), time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
]
|
||||
await handle.append(secondTurn)
|
||||
await handle.close()
|
||||
|
||||
const after = await readFile(path)
|
||||
expect(after.subarray(0, before.length)).toEqual(before)
|
||||
expect(scanZstdFrames(after).frames).toHaveLength(3)
|
||||
expect((await readAll(ctx.sessionPersistence, header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
|
||||
})
|
||||
|
||||
it('lists from a multi-chunk header frame without decoding a corrupt event frame', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('large-header', `/work/${'x'.repeat(24_000)}`)
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const buffer = Buffer.from(await readFile(path))
|
||||
const eventFrame = scanZstdFrames(buffer).frames[1]!
|
||||
buffer[eventFrame.end - 1] = buffer[eventFrame.end - 1]! ^ 0xFF
|
||||
await writeFile(path, buffer)
|
||||
|
||||
const listed = await ctx.sessionPersistence.list()
|
||||
expect(listed.map(item => item.header.id)).toEqual([header.id])
|
||||
expect(listed[0]?.formatStatus).toBe('current')
|
||||
expect((await ctx.sessionPersistence.stat(header.id))?.formatStatus).toBe('current')
|
||||
await expect(readAll(ctx.sessionPersistence, header.id)).rejects.toThrow(/frame at byte .* failed validation/)
|
||||
})
|
||||
|
||||
it('stops multi-frame inspection when cancellation arrives at a slice deadline', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('cancel-zstd-frames')
|
||||
const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
|
||||
const eventFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[0])}\n`)
|
||||
const laterFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[1])}\n`)
|
||||
const stream = Buffer.concat([headerFrame, eventFrame, laterFrame])
|
||||
const controller = new AbortController()
|
||||
const reason = new Error('cancel after Zstandard decode starts')
|
||||
const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
|
||||
vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValue(501)
|
||||
const pending = reader.readZstdPrefix(stream, controller.signal)
|
||||
queueMicrotask(() => { controller.abort(reason) })
|
||||
|
||||
await expect(pending).rejects.toBe(reason)
|
||||
})
|
||||
|
||||
it('continues decoding every frame after a slice deadline yields', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('yield-zstd-frames')
|
||||
const events = oneTurnLog().slice(0, 2)
|
||||
const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`)
|
||||
const eventFrames = await Promise.all(events.map(async event => (
|
||||
compressZstdFrame(`${JSON.stringify(event)}\n`)
|
||||
)))
|
||||
const stream = Buffer.concat([headerFrame, ...eventFrames])
|
||||
const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals
|
||||
vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValue(501)
|
||||
|
||||
const prefix = await reader.readZstdPrefix(stream)
|
||||
|
||||
expect(prefix.events).toEqual(events)
|
||||
})
|
||||
|
||||
it.each(['none', 'zstd'] as const)(
|
||||
'observes cancellation after each async %s header read during listing',
|
||||
async (compression) => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root, compression)
|
||||
const header = meta(`cancel-${compression}-header-read`, '/work')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
await ctx.sessionPersistence.list()
|
||||
const path = logPath(root, header.cwd, header.id, compression)
|
||||
// A changed revision makes the next listing read the header again.
|
||||
await utimes(path, new Date(), new Date(Date.now() + 60_000))
|
||||
const probe = await open(path, 'r')
|
||||
const prototype = Object.getPrototypeOf(probe) as { read: HeaderRead }
|
||||
const originalRead = prototype.read
|
||||
await probe.close()
|
||||
const controller = new AbortController()
|
||||
const reason = new Error(`cancel ${compression} header read`)
|
||||
const read = vi.spyOn(prototype, 'read').mockImplementation(async function (
|
||||
this: FileHandle,
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
position: number | null,
|
||||
) {
|
||||
const result = await originalRead.call(this, buffer, offset, length, position)
|
||||
controller.abort(reason)
|
||||
return result
|
||||
})
|
||||
|
||||
await expect(ctx.sessionPersistence.list({ signal: controller.signal })).rejects.toBe(reason)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
},
|
||||
)
|
||||
|
||||
it('recovers complete records from a torn final frame and rewrites them on the next append', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('recover-torn', '/proj')
|
||||
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const committed = await readFile(path)
|
||||
const openTurn: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 7, data: { turn: 2 } },
|
||||
{ type: 'step/start', seq: SessionSeq(7), time: 8, data: { turn: 2, step: 1 } },
|
||||
{
|
||||
type: 'assistant/attempt',
|
||||
seq: SessionSeq(8),
|
||||
time: 9,
|
||||
data: {
|
||||
turn: 2,
|
||||
step: 1,
|
||||
stream: [{ type: 'text-chunks', time0: 9, index: 0, dt: [], texts: [deterministicNoise(300_000)] }],
|
||||
},
|
||||
},
|
||||
]
|
||||
const plaintext = openTurn.map(e => JSON.stringify(e)).join('\n') + '\n'
|
||||
await appendFile(path, await tornFrame(plaintext, (decoded) => {
|
||||
const newlines = decoded.match(/\n/g)?.length ?? 0
|
||||
return newlines >= 2 && !decoded.endsWith('\n')
|
||||
}))
|
||||
|
||||
// Complete JSONL records already flushed into the torn frame are real
|
||||
// emitted events: reads recover them, while the half-written chunk stays
|
||||
// invisible and the file keeps its bytes until the write path repairs it.
|
||||
const loaded = await readAll(ctx.sessionPersistence, header.id)
|
||||
expect(loaded.events.map(event => event.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
|
||||
expect(loaded.events[6]).toEqual(openTurn[0])
|
||||
expect(loaded.events[7]).toEqual(openTurn[1])
|
||||
|
||||
// The first append truncates the torn bytes and rewrites the recovered
|
||||
// records durably before the new batch, continuing at their next-seq.
|
||||
const closers: SessionEvent[] = [
|
||||
{ type: 'step/end', seq: SessionSeq(8), time: 10, data: { turn: 2, step: 1 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(9), time: 11, data: { turn: 2, reason: { kind: 'interrupted' } } },
|
||||
]
|
||||
await appendBatch(ctx.sessionPersistence, header.id, closers)
|
||||
expect(warn).toHaveBeenCalledWith('session-persistence-jsonl: session "recover-torn" recovered from a torn tail; incomplete tail bytes were discarded')
|
||||
|
||||
const repaired = await readFile(path)
|
||||
expect(repaired.subarray(0, committed.length)).toEqual(committed)
|
||||
expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
|
||||
expect(scanLog(await decodeCompleteFrames(repaired)).events)
|
||||
.toEqual([...oneTurnLog(), openTurn[0]!, openTurn[1]!, ...closers])
|
||||
})
|
||||
|
||||
it('retries the torn-tail rewrite when its first durable write fails', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('retry-torn-rewrite', '/proj')
|
||||
vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const recovered: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 7, data: { turn: 2 } },
|
||||
{ type: 'step/start', seq: SessionSeq(7), time: 8, data: { turn: 2, step: 1 } },
|
||||
{
|
||||
type: 'assistant/attempt',
|
||||
seq: SessionSeq(8),
|
||||
time: 9,
|
||||
data: {
|
||||
turn: 2,
|
||||
step: 1,
|
||||
stream: [{ type: 'text-chunks', time0: 9, index: 0, dt: [], texts: [deterministicNoise(300_000)] }],
|
||||
},
|
||||
},
|
||||
]
|
||||
await appendFile(path, await tornFrame(recovered.map(e => JSON.stringify(e)).join('\n') + '\n', (decoded) => {
|
||||
const newlines = decoded.match(/\n/g)?.length ?? 0
|
||||
return newlines >= 2 && !decoded.endsWith('\n')
|
||||
}))
|
||||
|
||||
const handle = await ctx.sessionPersistence.open(header.id, 'write')
|
||||
try {
|
||||
const failure = new Error('rewrite refused')
|
||||
const service = ctx.sessionPersistence as unknown as { persistBatch: () => Promise<void> }
|
||||
vi.spyOn(service, 'persistBatch').mockRejectedValueOnce(failure)
|
||||
const closers: SessionEvent[] = [
|
||||
{ type: 'step/end', seq: SessionSeq(8), time: 10, data: { turn: 2, step: 1 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(9), time: 11, data: { turn: 2, reason: { kind: 'interrupted' } } },
|
||||
]
|
||||
// The rewrite of the recovered records fails first; the retained repair
|
||||
// state makes the retried append rewrite them exactly once.
|
||||
await expect(handle.append(closers)).rejects.toBe(failure)
|
||||
await handle.append(closers)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
const repaired = await readFile(path)
|
||||
expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
|
||||
expect(scanLog(await decodeCompleteFrames(repaired)).events.map(e => e.seq))
|
||||
.toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
})
|
||||
|
||||
it('drops a frame torn in its header before it has produced plaintext', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('partial-magic')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const committed = await readFile(path)
|
||||
await appendFile(path, MAGIC.subarray(0, 2))
|
||||
|
||||
expect((await readAll(ctx.sessionPersistence, header.id)).events).toEqual(oneTurnLog())
|
||||
// Reads never repair: the torn bytes stay until a write-path append.
|
||||
expect(await readFile(path)).toEqual(Buffer.concat([committed, MAGIC.subarray(0, 2)]))
|
||||
})
|
||||
|
||||
it('recovers a final frame torn at its checksum byte in full', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('partial-checksum')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const committed = await readFile(path)
|
||||
const secondTurn: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 7, data: { turn: 2 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(7), time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
]
|
||||
const frame = await compressZstdFrame(secondTurn.map(e => JSON.stringify(e)).join('\n') + '\n')
|
||||
await appendFile(path, frame.subarray(0, -1))
|
||||
|
||||
// One missing checksum byte leaves the frame structurally torn, but its
|
||||
// complete records decode in full: reads recover them, and the next
|
||||
// append rewrites them as a complete checksummed frame.
|
||||
const loaded = await readAll(ctx.sessionPersistence, header.id)
|
||||
expect(loaded.events).toEqual([...oneTurnLog(), ...secondTurn])
|
||||
const thirdTurn: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(8), time: 9, data: { turn: 3 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(9), time: 10, data: { turn: 3, reason: { kind: 'completed' } } },
|
||||
]
|
||||
await appendBatch(ctx.sessionPersistence, header.id, thirdTurn)
|
||||
const repaired = await readFile(path)
|
||||
expect(repaired.subarray(0, committed.length)).toEqual(committed)
|
||||
expect(scanZstdFrames(repaired).tornStart).toBeUndefined()
|
||||
expect(scanLog(await decodeCompleteFrames(repaired)).events).toEqual([...oneTurnLog(), ...secondTurn, ...thirdTurn])
|
||||
})
|
||||
|
||||
it('rejects a complete frame containing a torn JSONL record', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('complete-bad-jsonl')
|
||||
await writeLog(ctx.sessionPersistence, header, oneTurnLog())
|
||||
await appendFile(
|
||||
logPath(root, header.cwd, header.id, 'zstd'),
|
||||
await compressZstdFrame('{"type":"turn/start"'),
|
||||
)
|
||||
await expect(readAll(ctx.sessionPersistence, header.id)).rejects.toThrow(/complete frame contains a torn JSONL record/)
|
||||
})
|
||||
|
||||
it('rolls back a checksummed append frame when fsync fails', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
const header = meta('zstd-fsync-rollback')
|
||||
const handle = await ctx.sessionPersistence.create(header)
|
||||
await handle.append(oneTurnLog())
|
||||
const path = logPath(root, header.cwd, header.id, 'zstd')
|
||||
const before = await readFile(path)
|
||||
|
||||
const probe = await open(path, 'r')
|
||||
const prototype = Object.getPrototypeOf(probe) as { sync: () => Promise<void> }
|
||||
await probe.close()
|
||||
const realSync = prototype.sync
|
||||
let failed = false
|
||||
const spy = vi.spyOn(prototype, 'sync').mockImplementation(async function (this: FileHandle) {
|
||||
if (!failed) {
|
||||
failed = true
|
||||
throw new Error('simulated Zstandard fsync failure')
|
||||
}
|
||||
return realSync.call(this)
|
||||
})
|
||||
const secondTurn: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 7, data: { turn: 2 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(7), time: 8, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
]
|
||||
await expect(handle.append(secondTurn)).rejects.toThrow(/simulated Zstandard fsync failure/)
|
||||
expect(await readFile(path)).toEqual(before)
|
||||
spy.mockRestore()
|
||||
await handle.append(secondTurn)
|
||||
await handle.close()
|
||||
expect((await readAll(ctx.sessionPersistence, header.id)).events).toEqual([...oneTurnLog(), ...secondTurn])
|
||||
})
|
||||
|
||||
it('skips unreadable compressed headers during discovery while rejecting targeted reads', async () => {
|
||||
const root = await freshRoot()
|
||||
for (const [id, content] of [
|
||||
['empty', Buffer.alloc(0)],
|
||||
['partial', MAGIC],
|
||||
['not-header', await compressZstdFrame('{"type":"turn/start"}\n')],
|
||||
] as const) {
|
||||
const sessionId = brandString<SessionId>(id)
|
||||
await mkdir(sessionDir(root, undefined, sessionId), { recursive: true })
|
||||
await writeFile(logPath(root, undefined, sessionId, 'zstd'), content)
|
||||
}
|
||||
const ctx = await mount(root)
|
||||
expect(await ctx.sessionPersistence.list()).toEqual([])
|
||||
|
||||
const twoLinesId = brandString<SessionId>('two-lines')
|
||||
await mkdir(sessionDir(root, undefined, twoLinesId), { recursive: true })
|
||||
await writeFile(logPath(root, undefined, twoLinesId, 'zstd'), await compressZstdFrame([
|
||||
JSON.stringify(toHeaderLine(meta('two-lines'))),
|
||||
JSON.stringify({ type: 'turn/start' }),
|
||||
'',
|
||||
].join('\n')))
|
||||
expect(await ctx.sessionPersistence.list()).toEqual([])
|
||||
await expect(ctx.sessionPersistence.open(twoLinesId, 'read'))
|
||||
.rejects.toThrow(/first frame is not exactly one header line/)
|
||||
})
|
||||
|
||||
it('rejects missing, empty, and checksum-corrupt header frames on targeted reads', async () => {
|
||||
const root = await freshRoot()
|
||||
for (const id of ['partial-only', 'empty-header', 'bad-checksum']) {
|
||||
await mkdir(sessionDir(root, undefined, brandString<SessionId>(id)), { recursive: true })
|
||||
}
|
||||
await writeFile(logPath(root, undefined, brandString<SessionId>('partial-only'), 'zstd'), MAGIC)
|
||||
await writeFile(logPath(root, undefined, brandString<SessionId>('empty-header'), 'zstd'), await compressZstdFrame(''))
|
||||
const corruptHeader = Buffer.from(await compressZstdFrame(`${JSON.stringify(toHeaderLine(meta('bad-checksum')))}\n`))
|
||||
corruptHeader[corruptHeader.length - 1] = corruptHeader[corruptHeader.length - 1]! ^ 0xFF
|
||||
await writeFile(logPath(root, undefined, brandString<SessionId>('bad-checksum'), 'zstd'), corruptHeader)
|
||||
const ctx = await mount(root)
|
||||
|
||||
await expect(ctx.sessionPersistence.open(brandString<SessionId>('partial-only'), 'read'))
|
||||
.rejects.toThrow(/empty or header-less Zstandard session log/)
|
||||
await expect(ctx.sessionPersistence.open(brandString<SessionId>('empty-header'), 'read'))
|
||||
.rejects.toThrow(/first frame is not exactly one header line/)
|
||||
expect(await ctx.sessionPersistence.list()).toEqual([])
|
||||
await expect(ctx.sessionPersistence.stat(brandString<SessionId>('bad-checksum')))
|
||||
.rejects.toThrow(/header frame failed validation/)
|
||||
await expect(ctx.sessionPersistence.open(brandString<SessionId>('bad-checksum'), 'read'))
|
||||
.rejects.toThrow(/frame at byte 0 failed validation/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('JsonlSessionPersistence: encoding selection', () => {
|
||||
it('rejects roots owned by the opposite encoding in both directions', async () => {
|
||||
const rawRoot = await freshRoot('dsh-jsonl-raw-mismatch-')
|
||||
const raw = await mount(rawRoot, 'none')
|
||||
await writeLog(raw.sessionPersistence, meta('raw-log'), oneTurnLog())
|
||||
const defaultBackend = await mount(rawRoot)
|
||||
await expect(defaultBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "zstd"/)
|
||||
|
||||
const zstdRoot = await freshRoot('dsh-jsonl-zstd-mismatch-')
|
||||
const zstd = await mount(zstdRoot)
|
||||
await writeLog(zstd.sessionPersistence, meta('zstd-log'), oneTurnLog())
|
||||
const rawBackend = await mount(zstdRoot, 'none')
|
||||
await expect(rawBackend.sessionPersistence.list()).rejects.toThrow(/configured for compression "none"/)
|
||||
})
|
||||
|
||||
it('rechecks targeted artifacts and listing after an initially empty root', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
expect(await ctx.sessionPersistence.list()).toEqual([])
|
||||
|
||||
const loadHeader = meta('late-raw-load', '/late')
|
||||
await mkdir(sessionDir(root, loadHeader.cwd, loadHeader.id), { recursive: true })
|
||||
await writeFile(logPath(root, loadHeader.cwd, loadHeader.id, 'none'), [
|
||||
JSON.stringify(toHeaderLine(loadHeader)),
|
||||
...oneTurnLog().map(e => JSON.stringify(e)),
|
||||
'',
|
||||
].join('\n'))
|
||||
await expect(ctx.sessionPersistence.open(loadHeader.id, 'read')).rejects.toThrow(/uses \.jsonl/)
|
||||
await expect(ctx.sessionPersistence.open(loadHeader.id, 'write')).rejects.toThrow(/uses \.jsonl/)
|
||||
await expect(ctx.sessionPersistence.list()).rejects.toThrow(/uses \.jsonl/)
|
||||
})
|
||||
|
||||
it('refuses materialization when an opposite artifact appears after create', async () => {
|
||||
const root = await freshRoot()
|
||||
const ctx = await mount(root)
|
||||
await ctx.sessionPersistence.list()
|
||||
const header = meta('late-raw-materialize', '/late')
|
||||
const handle = await ctx.sessionPersistence.create(header)
|
||||
await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true })
|
||||
await writeFile(logPath(root, header.cwd, header.id, 'none'), [
|
||||
JSON.stringify(toHeaderLine(header)),
|
||||
...oneTurnLog().map(e => JSON.stringify(e)),
|
||||
'',
|
||||
].join('\n'))
|
||||
await expect(handle.append(oneTurnLog())).rejects.toThrow(/uses \.jsonl/)
|
||||
await handle.close()
|
||||
expect((await readdir(sessionDir(root, header.cwd, header.id))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -52,12 +52,11 @@ function isLockContention(error: unknown): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* One artifact write lock and an optional root-wide creation guard.
|
||||
* `release` attempts both locks, preserving independent release failures.
|
||||
* One held write lock. Constructed only by {@link SessionWriteLease.acquire};
|
||||
* `release` closes the descriptor or handle, which is what releases the lock.
|
||||
*/
|
||||
export class SessionWriteLease {
|
||||
private released = false
|
||||
private guard: SessionWriteLease | undefined
|
||||
|
||||
private constructor(private readonly held: HeldLock) {}
|
||||
|
||||
@@ -65,24 +64,10 @@ export class SessionWriteLease {
|
||||
* Acquire the session directory's kernel write lock.
|
||||
* @param dir - the session's artifact directory (created if absent).
|
||||
* @param id - the session the lock guards, for error identities.
|
||||
* @param guardDir - optional root-wide creation lock, acquired before the artifact lock and held until release.
|
||||
* @returns the held lock.
|
||||
* @throws {SessionAlreadyOwnedError} while another holder keeps the lock.
|
||||
*/
|
||||
static async acquire(dir: string, id: SessionId, guardDir?: string): Promise<SessionWriteLease> {
|
||||
const guard = guardDir === undefined ? undefined : await SessionWriteLease.acquireDirectory(guardDir, id)
|
||||
try {
|
||||
const lease = await SessionWriteLease.acquireDirectory(dir, id)
|
||||
lease.guard = guard
|
||||
return lease
|
||||
} catch (error: unknown) {
|
||||
try { await guard?.release() }
|
||||
catch (releaseError: unknown) { throw new AggregateError([error, releaseError], 'Session lock acquisition and rollback failed') }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private static async acquireDirectory(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
||||
static async acquire(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
||||
const path = join(dir, LEASE_FILENAME)
|
||||
// Owner-only like materializePosix's directories: the lock may create the
|
||||
// session directory first, and both creators must agree on the mode.
|
||||
@@ -139,16 +124,12 @@ export class SessionWriteLease {
|
||||
async release(): Promise<void> {
|
||||
if (this.released) return
|
||||
this.released = true
|
||||
const failures: unknown[] = []
|
||||
try {
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (this.held.kind === 'win32') await releaseLockHandleWin32(this.held.handle)
|
||||
else await this.held.handle.close()
|
||||
/* v8 ignore stop */
|
||||
} catch (error: unknown) { failures.push(error) }
|
||||
try { await this.guard?.release() }
|
||||
catch (error: unknown) { failures.push(error) }
|
||||
if (failures.length > 1) throw new AggregateError(failures, 'Session write locks failed to release')
|
||||
if (failures.length === 1) throw failures[0]
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (this.held.kind === 'win32') {
|
||||
await releaseLockHandleWin32(this.held.handle)
|
||||
return
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
await this.held.handle.close()
|
||||
}
|
||||
}
|
||||
@@ -68,11 +68,11 @@ export interface SqliteLogsOptions {
|
||||
/** Resolved JSONL root holding the per-Session write-lock directories and `.segments` routing records. */
|
||||
readonly legacyRoot: string
|
||||
/** SQLite writer wait in milliseconds. */
|
||||
readonly busyTimeoutMs: number
|
||||
readonly busyTimeoutMs?: number
|
||||
/** Maximum intentional live write delay in milliseconds. */
|
||||
readonly flushDelayMs: number
|
||||
readonly flushDelayMs?: number
|
||||
/** Admitted live event count that starts a write before the delay elapses. */
|
||||
readonly maxBufferedEvents: number
|
||||
readonly maxBufferedEvents?: number
|
||||
/** Publish a Session's routing record after its first commit. */
|
||||
readonly publish: (id: SessionId) => Promise<void>
|
||||
/** Claim a new Session across the provider's physical backends. */
|
||||
@@ -111,9 +111,9 @@ export class SqliteLogs {
|
||||
constructor(options: SqliteLogsOptions) {
|
||||
this.path = options.path
|
||||
this.legacyRoot = options.legacyRoot
|
||||
this.busyTimeoutMs = options.busyTimeoutMs
|
||||
this.flushDelayMs = options.flushDelayMs
|
||||
this.maxBufferedEvents = options.maxBufferedEvents
|
||||
this.busyTimeoutMs = options.busyTimeoutMs ?? 5000
|
||||
this.flushDelayMs = options.flushDelayMs ?? 200
|
||||
this.maxBufferedEvents = options.maxBufferedEvents ?? 256
|
||||
this.published = options.publish
|
||||
this.acquireCreationLease = options.acquireCreationLease
|
||||
this.report = options.report
|
||||
|
||||
@@ -188,6 +188,12 @@
|
||||
"packages/session/session-persistence-jsonl/src/generation.ts": {
|
||||
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/src/index.ts": {
|
||||
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/zstd.spec.ts": {
|
||||
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
|
||||
},
|
||||
"packages/shell/bash-local/src/index.ts": {
|
||||
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
|
||||
},
|
||||
|
||||
@@ -1503,12 +1503,28 @@
|
||||
"cdd46c8ceda6d5707bc2abfba329351ba06bcc030b314a3c799d72a4971bd5a4": 2,
|
||||
"f36c9eb275a387531e7c9c193c1fddf984cc8ff8a8fd3a95474630a737b5f728": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/jsonl.spec.ts": {
|
||||
"1058f7a4a2b920b8693144d4c329875739c05b83bcae4d1378427cc1d5f141a0": 1,
|
||||
"2f28d83ee100961d65baf06b0b57ff95b046c36d1e135dab4195ffbd6420a7fd": 1,
|
||||
"a7d8cc8d42e37ad5cc4882241492ac572ed8163c7fb8663180e893c7178e906f": 1,
|
||||
"aca72c9c675ac6aab8379d5d137eac122eb59803238c3e652bbea6e3e26da35b": 1,
|
||||
"b40f3bbda2adba664b54271ea4b552ffb2c78a239d39d8b1e882cca164d21c4f": 12,
|
||||
"b9fc932acb5b23fefbcc63e176999dd795d7cf7323a66a9a4de4c07b20d9c33c": 1,
|
||||
"c5d92cfb860759a6a1fd46a250b0c5be0e9b5779224b72f3dbbe0ace562a9f69": 1,
|
||||
"cc4c2ee361b8bd0a257383b90983432e1f707057eb6d90935bc023483858aa39": 1,
|
||||
"cdd46c8ceda6d5707bc2abfba329351ba06bcc030b314a3c799d72a4971bd5a4": 1,
|
||||
"ef31bd7c393b53eb4da79f4cf8fb5caa4d3628076458dbafd2fdb18ac88df9c9": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/lease.spec.ts": {
|
||||
"94e6c4d15a19729cf60005d29c0985aa4e5bd984b92f40c2b5d8e996bb651997": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/native-source-admission.spec.ts": {
|
||||
"24b3f41708c436a3b161317d9b04439dff484aa8f5a913ed3c68a299f490e3b9": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/zstd.spec.ts": {
|
||||
"71b7a878e6188e21f9e735a03a79e060e88184269c9890e414a4eef5ae58878f": 1,
|
||||
"aa35ddb1a441f4aa934fca868f66fb0899db603c8a222ca86a138e23741c350e": 2
|
||||
"aa35ddb1a441f4aa934fca868f66fb0899db603c8a222ca86a138e23741c350e": 2,
|
||||
"b40f3bbda2adba664b54271ea4b552ffb2c78a239d39d8b1e882cca164d21c4f": 3
|
||||
},
|
||||
"packages/session/session-persistence/tests/contract.ts": {
|
||||
"1a732182a70f9e0e8ea0e11f07e9bc1c8e56b5769056aab5040f3691b21d554c": 1,
|
||||
|
||||
Reference in new issue
Block a user