diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml index 440d9e0ca4..03e90dcc66 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: e7e612a45f80e32e - zh: 211b357403747dd2 + en: c9aff3ce6e32f790 + zh: 1748bb565a366db6 /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 72023cbeeb..df20957cc0 100644 --- a/packages/session/session-persistence-jsonl/README.md +++ b/packages/session/session-persistence-jsonl/README.md @@ -86,7 +86,7 @@ Materialized `stat` and `list` snapshots include the format catalog's header cla `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. +The bundled verifier passes the Worker an absolute path string, which the single-file runtime resolves through its embedded filesystem. 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. Historical body preparation completes the parent catalog through [V3→V4](../session-format-v3-to-v4/README.md). It finds candidate direct children from headers, reads each child's own descriptor through historical codecs, and retains compact evidence plus source revisions. It neither prepares child catalogs nor publishes child successors. Unreadable or unsupported headers, including corrupt Zstandard header frames, are omitted from discovery and `list()`. Direct access to a corrupt compressed header still rejects; header I/O and cancellation errors propagate. Child decoding and descriptor-field failures produce warnings naming the child path and retain header identity through `subagent/catalog` when the parent has no complete entry; healthy children and existing parent catalog entries remain available. Opening a damaged child still reports that child's error. Missing, unsupported, or multiple descriptors likewise produce unknown-mode membership without inventing a label. Published unknown entries remain browsable; child history reads retry the actual log and resolve its mode from a valid descriptor. Preparation rechecks membership and inspected source revisions before returning, reuse, and publication, including failed child reads so a repaired child invalidates stale preparation. Source drift retries a read open once and refuses a write open. Cancellation still aborts the operation. Current V4 opens bypass discovery and validate catalog fields, uniqueness, and current delivery ownership before exposing events. diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md index fb2e3072c8..8c82392627 100644 --- a/packages/session/session-persistence-jsonl/README.zh.md +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -86,7 +86,7 @@ kind: "package-reference" `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 退出,再使校验失败。 +打包后的校验器向 Worker 传入绝对路径字符串,由单文件运行时通过内嵌文件系统解析。校验只有在 Worker 自然以退出码 0 结束后,才接受其成功响应。并发配额一直保留到该次退出;取消或 Worker 错误会先终止并等待 Worker 退出,再使校验失败。 历史正文准备通过 [V3→V4](../session-format-v3-to-v4/README.zh.md) 补齐父目录:从 header 找到候选直属子 Session,通过历史编解码器逐个读取其自身 descriptor,保留紧凑证据与来源修订。此过程不准备子目录,也不发布子后继。不可读或不支持的 header(包括损坏的 Zstandard header 帧)不参与发现,也不出现在 `list()` 中。直接访问损坏的压缩 header 仍会失败;header 的 I/O 错误与取消错误继续传播。子日志解码或 descriptor 字段失败会产生带子路径的警告;父目录没有完整条目时,通过 `subagent/catalog` 保留 header 身份信息。健康子项和已有父目录项仍可使用。打开损坏子 Session 时仍报告该子会话的错误。缺失、不支持或多个 descriptor 同样生成模式未知的目录项,不编造标签。已发布的未知条目仍可浏览;读取子历史时会重试实际日志,并从有效 descriptor 确定模式。准备返回、复用与发布前会重新检查成员集合及已检查来源的修订,也包括读取失败的子日志,使修复后的子日志能够使旧准备缓存失效。来源变化时只读打开重试一次,写打开拒绝发布。取消仍会中止操作。当前 V4 打开跳过发现,并在暴露事件前校验目录字段、唯一性及当前投递归属。 diff --git a/packages/session/session-persistence-jsonl/src/migration-verifier.ts b/packages/session/session-persistence-jsonl/src/migration-verifier.ts index a23692d802..65b9b8c22f 100644 --- a/packages/session/session-persistence-jsonl/src/migration-verifier.ts +++ b/packages/session/session-persistence-jsonl/src/migration-verifier.ts @@ -1,5 +1,6 @@ /** Isolated verification for a staged or competing current JSONL generation. */ +import { fileURLToPath } from 'node:url' import { Worker } from 'node:worker_threads' import type { WorkerOptions } from 'node:worker_threads' import type { JsonlCompression } from './format.ts' @@ -71,10 +72,11 @@ class VerificationScheduler { const verificationScheduler = new VerificationScheduler() function workerSpawn(request: VerificationRequest): { readonly entry: string | URL; readonly options: WorkerOptions } { + // The single-file runtime resolves string Worker entries through its embedded filesystem. /* v8 ignore next 3 -- built-worker coverage owns the bundled path. */ if (!import.meta.url.endsWith('.ts')) { return { - entry: new URL('./worker.cjs', import.meta.url), + entry: fileURLToPath(new URL('./worker.cjs', import.meta.url)), options: { workerData: request, execArgv: [] }, } } diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index c23847855e..455e48b9bb 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -938,6 +938,7 @@ def main() -> None: smoke_sdk_scheduler_recovery(model.url, args.exe.resolve(), args.update_snapshots) if args.scenario in {"all", "sdk-restart"}: assert args.exe is not None + smoke_sdk_v3_resume(model.url, args.exe.resolve()) smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots) if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}: smoke_sdk_profile_plugin(model.url) @@ -1888,6 +1889,63 @@ def smoke_sdk_snapshot_mode( ) +def smoke_sdk_v3_resume(base_url: str, executable: Path) -> None: + """Migrate persisted V3 history and reopen the published log in a fresh runtime.""" + from deepseek_harness import DeepSeekHarness + + with tempfile.TemporaryDirectory(prefix="dsh-sdk-v3-resume-") as temporary: + root = Path(temporary).resolve() + sessions = root / "sessions" + session_id = "v3-resume" + directory = sessions / "_no-cwd" / session_id + directory.mkdir(parents=True) + source = directory / "session.v3.jsonl" + header = { + "type": "session", "version": 3, "id": session_id, "createdAt": 1, + "isSeeded": False, "delegationDepth": 0, + } + message = { + "id": "saved-message", "role": "user", "source": {"kind": "user"}, + "content": [{"type": "text", "text": "Saved V3 history"}], + } + events = [ + {"type": "turn/start", "data": {"turn": 1}}, + {"type": "user/message", "data": message, "surfaceOp": "append"}, + {"type": "turn/end", "data": {"turn": 1, "reason": {"kind": "completed"}}}, + ] + records = [header, *({**event, "seq": seq, "time": seq + 10} for seq, event in enumerate(events))] + original = "".join(json.dumps(record) + "\n" for record in records).encode("utf-8") + source.write_bytes(original) + patch = write_profile_patch(root, "v3-resume.patch.yml", sessions, []) + request_count = len(MockModelHandler.requests) + + def connect() -> DeepSeekHarness: + return DeepSeekHarness( + provider="deepseek-official", model="smoke-model", cwd=str(root), + dsh_bin=str(executable), dsh_home=str(root / "home"), patches=(str(patch),), + env={"DSH_TELEMETRY_DISABLED": "1"}, api_key="sk-keyless-smoke", base_url=base_url, + request_timeout_seconds=60, + ) + + with connect() as harness: + session = harness.resume_session(session_id) + assert session.id == session_id, f"migration resumed {session.id!r}" + logs = read_session_logs(sessions) + assert set(logs) == {session_id}, f"unexpected persisted sessions: {list(logs)}" + assert any(row.get("type") == "user/message" and row.get("data") == message for row in logs[session_id]), ( + "the migrated log lost the saved V3 user message" + ) + (published,) = latest_persisted_session_paths(sessions) + migrated = published.read_bytes() + + with connect() as harness: + session = harness.resume_session(session_id) + assert session.id == session_id, f"restart resumed {session.id!r}" + assert published.read_bytes().startswith(migrated), "restart rewrote the published session history" + assert source.read_bytes() == original, "resuming changed the original V3 log" + assert len(MockModelHandler.requests) == request_count, "resuming sent a model request" + + def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None: """Check isolated sessions and explicit history restoration across runtime restarts.""" from deepseek_harness import DeepSeekHarness