From 4bd6b6882e5fa384997f3f2d3f66d6bf462f0467 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Sat, 14 Nov 2026 22:45:19 +0800 Subject: [PATCH] refactor(session): trim persistence internals --- .../session-persistence-jsonl/src/index.ts | 11 +++---- .../session-persistence-sqlite/package.json | 1 + .../session-persistence-sqlite/src/index.ts | 4 +-- .../src/migration.ts | 32 +++---------------- .../src/persistence.ts | 14 +++++--- .../session-persistence-sqlite/src/sqlite.ts | 20 ++---------- pnpm-lock.yaml | 3 ++ 7 files changed, 26 insertions(+), 59 deletions(-) diff --git a/packages/session/session-persistence-jsonl/src/index.ts b/packages/session/session-persistence-jsonl/src/index.ts index 8ebf7c2d04..adea1293c6 100644 --- a/packages/session/session-persistence-jsonl/src/index.ts +++ b/packages/session/session-persistence-jsonl/src/index.ts @@ -21,8 +21,7 @@ import { scheduler } from 'node:timers/promises' import { createHash, randomBytes } from 'node:crypto' import pLimit, { type LimitFunction } from 'p-limit' import { - SessionPersistence, - SessionFormatUnsupportedError, + SessionPersistence, SessionFormatUnsupportedError, SessionPersistenceCorruptionError, SessionAlreadyExistsError, SessionPersistenceNotFoundError, assertStoredId, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents, @@ -67,7 +66,7 @@ interface LegacySessionSnapshot { } /** Prepared legacy history whose related sources are checked before destination publication. */ -interface PreparedLegacySession extends LegacySessionSnapshot { +interface PreparedLegacySession { commit(publish: (snapshot: LegacySessionSnapshot) => Promise): Promise } @@ -331,7 +330,7 @@ export class JsonlSessionPersistence extends SessionPersistence { * this backend (`list()`, the root encoding check, historical fingerprints). * Queued tasks of a cancelled listing run and reject at their signal check. */ - readonly listLimit: LimitFunction + private readonly listLimit: LimitFunction private rootEncodingCheck: Promise | undefined private readonly generationFormat: Omit /** @@ -401,14 +400,14 @@ export class JsonlSessionPersistence extends SessionPersistence { * Prepare logical history while the caller retains Session write ownership. * @param id - stored Session identity. * @param signal - optional cancellation for decoding and destination publication. - * @returns history and a commit operation that validates related sources before publication. + * @returns a commit operation that validates related sources before publishing the history. */ async prepare(id: SessionId, signal?: AbortSignal): Promise { await this.ensureRootEncoding() signal?.throwIfAborted() const stored = await this.requireStoredLog(id, signal) const snapshot = { header: stored.meta, inheritedEventCount: stored.inheritedEventCount, events: stored.events } - return { ...snapshot, commit: async (publish) => { + return { commit: async (publish) => { signal?.throwIfAborted() if (stored.status === 'prepared') await stored.validateRelatedSources() signal?.throwIfAborted() diff --git a/packages/session/session-persistence-sqlite/package.json b/packages/session/session-persistence-sqlite/package.json index 764328dd2f..8909c1fd45 100644 --- a/packages/session/session-persistence-sqlite/package.json +++ b/packages/session/session-persistence-sqlite/package.json @@ -47,6 +47,7 @@ "@deepseek-ai/dsh-session-format-v3-to-v4": "workspace:*", "zod": "4.6.6", "@deepseek-ai/node-addon-system": "workspace:~", + "p-limit": "7.3.3", "koffi": "3.1.1" } } diff --git a/packages/session/session-persistence-sqlite/src/index.ts b/packages/session/session-persistence-sqlite/src/index.ts index 036217eeb4..9c0a2e1e09 100644 --- a/packages/session/session-persistence-sqlite/src/index.ts +++ b/packages/session/session-persistence-sqlite/src/index.ts @@ -4,8 +4,6 @@ import { Config as JsonlConfig, JsonlSessionPersistence } from '@deepseek-ai/dsh import type { Config as JsonlConfigOptions } from '@deepseek-ai/dsh-session-persistence-jsonl' import { TracePersistence } from './persistence.ts' -export { TracePersistence } from './persistence.ts' - /** Loader label for the SQLite Session persistence provider. */ export const name = 'session-persistence-sqlite' @@ -30,7 +28,7 @@ export async function apply(ctx: Context, config: Config): Promise { name: 'session-persistence-sqlite-service', apply(serviceCtx: Context) { const legacy = new JsonlSessionPersistence(serviceCtx.isolate('sessionPersistence'), config) - new TracePersistence(serviceCtx, resources.ctx, config.root, legacy) + new TracePersistence(serviceCtx, resources.ctx, config, legacy) }, }) yield service.dispose diff --git a/packages/session/session-persistence-sqlite/src/migration.ts b/packages/session/session-persistence-sqlite/src/migration.ts index ddd1c4f04d..377139ec9a 100644 --- a/packages/session/session-persistence-sqlite/src/migration.ts +++ b/packages/session/session-persistence-sqlite/src/migration.ts @@ -1,38 +1,14 @@ /** Exclusive legacy Session import with same-provider open sequencing. @module */ -import type { SessionEvent, SessionHeader, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl' import { HarnessError } from '@deepseek-ai/dsh-llm' import { setTimeout } from 'node:timers/promises' import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' -import type { SessionAccess, SessionHandle, SessionPersistence, SessionPersistenceListOptions, SessionPersistenceOpenOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import type { SessionAccess, SessionHandle, SessionPersistenceOpenOptions } from '@deepseek-ai/dsh-session-persistence' import type { SqliteLogs } from './sqlite.ts' -/** Current logical history decoded from one immutable legacy artifact. */ -export interface LegacySessionSnapshot { - readonly header: SessionHeader - readonly inheritedEventCount: SessionLogOffset - readonly events: readonly SessionEvent[] -} - -/** Prepared logical history retained under Session ownership until import. */ -export interface PreparedLegacySession extends LegacySessionSnapshot { - /** - * Commit the prepared history while Session ownership remains held. - * @param publish - destination-owned atomic import of the prepared snapshot. - * @returns completed destination commit. - */ - commit(publish: (snapshot: LegacySessionSnapshot) => Promise): Promise -} - /** Historical reads used by the persistence service; no JSONL writes or live handles. */ -export interface JsonlBackend extends Pick { - readonly listLimit: (operation: () => Promise) => Promise - /** @param id - Session identity. @returns whether a physical legacy artifact exists. */ - hasStoredJsonl(id: SessionId): Promise - /** @param id - Session identity. @param signal - optional cancellation. @returns prepared logical prefix and commit. */ - prepare(id: SessionId, signal?: AbortSignal): Promise - /** @param options - optional cancellation. @param excluded - authoritative SQLite identities. @returns legacy metadata. */ - list(options?: SessionPersistenceListOptions, excluded?: ReadonlySet): Promise -} +export type JsonlBackend = Pick /** Owns pending legacy opens until import, ownership handoff, and cleanup finish. */ export class LegacySessionMigration { diff --git a/packages/session/session-persistence-sqlite/src/persistence.ts b/packages/session/session-persistence-sqlite/src/persistence.ts index 22f84f453d..5031ee1435 100644 --- a/packages/session/session-persistence-sqlite/src/persistence.ts +++ b/packages/session/session-persistence-sqlite/src/persistence.ts @@ -3,6 +3,8 @@ import { createHash, randomUUID } from 'node:crypto' 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 type { Config } from '@deepseek-ai/dsh-session-persistence-jsonl' +import pLimit, { type LimitFunction } from 'p-limit' import { z } from 'zod' import { HarnessError } from '@deepseek-ai/dsh-llm' import { SessionPersistence, SessionAlreadyExistsError, SessionPersistenceNotFoundError, materializeCreateHeader } from '@deepseek-ai/dsh-session-persistence' @@ -26,10 +28,12 @@ export class TracePersistence extends SessionPersistence { private readonly migration: LegacySessionMigration private readonly rootPath: string private readonly jsonl: JsonlBackend - constructor(ctx: Context, owner: Context, root: string, + private readonly listLimit: LimitFunction + constructor(ctx: Context, owner: Context, config: Config, jsonl: JsonlBackend) { super(ctx) - this.rootPath = resolve(root) + this.rootPath = resolve(config.root) + this.listLimit = pLimit(config.listConcurrency ?? 3) this.directory = join(this.rootPath, '.segments') this.sqlite = new SqliteLogs({ path: join(this.directory, 'sessions.sqlite'), @@ -176,15 +180,15 @@ export class TracePersistence extends SessionPersistence { await this.assertRoutingDatabase() // Routing records publish after their commit, so reading them first guarantees each one's row is in the later scan. let names: string[] = [] - try { names = await this.jsonl.listLimit(async () => { + try { names = await this.listLimit(async () => { options?.signal?.throwIfAborted() return readdir(this.directory) }) } catch (error: unknown) { if (!isAbsent(error)) throw error } const { entries: segmented, omitted } = await this.sqlite.scan(options?.signal) // 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) - const routes = await Promise.allSettled(names.filter(name => name.endsWith('.json')).map(name => this.jsonl.listLimit(async () => { + const entries = await this.jsonl.list(options) + const routes = await Promise.allSettled(names.filter(name => name.endsWith('.json')).map(name => this.listLimit(async () => { options?.signal?.throwIfAborted() const path = join(this.directory, name) const text = await readFile(path, { encoding: 'utf8', signal: options?.signal }) diff --git a/packages/session/session-persistence-sqlite/src/sqlite.ts b/packages/session/session-persistence-sqlite/src/sqlite.ts index 87b3ad2c2c..c826b57a75 100644 --- a/packages/session/session-persistence-sqlite/src/sqlite.ts +++ b/packages/session/session-persistence-sqlite/src/sqlite.ts @@ -67,12 +67,6 @@ export interface SqliteLogsOptions { readonly path: string /** 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 - /** Maximum intentional live write delay in milliseconds. */ - readonly flushDelayMs?: number - /** Admitted live event count that starts a write before the delay elapses. */ - readonly maxBufferedEvents?: number /** Publish a Session's routing record after its first commit. */ readonly publish: (id: SessionId) => Promise /** Claim a new Session across the provider's physical backends. */ @@ -85,11 +79,6 @@ export interface SqliteLogsOptions { export class SqliteLogs { /** Absolute database path, recorded in routing records. */ readonly path: string - /** Maximum intentional live write delay in milliseconds. */ - readonly flushDelayMs: number - /** Admitted live event count that starts a write before the delay elapses. */ - readonly maxBufferedEvents: number - private readonly busyTimeoutMs: number private readonly legacyRoot: string private readonly published: (id: SessionId) => Promise private readonly acquireCreationLease: SqliteLogsOptions['acquireCreationLease'] @@ -111,9 +100,6 @@ export class SqliteLogs { constructor(options: SqliteLogsOptions) { this.path = options.path this.legacyRoot = options.legacyRoot - 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 @@ -182,7 +168,7 @@ export class SqliteLogs { const { DatabaseSync } = await import('node:sqlite') let db: DatabaseSync | undefined try { - const opened = new DatabaseSync(this.path, { timeout: this.busyTimeoutMs }) + const opened = new DatabaseSync(this.path, { timeout: 5000 }) db = opened // Readers can acquire a snapshot as soon as schema creation commits. opened.exec('PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;') @@ -870,8 +856,8 @@ export class SqliteTrace implements SessionHandle { readonly inheritedEventCount = SessionLogOffset(0), private initialForkCut?: number, private forkWriteFrom?: number) { this.buffer = new LiveWriteBuffer({ - delayMs: this.logs.flushDelayMs, - maxEvents: this.logs.maxBufferedEvents, + delayMs: 200, + maxEvents: 256, enqueue: operation => this.enqueue(operation), persist: batch => this.logs.append(this.header, batch), retry: (error) => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43cffcfd0f..ee65ff3b84 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16125,6 +16125,9 @@ importers: koffi: specifier: 3.1.1 version: 3.1.1 + p-limit: + specifier: 7.3.3 + version: 7.3.3 zod: specifier: 4.6.6 version: 4.6.6