From e0b6d6572613d7273aaa3ff33ac5efde43dc3bfa Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Sat, 14 Nov 2026 13:25:09 +0800 Subject: [PATCH] fix(tests): preserve snapshot config and drain pending reads --- packages/acp/acp/tests/bridge.spec.ts | 12 ++++----- .../owner-credential-horizon.host.spec.ts | 9 ++++++- .../session-snapshot/README.i18n.yaml | 4 +-- .../test-support/session-snapshot/README.md | 2 +- .../session-snapshot/README.zh.md | 2 +- .../session-snapshot/src/harness.ts | 9 ++++--- .../session-snapshot/src/launcher.ts | 18 ++++++++----- .../session-snapshot/tests/harness.spec.ts | 25 ++++++++++++++++--- 8 files changed, 58 insertions(+), 23 deletions(-) diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts index 60fdc85e0a..2398e1af00 100644 --- a/packages/acp/acp/tests/bridge.spec.ts +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -440,12 +440,12 @@ describe('automation-only ACP bridge', () => { }) it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([ - [null], - [[]], - [['not-a-number', 'id']], - [[-1, 'id']], - [[1, '']], - ] as const).map(value => [storage, value] as const)))('%s: rejects malformed decoded list cursors %#', async (storage, decoded) => { + null, + [], + ['not-a-number', 'id'], + [-1, 'id'], + [1, ''], + ] as const).map(decoded => ({ storage, decoded }))))('$storage: rejects malformed decoded list cursors %#', async ({ storage, decoded }) => { harness = await makeBridgeHarness(storage) await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) const cursor = Buffer.from(JSON.stringify(decoded)).toString('base64url') diff --git a/packages/experimental/liveshare/tests/owner-credential-horizon.host.spec.ts b/packages/experimental/liveshare/tests/owner-credential-horizon.host.spec.ts index fe58fe9109..ba8f48820c 100644 --- a/packages/experimental/liveshare/tests/owner-credential-horizon.host.spec.ts +++ b/packages/experimental/liveshare/tests/owner-credential-horizon.host.spec.ts @@ -13,7 +13,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, onTestFinished } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import type {} from '../src/index.ts' import { apply } from '../src/host/share-host.ts' @@ -149,6 +149,13 @@ async function host(options: { } describe('owner host credential horizon', () => { + beforeEach(() => { + // Relay I/O and polling use real timers; only credential expiry uses this fixed clock. + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(START + 60_000) + }) + afterEach(() => { vi.useRealTimers() }) + it('adopts the horizon the Relay reports for a claim past the signed expiry', async () => { const relay = await relayStandIn({ claim: { body: { claimed: true, ownerCredentialExpiresAt: LIVE } } }) onTestFinished(relay.close) diff --git a/packages/test-support/session-snapshot/README.i18n.yaml b/packages/test-support/session-snapshot/README.i18n.yaml index b7d219c943..539e060abb 100644 --- a/packages/test-support/session-snapshot/README.i18n.yaml +++ b/packages/test-support/session-snapshot/README.i18n.yaml @@ -36,8 +36,8 @@ en: 18ff76b440fe40da zh: 4dbf2eb5f9ee98a2 /deepseek-ai-dsh-session-snapshot/understand-the-implementation/design: - en: 30dc1a78497bee82 - zh: 7904f391efdaed64 + en: 3a168e7c4eea09c1 + zh: 68cea5fa0481a97e /deepseek-ai-dsh-session-snapshot/understand-the-implementation/source-map: en: 1510b3b09c3bd553 zh: 1931fba0891f7d65 diff --git a/packages/test-support/session-snapshot/README.md b/packages/test-support/session-snapshot/README.md index 88b295a4f6..4ee500aea7 100644 --- a/packages/test-support/session-snapshot/README.md +++ b/packages/test-support/session-snapshot/README.md @@ -116,7 +116,7 @@ This section explains the design of the kit; the observable behavior is fully co ### Design -The shared core owns manifests, generation-qualified role selection, workspace setup/comparison, typed identity mapping, normalizers, and fixture invariants. The ACP adapter adds four composable layers: launcher, scenario harness, normalizers, and suite factory. `launchAcpTestAgent` boots a source profile under tsx or a built `lib` profile under plain Node, connects the SDK client over a raw-byte stdout tee, collects Session updates and stderr, fails closed on unhandled permission requests, and owns shutdown. `runScenario` drives ACP JSON-RPC stdio and reads committed logical histories through `SessionPersistence.list/open/read`, including compressed JSONL and SQLite sessions. The pure normalizers replace cwd paths and typed identities with stable tokens, zero times, expand physical source-event ranges, and scrub system-prompt text and tool-schema bulk. `defineAcpSnapshotSuite` registers comparisons, generation-qualified fixture write-back, and the live uniformity guard. +The shared core owns manifests, generation-qualified role selection, workspace setup/comparison, typed identity mapping, normalizers, and fixture invariants. The ACP adapter adds four composable layers: launcher, scenario harness, normalizers, and suite factory. `launchAcpTestAgent` boots a source profile under tsx or a built `lib` profile under plain Node, connects the SDK client over a raw-byte stdout tee, collects Session updates and stderr, fails closed on unhandled permission requests, and owns shutdown. `runScenario` drives ACP JSON-RPC stdio and reads committed logical histories through `SessionPersistence.list/open/read`, including compressed JSONL and SQLite sessions. Cleanup waits for pending Session reads before removing their storage. The pure normalizers replace cwd paths and typed identities with stable tokens, zero times, expand physical source-event ranges, and scrub system-prompt text and tool-schema bulk. `defineAcpSnapshotSuite` registers comparisons, generation-qualified fixture write-back, and the live uniformity guard. ### Source map diff --git a/packages/test-support/session-snapshot/README.zh.md b/packages/test-support/session-snapshot/README.zh.md index f2086231cd..3b14daecbc 100644 --- a/packages/test-support/session-snapshot/README.zh.md +++ b/packages/test-support/session-snapshot/README.zh.md @@ -116,7 +116,7 @@ Headless/ACP 与 SDK 适配器在规范化之前,将原始目录中的子创 ### 设计 -共享核心拥有 manifest、generation 限定角色选择、workspace 设置/比较、类型化身份映射、normalizer 与 fixture 不变式。ACP 适配器增加四个可组合层:launcher、场景 harness、normalizer 与 suite factory。`launchAcpTestAgent` 在 tsx 下启动源码 profile,或在普通 Node 下启动已构建 `lib` profile,通过原始字节 stdout tee 连接 SDK client,收集 Session update 与 stderr,默认拒绝未处理的权限请求,并负责关闭。`runScenario` 驱动 ACP JSON-RPC stdio,并通过 `SessionPersistence.list/open/read` 读取已提交的逻辑历史,包括压缩 JSONL 与 SQLite 会话。纯 normalizer 把 cwd 路径与类型化身份变为稳定 token,将时间归零、展开物理来源区间,并擦除系统提示词文本与工具 schema bulk。`defineAcpSnapshotSuite` 注册比较、generation 限定 fixture 回写与实时一致性保护。 +共享核心拥有 manifest、generation 限定角色选择、workspace 设置/比较、类型化身份映射、normalizer 与 fixture 不变式。ACP 适配器增加四个可组合层:launcher、场景 harness、normalizer 与 suite factory。`launchAcpTestAgent` 在 tsx 下启动源码 profile,或在普通 Node 下启动已构建 `lib` profile,通过原始字节 stdout tee 连接 SDK client,收集 Session update 与 stderr,默认拒绝未处理的权限请求,并负责关闭。`runScenario` 驱动 ACP JSON-RPC stdio,并通过 `SessionPersistence.list/open/read` 读取已提交的逻辑历史,包括压缩 JSONL 与 SQLite 会话。清理会等待尚未完成的 Session 读取结束,再删除其存储目录。纯 normalizer 把 cwd 路径与类型化身份变为稳定 token,将时间归零、展开物理来源区间,并擦除系统提示词文本与工具 schema bulk。`defineAcpSnapshotSuite` 注册比较、generation 限定 fixture 回写与实时一致性保护。 ### 源码地图 diff --git a/packages/test-support/session-snapshot/src/harness.ts b/packages/test-support/session-snapshot/src/harness.ts index 815160f718..95b75f0423 100644 --- a/packages/test-support/session-snapshot/src/harness.ts +++ b/packages/test-support/session-snapshot/src/harness.ts @@ -238,8 +238,8 @@ export function snapshotSpillRoot( /** * Run a scenario end-to-end against a freshly-spawned subprocess. Owns the - * child and its generated dirs; always tears them down. Returns the captured stdout - * and (record mode) the harvested session-log path. + * child and its generated dirs; always tears them down after pending Session + * reads settle. Returns the captured stdout and harvested session logs. * * @param input The scenario's input script (steps + optional permission answers). * @param opts The agent to boot, the mode, and the fixture wiring. @@ -250,7 +250,8 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise const cwdAliases = [...new Set([realpathSync(cwd), realpathSync.native(cwd)])] const storage = (opts.env?.DSH_SNAPSHOT_STORAGE ?? process.env.DSH_SNAPSHOT_STORAGE ?? 'jsonl') as 'jsonl' | 'sqlite' const sessionsRoot = await mkdtemp(join(tmpdir(), 'acp-snap-sessions-')) - const readLogs = (): Promise => harvestSessionLogs(sessionsRoot, storage) + let logRead = Promise.resolve([]) + const readLogs = (): Promise => (logRead = harvestSessionLogs(sessionsRoot, storage)) let spillRoot: string | undefined // Everything past the temp-dir creation is followed by failure-safe cleanup, // so a failure in workspace seeding, spawn, or any step never leaks resources. @@ -394,6 +395,8 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise /* v8 ignore next 1 -- launch itself can only throw on a defensive synchronous spawn API failure */ await cleanup(() => launched?.close('SIGKILL') ?? Promise.resolve()) await cleanup(() => rm(cwd, { recursive: true, force: true })) + // A wait deadline can expire while its harvest still owns database or file handles. + await Promise.allSettled([logRead]) await cleanup(() => rm(sessionsRoot, { recursive: true, force: true })) const allocatedSpillRoot = spillRoot if (allocatedSpillRoot !== undefined) await cleanup(() => rm(allocatedSpillRoot, { recursive: true, force: true })) diff --git a/packages/test-support/session-snapshot/src/launcher.ts b/packages/test-support/session-snapshot/src/launcher.ts index 86a0f2ae5c..6b87a797da 100644 --- a/packages/test-support/session-snapshot/src/launcher.ts +++ b/packages/test-support/session-snapshot/src/launcher.ts @@ -358,12 +358,18 @@ function profileArgs( const materializedRoot = join(cwd, '.dsh-profile-patches') mkdirSync(materializedRoot, { recursive: true }) const materializedDir = mkdtempSync(join(materializedRoot, 'launch-')) - const materialized = patches.map((file, index) => materializeProfilePatch(file, cwd, profile, materializedDir, index)) - if (storage !== undefined) { - const storagePatch = join(materializedDir, 'session-storage.yml') - writeFileSync(storagePatch, stringifyEntryYaml([{ id: 'session-persistence-jsonl', config: { storage } }])) - materialized.push(storagePatch) - } + const materialized = patches.map((file, index) => { + const target = materializeProfilePatch(file, cwd, profile, materializedDir, index) + if (storage === undefined) return target + const entries = parseEntryYaml(readFileSync(target, 'utf8')) as PatchOptions[] + for (const entry of entries) { + if (entry.id === 'session-persistence-jsonl' && entry.config !== undefined) { + entry.config = { ...(entry.config as object), storage } + } + } + writeFileSync(target, stringifyEntryYaml(entries, { lineWidth: -1 })) + return target + }) return ['--profile', profile, ...materialized.flatMap(file => ['--patch', file])] } diff --git a/packages/test-support/session-snapshot/tests/harness.spec.ts b/packages/test-support/session-snapshot/tests/harness.spec.ts index f77bb0c318..1af2591f1e 100644 --- a/packages/test-support/session-snapshot/tests/harness.spec.ts +++ b/packages/test-support/session-snapshot/tests/harness.spec.ts @@ -194,6 +194,10 @@ describe.each(['jsonl', 'sqlite'] as const)('runScenario (%s)', (storage) => { ]) await Promise.all([ writeFile(basePatch, [ + '- id: session-persistence-jsonl', + ' config:', + ' root: ./sessions', + ' compression: none', '- id: asserted', ' name: ./plugin.mjs', ' disabled: true', @@ -235,8 +239,9 @@ describe.each(['jsonl', 'sqlite'] as const)('runScenario (%s)', (storage) => { expect(materialized).toContain(pathToFileURL(join(patchDir, 'plugin.mjs')).href) expect(materialized).toContain(pathToFileURL(join(dir, 'nested.mjs')).href) expect(materialized).toContain('example-package') - expect(await readFile(await materializedPatch(materializedRoot, 'session-storage.yml'), 'utf8')) - .toContain(`storage: ${storage}`) + expect(materialized).toContain('root: ./sessions') + expect(materialized).toContain('compression: none') + expect(materialized).toContain(`storage: ${storage}`) expect(await realpath(join(dir, '.dsh', 'profiles', 'acp', 'node_modules', 'example-package'))) .toBe(await realpath(packageDir)) expect(await realpath(join(dir, '.dsh', 'profiles', 'acp', 'node_modules', '@fixture', 'example-package'))) @@ -1003,16 +1008,29 @@ describe.each(['jsonl', 'sqlite'] as const)('runScenario (%s)', (storage) => { const reading = Promise.withResolvers() const release = Promise.withResolvers() let pendingRead: Promise | undefined + let readSettled = false const originalReaddir = readdir + const originalRm = rm const spy = vi.spyOn(fsPromises, 'readdir').mockImplementation(async (...args) => { if (pendingRead === undefined && String(args[0]).includes('acp-snap-sessions-')) { - const read = release.promise.then(() => originalReaddir(...args)) + const read = (async () => { + await release.promise + try { return await originalReaddir(...args) } + finally { readSettled = true } + })() pendingRead = read reading.resolve(undefined) return await read } return await originalReaddir(...args) }) + const remove = vi.spyOn(fsPromises, 'rm').mockImplementation(async (...args) => { + const path = String(args[0]) + const readingStorage = path.includes('acp-snap-sessions-') && !readSettled + await originalRm(...args) + if (path.includes('acp-snap-cwd-')) release.resolve(undefined) + expect(readingStorage).toBe(false) + }) const run = runScenario( { steps: [...boot, step] }, { agent: AGENT, mode: 'replay', fixtureFile }, @@ -1027,6 +1045,7 @@ describe.each(['jsonl', 'sqlite'] as const)('runScenario (%s)', (storage) => { release.resolve(undefined) await Promise.allSettled([pendingRead, run, rejected]) spy.mockRestore() + remove.mockRestore() } })