diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml index d8f2314ebd..440d9e0ca4 100644 --- a/packages/session/session-persistence-jsonl/README.i18n.yaml +++ b/packages/session/session-persistence-jsonl/README.i18n.yaml @@ -30,8 +30,8 @@ en: 96498792672f6d50 zh: d767a9c69dced889 /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/reading-the-logs: - en: 4cec8a6c9f6e488b - zh: 4757440a552db5e3 + en: e7e612a45f80e32e + zh: 211b357403747dd2 /deepseek-ai-dsh-session-persistence-jsonl/understand-the-implementation: en: a35407bb25671e7e zh: 6a00f9510c85adcb diff --git a/packages/session/session-persistence-jsonl/README.md b/packages/session/session-persistence-jsonl/README.md index 2de63df367..72023cbeeb 100644 --- a/packages/session/session-persistence-jsonl/README.md +++ b/packages/session/session-persistence-jsonl/README.md @@ -84,7 +84,7 @@ Unloading the backend waits for the consumer unloads it triggers through `sessio Materialized `stat` and `list` snapshots include the format catalog's header classification as `formatStatus`, alongside the translated logical `header`. They also include `location: { kind: 'jsonl', path }` for the selected physical generation. A read-only preparation leaves the selected historical version unchanged; the status becomes `current` after publication of the successor. Unmaterialized pending Sessions omit `formatStatus` and `location`. -`open(id, 'read'|'write')` selects the highest canonical generation. Current input follows the ordinary fast path. For historical input, a read open decodes and migrates the source once, validates the current logical result, and returns it without publishing a successor. A write open reuses that revision-keyed preparation when available, or performs the same preparation, then encodes a same-directory temporary file in bounded chunks, verifies it in a Worker Thread, rechecks the source revision, and publishes the current successor without overwrite before returning. The source remains byte-identical. Source drift after preparation rejects that write open without replacing the logical history already returned to readers; a later write open prepares the new revision. The backend marks decoded event graphs `shared-frozen` when it freezes them before memoization; every nested object and array is frozen, and handle reads and slices preserve that state, including empty slices. Only an unmaterialized pending log reports `detached`. `stat(id)` and `list()` select and translate only the highest generation header without reading event rows or starting migration; snapshots carry the selected file’s `sizeBytes` and a best-effort revision. Current revisions identify that file; historical revisions also fingerprint the selected files across the persistence root, so child changes invalidate cached logical events. Fingerprinting reads filesystem metadata only; unrelated changes conservatively invalidate historical revisions. One `list()` call shares a corpus fingerprint across its historical entries. With `compression: 'none'`, the log is newline-delimited text an external reader can consume directly; the compressed default must be read through the backend. +`open(id, 'read'|'write')` selects the highest canonical generation. Current input follows the ordinary fast path. For historical input, a read open decodes and migrates the source once, validates the current logical result, and returns it without publishing a successor. A write open reuses that revision-keyed preparation when available, or performs the same preparation, then encodes a same-directory temporary file in bounded chunks, verifies it in a Worker Thread, rechecks the source revision, and publishes the current successor without overwrite before returning. The source remains byte-identical. Source drift after preparation rejects that write open without replacing the logical history already returned to readers; a later write open prepares the new revision. The backend marks decoded event graphs `shared-frozen` when it freezes them before memoization; every nested object and array is frozen, and handle reads and slices preserve that state, including empty slices. Only an unmaterialized pending log reports `detached`. `stat(id)` and `list()` select and translate only the highest generation header without reading event rows or starting migration; snapshots carry the selected file’s `sizeBytes` and a best-effort revision. Current revisions identify that file; historical revisions also fingerprint the selected files across the persistence root, so child changes invalidate cached logical events. Fingerprinting reads filesystem metadata only; unrelated changes conservatively invalidate historical revisions. One `list()` call shares a corpus fingerprint across its historical entries and computes it from the same stat results. A later `list()` reuses a header from the previous complete listing while its file revision is unchanged, so it reads only the headers of changed logs. With `compression: 'none'`, the log is newline-delimited text an external reader can consume directly; the compressed default must be read through the backend. Verification accepts a successful Worker response only after the Worker exits naturally with code 0. Its concurrency slot remains held through that exit; cancellation and Worker errors terminate and join the Worker before rejecting. diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md index e5494de7d6..fb2e3072c8 100644 --- a/packages/session/session-persistence-jsonl/README.zh.md +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -84,7 +84,7 @@ kind: "package-reference" 已实体化的 `stat` 与 `list` 快照在转换后的逻辑 `header` 之外,通过 `formatStatus` 保留格式 catalog 的头部分类。它们还包含选中物理 generation 的 `location: { kind: 'jsonl', path }`。只读准备不会改变所选历史版本;发布后继之后,状态才变为 `current`。尚未实体化的待定 Session 省略 `formatStatus` 与 `location`。 -`open(id, 'read'|'write')` 选择最高规范 generation。当前格式输入走普通快速路径。对于历史输入,只读 open 会单遍解码并迁移源、校验当前逻辑结果,然后在不发布后继的情况下返回。写 open 会在可用时复用按 revision 为键的 preparation,否则执行同一套 preparation,再按有界分片编码同目录临时文件、在 Worker Thread 中校验、复查源修订,并在返回前以不覆盖方式发布当前后继。源保持逐字节不变。如果源在 preparation 后发生变化,该次写 open 会失败,已经返回给读方的逻辑历史不会被替换;后续写 open 会针对新的 revision 重新执行 preparation。后端在 memo 化前冻结已解码的 event graph,并在此时将其标记为 `shared-frozen`;每个嵌套对象和数组都会冻结,句柄读取和 slice 即使为空也保留该状态。只有尚未实体化的 pending 空日志报告 `detached`。`stat(id)` 与 `list()` 只选择并转换最高 generation 的 header,不读取事件行,也不启动迁移;快照携带所选文件的 `sizeBytes` 与尽力而为的修订号。当前格式修订号标识该文件;历史格式修订号还包含持久化根目录中所选文件的指纹,因此子日志变化会使缓存的逻辑事件失效。指纹只读取文件系统元数据;无关变化也会保守地使历史修订号失效。一次 `list()` 为其历史条目共用一个全库指纹。选择 `compression: 'none'` 后,日志是外部读取方可直接消费的换行分隔文本;压缩默认值必须经后端读取。 +`open(id, 'read'|'write')` 选择最高规范 generation。当前格式输入走普通快速路径。对于历史输入,只读 open 会单遍解码并迁移源、校验当前逻辑结果,然后在不发布后继的情况下返回。写 open 会在可用时复用按 revision 为键的 preparation,否则执行同一套 preparation,再按有界分片编码同目录临时文件、在 Worker Thread 中校验、复查源修订,并在返回前以不覆盖方式发布当前后继。源保持逐字节不变。如果源在 preparation 后发生变化,该次写 open 会失败,已经返回给读方的逻辑历史不会被替换;后续写 open 会针对新的 revision 重新执行 preparation。后端在 memo 化前冻结已解码的 event graph,并在此时将其标记为 `shared-frozen`;每个嵌套对象和数组都会冻结,句柄读取和 slice 即使为空也保留该状态。只有尚未实体化的 pending 空日志报告 `detached`。`stat(id)` 与 `list()` 只选择并转换最高 generation 的 header,不读取事件行,也不启动迁移;快照携带所选文件的 `sizeBytes` 与尽力而为的修订号。当前格式修订号标识该文件;历史格式修订号还包含持久化根目录中所选文件的指纹,因此子日志变化会使缓存的逻辑事件失效。指纹只读取文件系统元数据;无关变化也会保守地使历史修订号失效。一次 `list()` 为其历史条目共用一个全库指纹,并基于同一批 stat 结果计算该指纹。后续 `list()` 在文件修订号未变时复用上一次完整列举的 header,因此只读取已变化日志的 header。选择 `compression: 'none'` 后,日志是外部读取方可直接消费的换行分隔文本;压缩默认值必须经后端读取。 校验只有在 Worker 自然以退出码 0 结束后,才接受其成功响应。并发配额一直保留到该次退出;取消或 Worker 错误会先终止并等待 Worker 退出,再使校验失败。 diff --git a/packages/session/session-persistence-jsonl/src/index.ts b/packages/session/session-persistence-jsonl/src/index.ts index f8351fa9ee..bf805bce1a 100644 --- a/packages/session/session-persistence-jsonl/src/index.ts +++ b/packages/session/session-persistence-jsonl/src/index.ts @@ -186,6 +186,13 @@ interface ResolvedJsonlGeneration { readonly currentPath: string } +/** One listed generation header and the file revision it was read from. */ +interface ListedHeader { + readonly revision: PersistenceRevision + /** `undefined` when the log is unreadable as a listed Session. */ + readonly metadata: GenerationHeader | undefined +} + /** One backend-owned historical preparation shared by its current callers. */ interface MigrationPreparation { readonly sourcePath: string @@ -207,6 +214,20 @@ function fileRevision(identity: JsonlPhysicalIdentity): PersistenceRevision { ].join(':')) } +/** + * Fingerprint a generation corpus independently of listing order. + * @param revisions - each generation path with its file revision or `missing`. + * @returns the hex digest. + */ +function corpusDigest(revisions: ReadonlyArray): string { + const hash = createHash('sha256') + const byPath = new Map(revisions) + for (const path of [...byPath.keys()].sort()) { + hash.update(JSON.stringify([path, byPath.get(path)])) + } + return hash.digest('hex') +} + /** Whether a filesystem error means absence; every non-ENOENT failure must surface. */ function isENOENT(error: unknown): boolean { return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT' @@ -310,6 +331,13 @@ class JsonlSessionPersistence extends SessionPersistence { * revision guard. */ private readonly coldLogMemo = new Map() + /** + * Generation headers observed by the latest complete listing, keyed by + * source path and guarded by the stat-derived revision, so a listing reads + * only the first frame of logs whose file changed. Each complete listing + * replaces the map, which drops deleted paths. + */ + private listedHeaders = new Map() /** One joinable decode/migration operation per selected historical Session file revision. */ private readonly migrationPreparations = new Map() @@ -527,24 +555,11 @@ class JsonlSessionPersistence extends SessionPersistence { // append lands mid-scan is then still in this snapshot (its artifact may // predate the scan), so create-to-list visibility never has a hole. const pending = [...this.tracker.pendingEntries()] - const artifacts = await this.listArtifacts(signal) + const { artifacts, revisions } = await this.listArtifacts(signal) const corpusRevision = artifacts.some(artifact => artifact.sourceVersion < SESSION_FORMAT_VERSION) - ? await this.historicalCorpusRevision(signal) : undefined - const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => { - signal?.throwIfAborted() - try { - const identity = await stat(artifact.path, { bigint: true }) - signal?.throwIfAborted() - return { artifact, identity } - } catch (error: unknown) { - signal?.throwIfAborted() - if (!isENOENT(error)) throw error - return undefined - } - })) - for (const entry of statted) { - if (entry === undefined) continue - const { artifact, identity } = entry + ? corpusDigest(revisions) : undefined + for (const artifact of artifacts) { + const { identity } = artifact listed.add(artifact.header.id) snapshots.push({ header: artifact.header, @@ -684,7 +699,7 @@ class JsonlSessionPersistence extends SessionPersistence { let prepared: Awaited> let validateRelatedSources: () => Promise try { - const children = async () => (await this.listArtifacts(signal)) + const children = async () => (await this.listArtifacts(signal)).artifacts .filter(source => source.header.origin === 'subagent' && source.header.parentSession === id) const sources = await children() const related = await prepareCatalogFacts(id, sources, this.compression, signal) @@ -1119,54 +1134,87 @@ class JsonlSessionPersistence extends SessionPersistence { /** Historical logical events depend on the corpus, including members with unreadable headers. */ private async historicalCorpusRevision(signal?: AbortSignal): Promise { - const paths = (await this.listGenerations(signal)).map(source => source.sourcePath).sort() + const paths = (await this.listGenerations(signal)).map(source => source.sourcePath) const entries = settledValues(await settleLimited(this.listLimit, paths, async (path) => { signal?.throwIfAborted() try { - return { path, revision: fileRevision(await stat(path, { bigint: true })) } + return [path, fileRevision(await stat(path, { bigint: true }))] as const } catch (error: unknown) { if (!isENOENT(error)) throw error - return { path, revision: 'missing' } + return [path, 'missing'] as const } })) - const hash = createHash('sha256') - for (const { path, revision } of entries) hash.update(JSON.stringify([path, revision])) signal?.throwIfAborted() - return hash.digest('hex') + return corpusDigest(entries) } - private async listArtifacts( - signal?: AbortSignal, - ): Promise> { + /** + * Read every listed Session's generation header with one stat per generation. + * @param signal - optional cancellation. + * @returns the readable artifacts, and the revision of every generation + * (`missing` when it vanished) for {@link corpusDigest}. + */ + private async listArtifacts(signal?: AbortSignal): Promise<{ + artifacts: Array + revisions: Array + }> { signal?.throwIfAborted() await this.ensureRootEncoding() signal?.throwIfAborted() const generations = await this.listGenerations(signal) + const previous = this.listedHeaders + const listed = new Map() const headers = await settleLimited(this.listLimit, generations, async (selected) => { signal?.throwIfAborted() + let identity: JsonlPhysicalIdentity try { - return { selected, metadata: await this.readGenerationHeader(selected, undefined, signal) } + identity = await stat(selected.sourcePath, { bigint: true }) } catch (error: unknown) { - if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) { - return { selected, metadata: undefined } - } - throw error + signal?.throwIfAborted() + if (!isENOENT(error)) throw error + return { selected, revision: 'missing', identity: undefined, metadata: undefined } } + signal?.throwIfAborted() + const revision = fileRevision(identity) + const memo = previous.get(selected.sourcePath) + const metadata = memo !== undefined && memo.revision === revision + ? memo.metadata + : await this.readListedHeader(selected, signal) + listed.set(selected.sourcePath, { revision, metadata }) + return { selected, revision, identity, metadata } }) - const artifacts: Array = [] + const artifacts: Array = [] + const revisions: Array = [] const ids = new Set() for (const outcome of headers) { if (outcome.status === 'rejected') throw outcome.reason - const { selected, metadata } = outcome.value - if (metadata === undefined) continue + const { selected, revision, identity, metadata } = outcome.value + revisions.push([selected.sourcePath, revision]) + if (identity === undefined || metadata === undefined) continue if (ids.has(metadata.header.id)) { throw new Error(`duplicate JSONL session id "${metadata.header.id}" appears in multiple project directories`) } ids.add(metadata.header.id) - artifacts.push({ ...metadata, path: selected.sourcePath, sourceVersion: selected.sourceVersion }) + artifacts.push({ ...metadata, path: selected.sourcePath, sourceVersion: selected.sourceVersion, identity }) } signal?.throwIfAborted() - return artifacts + this.listedHeaders = listed + return { artifacts, revisions } + } + + /** Read one listed generation header; an unsupported or corrupt log is not a listed Session. */ + private async readListedHeader( + selected: ResolvedJsonlGeneration, + signal?: AbortSignal, + ): Promise { + try { + return await this.readGenerationHeader(selected, undefined, signal) + } catch (error: unknown) { + if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) { + return undefined + } + throw error + } } /** Read and translate one selected generation header without inspecting its body. */ diff --git a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts index 82f9f5b6c8..b64306806a 100644 --- a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts @@ -1,7 +1,8 @@ import { MessageId, createMessage } from '@deepseek-ai/dsh-llm' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { appendFile, mkdtemp, mkdir, rm, readFile, writeFile, readdir, stat, symlink } from 'node:fs/promises' +import { appendFile, mkdtemp, mkdir, open, rm, readFile, writeFile, readdir, stat, symlink, utimes } from 'node:fs/promises' +import type { FileHandle } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join, relative, resolve } from 'node:path' import { scheduler } from 'node:timers/promises' @@ -2066,13 +2067,13 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { const m = meta('vanishing-snapshot') await writeLog(ctx.sessionPersistence, m, oneTurnLog()) const persistence = ctx.sessionPersistence as unknown as { - listArtifacts(): Promise> + listGenerations(): Promise> } - const listArtifacts = persistence.listArtifacts.bind(persistence) - const discovery = vi.spyOn(persistence, 'listArtifacts').mockImplementation(async () => { - const artifacts = await listArtifacts() - await rm(artifacts[0]!.path) - return artifacts + const listGenerations = persistence.listGenerations.bind(persistence) + const discovery = vi.spyOn(persistence, 'listGenerations').mockImplementation(async () => { + const generations = await listGenerations() + await rm(generations[0]!.sourcePath) + return generations }) await expect(ctx.sessionPersistence.list()).resolves.toEqual([]) @@ -2081,11 +2082,13 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { it('surfaces non-ENOENT stat failures during listing', async () => { const persistence = ctx.sessionPersistence as unknown as { - listArtifacts(): Promise> + listGenerations(): Promise> } - const discovery = vi.spyOn(persistence, 'listArtifacts').mockResolvedValue([{ - header: meta('snapshot-stat-failure'), - path: `${root}\0snapshot-stat-failure`, + const path = `${root}\0snapshot-stat-failure` + const discovery = vi.spyOn(persistence, 'listGenerations').mockResolvedValue([{ + sourcePath: path, + sourceVersion: SESSION_FORMAT_VERSION, + currentPath: path, }]) await expect(ctx.sessionPersistence.list()).rejects.toThrow(/null bytes/) @@ -2094,7 +2097,7 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { it('forwards list cancellation and awaits in-flight discovery cleanup', async () => { const persistence = ctx.sessionPersistence as unknown as { - listArtifacts(signal?: AbortSignal): Promise> + listArtifacts(signal?: AbortSignal): Promise<{ artifacts: never[]; revisions: never[] }> } const started = Promise.withResolvers() const cleanup = Promise.withResolvers() @@ -2102,7 +2105,7 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { if (signal === undefined) throw new Error('expected list signal') started.resolve(signal) await cleanup.promise - return [] + return { artifacts: [], revisions: [] } }) const reason = new Error('JSONL list discovery cancelled') const controller = new AbortController() @@ -2126,11 +2129,13 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { const m = meta('snapshot-stat-cancellation') await writeLog(ctx.sessionPersistence, m, oneTurnLog()) const persistence = ctx.sessionPersistence as unknown as { - listArtifacts(signal?: AbortSignal): Promise> + listGenerations(signal?: AbortSignal): Promise> } - const discovery = vi.spyOn(persistence, 'listArtifacts').mockResolvedValue([{ - header: m, - path: rawLogPath(root, m.cwd, m.id), + const path = rawLogPath(root, m.cwd, m.id) + const discovery = vi.spyOn(persistence, 'listGenerations').mockResolvedValue([{ + sourcePath: path, + sourceVersion: SESSION_FORMAT_VERSION, + currentPath: path, }]) const reason = new Error('JSONL list stat cancelled') const controller = new AbortController() @@ -2632,6 +2637,39 @@ describe('JsonlSessionPersistence: edge cases', () => { expect(await ctx.sessionPersistence.list()).toEqual([]) }) + it('list re-reads only the headers of logs whose file changed', async () => { + const kept = meta('memo-kept', '/memo') + const changed = meta('memo-changed', '/memo') + const removed = meta('memo-removed', '/memo') + for (const m of [kept, changed, removed]) await writeLog(ctx.sessionPersistence, m, oneTurnLog()) + const created = (ids: readonly { header: SessionHeader }[]) => + Object.fromEntries(ids.map(({ header }) => [header.id, header.createdAt])) + expect(created(await ctx.sessionPersistence.list())) + .toEqual({ [kept.id]: kept.createdAt, [changed.id]: changed.createdAt, [removed.id]: removed.createdAt }) + + const path = rawLogPath(root, changed.cwd, changed.id) + const probe = await open(path, 'r') + const handles = Object.getPrototypeOf(probe) as Pick + await probe.close() + const reads = vi.spyOn(handles, 'read') + expect(created(await ctx.sessionPersistence.list())) + .toEqual({ [kept.id]: kept.createdAt, [changed.id]: changed.createdAt, [removed.id]: removed.createdAt }) + expect(reads).not.toHaveBeenCalled() + + await writeFile(path, [ + JSON.stringify(toHeaderLine({ ...changed, createdAt: changed.createdAt + 1 })), + ...oneTurnLog().map(event => JSON.stringify(event)), + '', + ].join('\n')) + // An explicit mtime keeps the revision distinct on coarse-timestamp filesystems. + await utimes(path, new Date(), new Date(Date.now() + 60_000)) + await rm(sessionDir(root, removed.cwd, removed.id), { recursive: true }) + expect(created(await ctx.sessionPersistence.list())) + .toEqual({ [kept.id]: kept.createdAt, [changed.id]: changed.createdAt + 1 }) + expect(reads).toHaveBeenCalled() + reads.mockRestore() + }) + it('keeps the transcript in an extensible session-owned directory', async () => { const m = meta('owned-directory', '/project') await writeLog(ctx.sessionPersistence, m, oneTurnLog()) diff --git a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts index 91cea44e31..eb637304a4 100644 --- a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { appendFile, mkdir, mkdtemp, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises' +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' @@ -570,6 +570,8 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { 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