refactor(session): trim persistence internals
This commit is contained in:
1 parent
69cec93294
commit
4bd6b6882e
7 files changed
+26
-59
No files matched your search
@@ -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<void>): Promise<void>
|
||||
}
|
||||
|
||||
@@ -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<void> | undefined
|
||||
private readonly generationFormat: Omit<JsonlGenerationFormatAdapter, 'createRestore'>
|
||||
/**
|
||||
@@ -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<PreparedLegacySession> {
|
||||
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()
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
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
|
||||
|
||||
@@ -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<void>): Promise<void>
|
||||
}
|
||||
|
||||
/** Historical reads used by the persistence service; no JSONL writes or live handles. */
|
||||
export interface JsonlBackend extends Pick<SessionPersistence, 'stat'> {
|
||||
readonly listLimit: <T>(operation: () => Promise<T>) => Promise<T>
|
||||
/** @param id - Session identity. @returns whether a physical legacy artifact exists. */
|
||||
hasStoredJsonl(id: SessionId): Promise<boolean>
|
||||
/** @param id - Session identity. @param signal - optional cancellation. @returns prepared logical prefix and commit. */
|
||||
prepare(id: SessionId, signal?: AbortSignal): Promise<PreparedLegacySession>
|
||||
/** @param options - optional cancellation. @param excluded - authoritative SQLite identities. @returns legacy metadata. */
|
||||
list(options?: SessionPersistenceListOptions, excluded?: ReadonlySet<SessionId>): Promise<readonly SessionPersistenceSnapshot[]>
|
||||
}
|
||||
export type JsonlBackend = Pick<JsonlSessionPersistence, 'stat' | 'hasStoredJsonl' | 'prepare' | 'list'>
|
||||
|
||||
/** Owns pending legacy opens until import, ownership handoff, and cleanup finish. */
|
||||
export class LegacySessionMigration {
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -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<void>
|
||||
/** 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<void>
|
||||
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) => {
|
||||
|
||||
Generated
+3
@@ -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
|
||||
|
||||
Reference in new issue
Block a user