@davideasden/pi-undo 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -167,7 +167,7 @@ recovery_required
167
167
 
168
168
  ### Performance Notes
169
169
 
170
- 普通文件原生恢复路径保留 5 次完整拓扑扫描。macOS/Linux 的新版 helper 使用不跟随符号链接的目录句柄扫描,仍会发现 Git 忽略目录中的嵌套仓库。小工作区根据上次扫描规模选择 TypeScript 完整重扫,避免进程启动开销;没有使用 TTL 缓存或默认跳过 `node_modules`。
170
+ 普通文件恢复在持有 workspace 独占锁时,先逐项核验 changedPaths 中的叶子文件;若与 checkpoint source 一致,就直接复用 manifest,避免额外 scoped capture 和全目录扫描。目录 scope、内容不匹配或 source 无法证明时仍走 scoped safety capture。成功路径保留 `restore-pre` 与 `restore-post` 两次 topology 检查,并继续执行 scope 内可见路径校验;锁内省略其后的重复 topology 扫描。native helper 仍不跟随符号链接地扫描 ignored 目录中的嵌套仓库;没有默认跳过 `node_modules`,也没有使用 TTL 缓存。
171
171
 
172
172
  原生恢复可处理已有父目录中的普通文件删除、覆盖、创建及混合计划。`restore-files-v2` 覆盖子目录删除和混合 mutation;`restore-files-v3` 会把分散在大量父目录中的文件拆成多个批次,每批最多打开 128 个非根父目录句柄。旧 helper、缺少二进制、目录操作、类型替换及单条路径深度超过句柄预算时继续走 TypeScript 路径。durable pack、逐项内容校验、no-clobber 与恢复依据均保留。
173
173
 
@@ -214,6 +214,15 @@ Performance gains come from:
214
214
  - **Durable pack caching** — completed agent runs build and cache reverse/forward durable packs; the undo/redo hot path reuses the cached pack with manifest pin, avoiding redundant snapshot reads.
215
215
  - **Indexed WAL record lookups** — mutation records are indexed by ordinal for O(1) direct access instead of linear scan.
216
216
  - **Indexed path conflict resolution** — `exactExclusions` are stored as a Set for O(1) membership checks instead of O(n) `Array.includes`.
217
+ - **Private ODB compaction** — once 4,096 loose objects (or 256 MiB) have stayed above the threshold for 5 minutes, they are packed so `cat-file --batch-check` and blob reads use the pack index. Deferring avoids charging the repack (≈2.7 s for 20k objects) to the first undo after a large change; 10k-object `assertComplete` drops from ~331 ms to ~49 ms and 10k-blob reads from ~443–966 ms to ~158 ms once packed.
218
+ - **Indexed mutation path checks** — `MutationPathIndex` replaces the per-target-path `[...deletePaths, ...writePaths].some(...)` scan (10k × 10k ≈ 962 ms → < 1 ms).
219
+ - **Deduped batch blob reads** — object IDs are deduplicated with a `Set` instead of `Array.includes` (10k unique blobs ≈ 101 ms → 2.2 ms).
220
+ - **Shared, parallel parent validation** — native metadata inspect validates the deduplicated parent set once per request with 32-way concurrency (10k deep paths 111.7 ms → 71.0 ms).
221
+ - **Persistent resident scan cache** — `--serve` starts from the on-disk v2 directory cache and writes it back; idle timeout raised to 600 s. 20k-directory cold start 377 ms → 251 ms with a warm cache, steady-state requests remain 13–20 ms.
222
+ - **Racy-window baseline skip** — settled capture skips the guaranteed-failing `isBaselineFresh` probe within 2 s after a restore, removing ~227–240 ms from the settlement path.
223
+ - **Transferred pack payloads** — the restore path hands pack ownership of its freshly read blobs instead of copying them (64 MiB benchmark: +64.0 MiB → +0.01 MiB extra ArrayBuffers, +2.3 MiB RSS), and the pack checksum is computed during the write pass.
224
+
225
+ The ignored-present proof still runs `git ls-files --others --ignored --exclude-standard` on every full capture (~363 ms for 10k ignored files on the local benchmark). Reusing a previous proof needs directory-cache evidence to cross the helper boundary, which is tracked in `docs/native-performance.md` as the remaining follow-up.
217
226
  - **Batch validated manifest blob reads** — durable pack reads coalesce blob fetches into a single batch per manifest with combined Git validation.
218
227
 
219
228
  ## How It Works
@@ -1,6 +1,6 @@
1
1
  # 原生目录扫描与普通文件恢复性能验证
2
2
 
3
- 本轮实现目录项缓存与 scoped restore 的可见路径检查,保留恢复前后的拓扑校验。目录扫描仍会逐个打开、核验工作区内的目录;缓存减少 `readdir`,没有把整次检查变成只访问 changedPaths 的增量操作。
3
+ 本轮实现目录项缓存与 scoped restore 的可见路径检查;普通一次性扫描仍会逐个打开、核验工作区内的目录,宽目录最多使用 16 个有界 worker 并行处理。常驻 `--serve` 在 macOS 上使用 FSEvents 收集变更父目录,只重新枚举受影响祖先并合并局部 cache;无变化请求复用驻留 cache,事件丢失、监听停止或扫描竞争时回退完整校验。
4
4
 
5
5
  ## Durable pack 准备与批量写入
6
6
 
@@ -74,7 +74,7 @@ plan 额外报告 `plan.validate`、`plan.complete`、`plan.paths`、`plan.diff`
74
74
 
75
75
  小文件冷缓存三次为基线 `[1980, 1922, 1938]`、最终 `[1560, 1526, 1511]`。热缓存、稀疏修改和大文件没有证明稳定提速。未充分覆盖目录的稀疏大 scope 可能增加一次有界探测开销;超过探测预算时回退精确查询,不复用部分结果。
76
76
 
77
- 真实 Pi 1.3.0 SDK、10,000 个 ignored 依赖包场景也分别进行了三次 undo/redo,验证每次内容、历史状态和五次拓扑发现。耗时中位数如下:
77
+ 本轮真实 Pi 1.3.0 SDK、10,000 个 ignored 依赖包场景此前分别进行了三次 undo/redo,验证每次内容、历史状态和五次拓扑发现;该数据记录的是当时版本,不代表当前复用 durable source 的扫描次数。耗时中位数如下:
78
78
 
79
79
  | 场景 | undo 基线 → 最终 | redo 基线 → 最终 |
80
80
  | --- | ---: | ---: |
@@ -105,13 +105,13 @@ metadata inspect 默认每批最多处理 2,048 条路径,并受 1 MiB 路径
105
105
 
106
106
  GitRunner 会对单次 Git stdout 应用 256 MiB 硬上限;超过上限时终止整个 Git 进程组并抛出 `git_output_limit`,避免在 `Buffer.concat(...).toString()` 阶段触发 Node.js `ERR_STRING_TOO_LONG` 或无界内存增长。正常的 blob batch 读取仍按 16 MiB 分批,不受该上限影响。
107
107
 
108
- - `scan-directories-v2` 在 macOS/Linux 上缓存每个目录的 `dev/ino/mtime/ctime`、Git 标记和直接子目录。每次检查仍核验全部目录的身份与时间戳,匹配时才复用目录项。检查点之间发生变化的目录重新枚举;扫描期间发生变化则显式失败,不接受部分结果。
108
+ - `scan-directories-v2` 在 macOS/Linux 上缓存每个目录的 `dev/ino/mtime/ctime`、Git 标记和直接子目录。一次性 helper 及常驻服务的完整回退路径仍核验全部目录;常驻 macOS 服务收到可靠 FSEvents 后只重新枚举变更父目录和祖先,其他未受影响子树按 cache 整体复用。宽目录按最多 16 个 worker 分批并行,避免为每个目录创建线程。直接命中的 racy 目录不会被局部路径直接复用,而是重新枚举。
109
109
  - 缓存把 racy 标记固化到记录中,以开始枚举目录前的观察时刻计算两秒窗口。长子树扫描或之后的时间流逝不会让旧的 racy 记录自动变成可信记录。时间戳纳秒部分为零、无效或处于未来时采取保守重扫。
110
110
  - 扫描继续进入 ignored 目录,以发现其中的嵌套仓库;不进入名称恰为 `.git` 的元数据目录,不跟随 symlink。目录句柄、父子绑定和工作区身份检查保留。超过 128 层时丢弃原生部分结果,由 TypeScript 从根重扫。
111
111
  - v2 cache 绑定工作区路径与身份,结构解析失败或不匹配时不复用。它位于工作区外的私有临时目录,位置检查会解析 `TMPDIR` 的符号链接;无法安全放置请求时使用 TypeScript。cache 创建失败时使用本次请求目录,cache 写入失败不使成功扫描失败。正常进程退出时尽力清理,强制终止仍可能留下系统临时文件。
112
112
  - 能力探测一次取得 capability 集合;旧 `scan-directories-v1` helper 继续完整扫描,缺少 helper 时使用 TypeScript。扫描仍受操作剩余时间和 `PI_UNDO_OPERATION_TIMEOUT_MS` 限制,取消或未确认退出保持原有处理契约。
113
113
  - `listVisibleLeafPaths` 支持 `includePaths`。带 scope 的 complete restore 只枚举 scope 内的可见叶子;scope 外新增文件保留,scope 内新增可见路径仍会在修改前阻止恢复。未指定 scope 的完整恢复继续枚举整个工作区。嵌套仓库边界、内容、mode、symlink、mutation journal 和 quarantine 检查保留。
114
- - 本轮没有引入 FSEvents/inotify 变更索引,也没有消除 settled 阶段完整 baseline 的枚举成本。因此,目录很多或 baseline 捕获很慢的工作区仍可能有明显等待,不能据此保证用户的 50GB 项目达到秒级响应。
114
+ - 常驻 `--serve` 在 macOS 上使用带 file events 的 FSEvents stream,按事件路径归并到父目录;事件 dropped、路径无法解析、监听线程停止或扫描前后仍有新事件时回退完整扫描。事件取样有短暂 settle 窗口,以覆盖文件操作刚完成但系统尚未投递事件的情况;Linux/Windows 仍使用现有回退路径。
115
115
 
116
116
  缓存信任应用进程创建的私有文件及操作系统提供的目录元数据,不提供跨整个工作区的原子快照,也不提供抵抗同用户篡改 cache 的完整性保证。
117
117
 
@@ -127,6 +127,142 @@ GitRunner 会对单次 Git stdout 应用 256 MiB 硬上限;超过上限时终
127
127
 
128
128
  此前开发中一次 v2 采样为 `[2443, 2423, 2419]` ms;它与最终对比属于不同批次,不合并计算。三次本机采样只能说明这一基准的表现,没有墙钟性能断言,也没有对用户实际 50GB 项目、其他平台或其他磁盘作出速度保证。
129
129
 
130
+ ## 本轮追加:撤销前序准备与拓扑扫描
131
+
132
+ 真实 Pi SDK、10,000 个 ignored 依赖包、单文件变更的三次 undo/redo 基准中,改动前 undo 中位数为 2,150 ms、每次 3 次完整拓扑发现;改动后中位数为 1,745 ms、每次 2 次发现。单次诊断中 safety 阶段从 504 ms 降至 90 ms:当 `changedPaths` 全部是叶子且工作区内容逐项匹配 checkpoint source 时,直接复用 source manifest;目录 scope、内容不匹配或无法证明时仍走原 scoped safety capture。运行时持有 workspace lock 后,visible-pre 的可见路径校验保留,但跳过其后的重复 topology 扫描;`restore-pre` 和 `restore-post` 两次检查仍保留。上述为本机样本,墙钟数据会受扫描缓存和负载影响,不构成其他工作区的速度保证。
133
+
134
+ ## 私有 ODB 合并、父目录校验与 pack 内存
135
+
136
+ 本轮不改恢复语义,只处理五类剩余成本:私有快照库长期保留 loose object、恢复路径上的两处 O(n²)、native metadata inspect 的重复父目录校验、常驻扫描重启后的冷启动,以及 durable pack 的整份 payload 副本。
137
+
138
+ ### 私有 ODB 定期合并 loose object
139
+
140
+ 私有仓库显式关闭了 `gc.auto` 与 `maintenance.auto`,此前没有任何 repack 路径,capture 写入的 blob/tree 会一直以 loose object 保留。`cat-file --batch-check` 与 `cat-file --batch` 因此需要逐个打开 loose 文件。
141
+
142
+ 现在 `captureBaselineLocked` 在完整 capture 结束后检查 `git count-objects -v`,满足以下条件才合并:
143
+
144
+ - loose 对象达到 4,096 个或 256 MiB;
145
+ - 该状态已持续至少 5 分钟(首次越阈值只写 `pi-undo-compact.json` 观察时间,不立即 repack);
146
+ - 距离上次检查至少 60 秒(`count-objects` 在 2 万对象库上约 80–100 ms,不能每次 settle 都付)。
147
+
148
+ 真正执行时按磁盘上的 loose object 列表调用 `git pack-objects`,再 `git prune-packed`。私有仓库没有 refs,`git repack -a` 不会把 manifest 引用的对象视为可达,因此不能直接使用 repack。维护窗口与 capture 共用 store 锁,调用方(settled capture)同时持有 workspace 独占锁;维护失败不影响已经完成的 capture。维护耗时单独报告为 `settled.compact`,不计入 `settled.fullCapture`。默认阈值可通过 `SnapshotStoreOptions.compactMinLooseObjects` / `compactMinAgeMs` 调整,`compactMinLooseObjects: 0` 表示禁用。
149
+
150
+ **为什么延迟 5 分钟**:A/B 复测发现“立即合并”会让大改动后的第一次 undo 变慢。10,000 个文件全部修改、settle 完整 capture 后再 `prepareDurableRestore` 的本机结果:
151
+
152
+ | 方案 | settle(含维护) | prepare(含 plan + pack) | 合计 |
153
+ | --- | ---: | ---: | ---: |
154
+ | 基线(不合并) | 3,997 ms | 2,490 ms | 6,487 ms |
155
+ | 立即合并(旧版本轮实现) | 6,074 ms(其中 repack 2,666 ms) | 1,140 ms | 7,214 ms |
156
+ | 延迟合并(当前实现) | 3,651–3,684 ms(检查约 134 ms) | 1,728–1,775 ms | 5,379–5,459 ms |
157
+
158
+ 立即合并虽然把 `plan.complete` 从约 930 ms 降到约 299 ms,但 repack 成本(20,403 个对象约 2.7 s,其中 `prune-packed` 约 1 s)被提前到刚写完这批对象的时候,单次流程反而更慢。延迟到 5 分钟后,repack 摊销到后续多次 plan/verify:每次 undo 约省 600 ms,约 4–5 次后收回成本。
159
+
160
+ 合并前后(10,000 个内容各异的文件,真实 `SnapshotStore`):
161
+
162
+ | 指标 | 合并前(loose) | 合并后(packed) |
163
+ | --- | ---: | ---: |
164
+ | `assertComplete`(10k blob) | 331 ms | 49 ms |
165
+ | `readBlobs`(10k blob,含 manifest 复验) | 443–966 ms | 158 ms |
166
+ | `count-objects` | `count: 10202, in-pack: 0` | `count: 0, in-pack: 10205` |
167
+
168
+ ### 本轮端到端 A/B 复核
169
+
170
+ 基线为合并前的 `ce0b71e5`;两侧在隔离 worktree 中顺序运行同一用例。
171
+
172
+ **大型工作区(10,000 个依赖包,修改 1 个文件)**:每次调用 3 次 undo/redo,三次调用结果:
173
+
174
+ | 指标 | 基线 | 本轮 |
175
+ | --- | ---: | ---: |
176
+ | undo 中位数 | 345 / 343 / 335 ms | 367 / 337 / 328 ms |
177
+ | redo 中位数 | 565 / 563 / 567 ms | 636 / 569 / 561 ms |
178
+ | 扫描次数 | 2 / 2 / 2 | 2 / 2 / 2 |
179
+
180
+ 差异在运行波动内,**没有证明该场景的端到端提速**。该场景的可见文件只有 2 个,扫描已是常驻 13–20 ms 稳态,本轮改动主要作用在 10k 文件的捕获/校验路径,不改变这条主耗时。
181
+
182
+ **durable pack 准备(10,001 个文件全部修改,冷/热各三次)**:
183
+
184
+ | 场景 | 基线 | 本轮 | 变化 |
185
+ | --- | ---: | ---: | ---: |
186
+ | 冷缓存完整准备 | 2,598 / 2,449 / 2,431 ms | 1,697 / 1,666 / 1,666 ms | 约 -32% |
187
+ | 热缓存完整准备 | 1,852 / 1,852 / 1,808 ms | 1,039 / 1,060 / 1,060 ms | 约 -43% |
188
+ | `prepare.blobs` | 892–978 ms | 148–173 ms | 约 6× |
189
+ | `plan.complete`(loose) | 约 900 ms | 约 900 ms | 不变 |
190
+
191
+ 主要收益来自 `readBlobs` 的 `Set` 去重(10k 唯一 blob 的 `Array.includes` 约 100 ms)与 `MutationPathIndex`;`plan.complete` 只有在 ODB 合并后才从约 930 ms 降到约 299 ms。
192
+
193
+ **native metadata inspect**:10,000 个深路径(20,001 个父目录)从 111.5–112.8 ms 降到 68.3–72.3 ms;10 个路径的小请求 4.25–4.27 ms → 4.16–4.32 ms,加入“小于 64 个父目录保持串行”后没有回归。
194
+
195
+ **常驻扫描**:20,002 个目录的 serve 冷启动 377 ms、带持久缓存 251 ms、稳态 13–20 ms。该收益在进程重启/长空闲后才体现;同一 session 内的连续 discover 本来就是稳态。
196
+
197
+ **racy 窗口 baseline 探测**:A/B 中强制 `skipBaselineProbe` 时 `settled.baselineValidation` 从 530 ms 降到 0 ms;实际只在 restore 后 2 秒内的下一次 settle 生效,不是每轮都有的收益。
198
+
199
+ ### 恢复路径的 O(n²)
200
+
201
+ - `MutationPathIndex`(`src/path-safety.ts`):`reusableTargetPaths` 原实现对每个 target path 重新展开 `[...deletePaths, ...writePaths]` 并线性扫描,10k × 10k 时约 962 ms。现在一次构建精确集合与排序列表,单次判定近 O(log n),同数据形状 < 1 ms(构建 1.6 ms)。语义与 `mutationPath === path || mutationPath.startsWith(path + "/") || path.startsWith(mutationPath + "/")` 逐项等价,随机集合差分测试覆盖。
202
+ - `SnapshotStore.readBlobs`:同一 ODB 内的对象 ID 去重从 `Array.includes` 改为 `Set`,10k 个唯一 blob 从约 101 ms 降到 2.2 ms。该路径会在 durable pack 预制的 source/target 两个方向各执行一次。
203
+
204
+ ### native metadata inspect 父目录校验
205
+
206
+ `inspect-batches` 原来按 batch 各自构建 `BTreeSet<PathBuf>` 父目录集合并前后各校验一遍;10,000 个 `node_modules/pkg/lib/index.js` 会收集 20,001 个父目录、执行 40,002 次 `lstat`。现在:
207
+
208
+ - 路径校验与父目录收集在整个请求内共享,parent 集合用 `HashSet<&str>` 借用请求中的路径字符串,避免为每个祖先分配 `PathBuf`;
209
+ - 父目录校验用与叶子 stat 相同的 32 路并发执行,前后仍然各一次;
210
+ - 保留原有 symlink/非目录诊断;macOS 上 `O_NOFOLLOW|O_DIRECTORY` 对 symlink 返回 `ENOTDIR` 的差异不再影响判定,因为改为直接 `lstat`。
211
+
212
+ 本机 10k 深路径(20,001 个父目录)`--inspect-batches`:111.7 ms → 71.0 ms,约 36%;平铺 10k 路径的基线仍约 20 ms。
213
+
214
+ ### 常驻扫描的持久缓存与闲置超时
215
+
216
+ `--serve` 握手新增可选 `cachePath`。启动时读取一次性扫描使用的 v2 目录缓存作为初始 `previous`,每个目录仍逐项核验元数据,漂移会重新枚举;初始扫描结束后把最终目录表原子写回,供下一次进程启动复用。闲置超时从 60 s 提高到 600 s,TS 客户端从 70 s 提高到 610 s,避免间歇使用时反复付冷启动。
217
+
218
+ 本机 20,002 个目录:
219
+
220
+ | 场景 | 初始扫描 |
221
+ | --- | ---: |
222
+ | serve 冷启动(无缓存) | 377 ms |
223
+ | serve 使用持久缓存启动 | 251 ms |
224
+ | serve 稳态请求(无变化/单文件变化) | 13–20 ms |
225
+
226
+ ### settled 的 baseline 探测
227
+
228
+ restore 成功后 2 s 内的 racy-clean 窗口内,文件 ctime 尚未稳定,`isBaselineFresh` 必然返回 false,但仍会完整执行 `assertObjectsComplete`、`collectVisibleLeaves`、ignored proof 和叶子复核。调用方在这个窗口内传入的 baseline 已确定失效,因此 `CaptureOptions.skipBaselineProbe` 直接进入 fullCapture。
229
+
230
+ 控制器只在 `changedPaths.length > 0` 的 restore 后记录 target baseline;空 changedPaths 的 session-only undo 不写文件,探测仍可能成功,不跳过。多文件工作区实测 `settled.baselineValidation` 约 227–240 ms,本改动把这部分从结算路径上移除(诊断中保留 0 ms 阶段)。
231
+
232
+ ### durable pack 的内存副本
233
+
234
+ `createDurablePack` 默认仍在校验前复制 payload,保证调用方之后改写输入不影响磁盘与驻留 pack。`restore-engine` 的 blob 来自本次操作独占的 store 读取,两个生产调用点改用 `payloadOwnership: "transfer"`,pack 直接引用这些 buffer。`loadDurablePack` 也不再为每个 variant 复制 payload,而是共享同一次 `readFile` 的 subarray,`leaf()` 返回时再复制。pack checksum 改为在 `writeAll` 按实际写出的字节增量计算,发布后不再完整遍历 payload。
235
+
236
+ 本机独立进程 64 MiB payload 基准(阶段边界观测,不是瞬时峰值):
237
+
238
+ | 模式 | 额外 ArrayBuffer | 额外 RSS | `pack.checksum` |
239
+ | --- | ---: | ---: | ---: |
240
+ | copy(默认/旧行为) | 64.0 MiB | 66.8 MiB | 24 ms |
241
+ | transfer(生产路径) | 0.01 MiB | 2.3 MiB | ~0 ms |
242
+
243
+ `PI_UNDO_PACK_MEMORY_TRANSFER=1` 可复现 transfer 数值;输入 buffer 本身仍由调用方持有,因此该表只表示 pack 阶段的额外增量。
244
+
245
+ ### 仍未处理:ignored-present proof 的全量枚举
246
+
247
+ `captureIgnoredPresentPaths` 每次完整 capture 仍执行 `git ls-files --others --ignored --exclude-standard`。本机 10,000 个 `node_modules` 忽略文件约 363 ms(`--directory` 可降到约 30 ms,但会丢失具体路径,无法直接替代 proof)。复用旧 proof 需要证明 ignored 子树的目录项集合未变,即把目录扫描的 cache 复用证据(或 FSEvents 代数)传递到 capture;这需要新的 helper 协议和缓存 schema 变更,本轮未实现,避免在恢复安全判定上引入未经复核的信任路径。当前只完成了同一条路径上 native inspect 部分的优化。
248
+
249
+ ### 测试与复现
250
+
251
+ 新增覆盖:MutationPathIndex 随机差分、readBlobs 重复请求只发一次 batch、`skipBaselineProbe` 直接完整捕获、自动 loose object 合并与阈值以下不重写 pack、transfer 所有权与 copy 逐字节一致且 `leaf()` 仍返回副本、serve handshake 的 cachePath(`PI_UNDO_RUN_RESIDENT_LIVE=1` 冒烟用例)。
252
+
253
+ ```bash
254
+ npm run build:native
255
+ cp native/pi-undo-fs/target/release/pi-undo-fs native/bin/pi-undo-fs-darwin-arm64
256
+ npm run test:native
257
+ npm test
258
+ npm run typecheck
259
+ PI_UNDO_PACK_MEMORY_BENCHMARK=1 npx vitest run test/durable-pack-memory-benchmark.test.ts
260
+ PI_UNDO_PACK_MEMORY_BENCHMARK=1 PI_UNDO_PACK_MEMORY_TRANSFER=1 npx vitest run test/durable-pack-memory-benchmark.test.ts
261
+ PI_UNDO_RUN_RESIDENT_LIVE=1 npx vitest run test/resident-live.test.ts
262
+ ```
263
+
264
+ 本轮未在本机验证 Linux、其他架构或 Windows 的构建与运行;发布仍依赖现有六平台构建流程。
265
+
130
266
  ## 上一轮原生优化的历史数据
131
267
 
132
268
  下表保留上一轮以 `d7d80230` 为起点的结果,便于追踪原生扫描及普通文件恢复的收益;这些数据不是本轮缓存改动的前后对比。单位为毫秒。
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davideasden/pi-undo",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/controller.ts CHANGED
@@ -49,6 +49,7 @@ export interface ControllerDependencies {
49
49
  baseline: SnapshotManifest,
50
50
  onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
51
51
  onTiming?: (phase: string, durationMs: number) => void,
52
+ options?: CaptureBaselineOptions,
52
53
  ) => Promise<SnapshotManifest>;
53
54
  readonly captureSafety?: (
54
55
  referenceManifestId: ManifestId,
@@ -87,6 +88,14 @@ export interface ControllerDependencies {
87
88
  readonly onSettlement?: (diagnostic: SettlementDiagnostic) => void | Promise<void>;
88
89
  }
89
90
 
91
+ export interface CaptureBaselineOptions {
92
+ /**
93
+ * 调用方已证明 baseline 一定不是当前状态(例如 restore 后仍在 racy-clean 窗口内),
94
+ * 跳过 isBaselineFresh 的完整探测,直接走 fullCapture。
95
+ */
96
+ readonly skipBaselineProbe?: boolean;
97
+ }
98
+
90
99
  export interface JournalPort {
91
100
  prepare(descriptor: OperationDescriptor, plan: unknown): Promise<void>;
92
101
  setPhase(
@@ -322,16 +331,23 @@ export class UndoControllerImpl implements UndoController {
322
331
  return true;
323
332
  }
324
333
 
325
- private runBackground<T>(body: () => Promise<T>): Promise<T> {
334
+ private runBackground<T>(body: () => Promise<T>, deferStart = false): Promise<T> {
326
335
  const scope = createOperationScope({ timeoutMs: this.operationTimeout() });
327
336
  this.backgroundScopes.add(scope);
328
- const task = runWithOperationContext(scope.context, async () => {
337
+ const start = (): Promise<T> => runWithOperationContext(scope.context, async () => {
329
338
  try {
330
339
  return await body();
331
340
  } finally {
332
341
  if (operationHasUnconfirmedExit()) this.recordUnsafeExit({ code: "process_exit_unconfirmed" });
333
342
  }
334
- }).finally(() => {
343
+ });
344
+ let task!: Promise<T>;
345
+ const execution = deferStart
346
+ ? new Promise<T>((resolve, reject) => {
347
+ setImmediate(() => start().then(resolve, reject));
348
+ })
349
+ : start();
350
+ task = execution.finally(() => {
335
351
  scope.dispose();
336
352
  this.backgroundScopes.delete(scope);
337
353
  this.backgroundTasks.delete(task);
@@ -387,12 +403,12 @@ export class UndoControllerImpl implements UndoController {
387
403
  if (this.disposed || this.locked || this.warmUpInFlight !== undefined) return;
388
404
  const warmUp = this.runBackground(async () => {
389
405
  try {
390
- this.warmUpManifest = await this.captureWithWorkspaceLock();
406
+ this.warmUpManifest = await this.captureWithWorkspaceLock(true);
391
407
  } catch (error) {
392
408
  this.recordUnsafeExit(error);
393
409
  // 预热是 best-effort:失败静默,正式 capture 会再次尝试并上报。
394
410
  }
395
- });
411
+ }, true);
396
412
  this.warmUpInFlight = warmUp;
397
413
  void warmUp.finally(() => {
398
414
  if (this.warmUpInFlight === warmUp && this.warmUpManifest === undefined) {
@@ -439,7 +455,7 @@ export class UndoControllerImpl implements UndoController {
439
455
  this.lastCaptureFailureMessage = undefined;
440
456
  this.deferAgentStartUntilMessageEnd = true;
441
457
  const token = Symbol("input-capture");
442
- const promise = this.runBackground(() => this.captureInputForToken(text, token));
458
+ const promise = this.runBackground(() => this.captureInputForToken(text, token), true);
443
459
  this.pendingInputCapture = { token, promise };
444
460
  void promise.then(() => {
445
461
  if (this.pendingInputCapture?.token === token) this.pendingInputCapture = undefined;
@@ -519,6 +535,8 @@ export class UndoControllerImpl implements UndoController {
519
535
  // warm-up 仍在进行时先等待,确保随后可以消费已完成的 baseline,而不是再次完整 capture。
520
536
  const warmUp = this.warmUpInFlight;
521
537
  if (warmUp !== undefined) await warmUp;
538
+ // 输入事件已经返回后再进入实际捕获,优先让终端处理 Esc、命令和重绘。
539
+ await yieldToEventLoop();
522
540
  const warmUpManifest = this.warmUpManifest;
523
541
  this.warmUpManifest = undefined;
524
542
  if (this.warmUpInFlight === warmUp) this.warmUpInFlight = undefined;
@@ -565,7 +583,7 @@ export class UndoControllerImpl implements UndoController {
565
583
  if (this.disposed) return Promise.resolve();
566
584
  if (this.settling !== undefined) return this.settling;
567
585
  const run = this.runCompletion;
568
- const settled = this.runBackground(() => this.settleRun(run));
586
+ const settled = this.runBackground(() => this.settleRun(run), true);
569
587
  this.settling = settled.finally(() => {
570
588
  this.settling = undefined;
571
589
  // settleRun 成功或失败后都结束本轮等待凭据。
@@ -617,16 +635,21 @@ export class UndoControllerImpl implements UndoController {
617
635
  try {
618
636
  // settled 复用 run 开始时的 before;helper 在缺少 captureBaseline 时回退完整 capture。
619
637
  // 撕裂捕获(并发写撞上断言窗口)是暂态的:短暂退避后重试一次,成功则不清空历史。
638
+ // racy-clean 窗口(2s)内文件 ctime 未稳定,isBaselineFresh 必然失败且会多跑一轮
639
+ // collectVisibleLeaves;只有超过 2s 后才能从 target manifest 受益。
640
+ const appliedTargetInRacyWindow = appliedTargetManifest !== undefined &&
641
+ appliedTargetAt !== undefined && performance.now() - appliedTargetAt < 2_000;
620
642
  const after = await measure("settled.capture", () =>
621
643
  this.captureSettledBaselineWithRetry(
622
- // racy-clean 窗口(2s)内文件 ctime 未稳定,isBaselineFresh 必然失败且会多跑一轮
623
- // collectVisibleLeaves;只有超过 2s 后才能从 target manifest 受益。
624
- (appliedTargetManifest !== undefined && appliedTargetAt !== undefined &&
625
- performance.now() - appliedTargetAt >= 2_000)
644
+ appliedTargetManifest !== undefined && appliedTargetAt !== undefined &&
645
+ !appliedTargetInRacyWindow
626
646
  ? appliedTargetManifest
627
647
  : staged.before,
628
648
  (diagnostic) => captureDiagnostics.push(diagnostic),
629
649
  recordCaptureTiming,
650
+ // 窗口内传入的 baseline 是 restore 前的 staged.before,已确定失效;
651
+ // 探测只会白跑一轮,直接进入 fullCapture。
652
+ { skipBaselineProbe: appliedTargetInRacyWindow },
630
653
  ));
631
654
  failureStage = "settled.changedPaths";
632
655
  const changedPaths = await measure("settled.changedPaths", () =>
@@ -1036,8 +1059,10 @@ export class UndoControllerImpl implements UndoController {
1036
1059
  await this.dependencies.journal.markCommitted(descriptor.opId);
1037
1060
  });
1038
1061
  this.lastSafetyManifestId = rollback.manifestId;
1039
- this.lastAppliedTargetManifest = target;
1040
- this.lastAppliedTargetAt = performance.now();
1062
+ if (checkpoint.changedPaths.length > 0) {
1063
+ this.lastAppliedTargetManifest = target;
1064
+ this.lastAppliedTargetAt = performance.now();
1065
+ }
1041
1066
  return done(this.advanceHistory(action, checkpoint, { code: "ok", changedFiles: applied.verifiedPaths }));
1042
1067
  } catch (error) {
1043
1068
  if (this.recordUnsafeExit(error)) return done(this.recoveryResult());
@@ -1216,10 +1241,9 @@ export class UndoControllerImpl implements UndoController {
1216
1241
  }
1217
1242
  }
1218
1243
 
1219
- private async captureWithWorkspaceLock(): Promise<SnapshotManifest> {
1220
- // 预热可能仍持有 workspace lock:先等它完成再 acquire,避免排队超时;
1221
- // 此时进程内缓存已暖,本次 capture 只需指纹校验。
1222
- const warmUp = this.warmUpInFlight;
1244
+ private async captureWithWorkspaceLock(skipWarmUpWait = false): Promise<SnapshotManifest> {
1245
+ // 预热任务本身不能等待 warmUpInFlight,否则会等待自己的 Promise。
1246
+ const warmUp = skipWarmUpWait ? undefined : this.warmUpInFlight;
1223
1247
  if (warmUp !== undefined) await warmUp;
1224
1248
  const lease = await this.dependencies.acquireWorkspaceLock();
1225
1249
  try {
@@ -1236,6 +1260,7 @@ export class UndoControllerImpl implements UndoController {
1236
1260
  baseline: SnapshotManifest,
1237
1261
  onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
1238
1262
  onTiming?: (phase: string, durationMs: number) => void,
1263
+ options: CaptureBaselineOptions = {},
1239
1264
  ): Promise<SnapshotManifest> {
1240
1265
  const captureBaseline = this.dependencies.captureBaseline;
1241
1266
  if (captureBaseline === undefined) return this.captureWithWorkspaceLock();
@@ -1248,7 +1273,7 @@ export class UndoControllerImpl implements UndoController {
1248
1273
  }
1249
1274
  const captureStartedAt = performance.now();
1250
1275
  try {
1251
- return await captureBaseline(baseline, onDiagnostics, onTiming);
1276
+ return await captureBaseline(baseline, onDiagnostics, onTiming, options);
1252
1277
  } catch (error) {
1253
1278
  this.recordUnsafeExit(error);
1254
1279
  throw error;
@@ -1267,16 +1292,17 @@ export class UndoControllerImpl implements UndoController {
1267
1292
  baseline: SnapshotManifest,
1268
1293
  onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
1269
1294
  onTiming?: (phase: string, durationMs: number) => void,
1295
+ options: CaptureBaselineOptions = {},
1270
1296
  ): Promise<SnapshotManifest> {
1271
1297
  try {
1272
- return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1298
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming, options);
1273
1299
  } catch (error) {
1274
1300
  rethrowOperationFailure(error);
1275
1301
  if (!isTransientCaptureFailure(error)) throw error;
1276
1302
  const retryStartedAt = performance.now();
1277
1303
  await sleep(250);
1278
1304
  onTiming?.("settled.captureRetryDelay", performance.now() - retryStartedAt);
1279
- return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1305
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming, options);
1280
1306
  }
1281
1307
  }
1282
1308
 
@@ -1540,6 +1566,10 @@ function isTransientCaptureFailure(error: unknown): boolean {
1540
1566
  (name === "WorkspaceLockError" && code === "lock_timeout");
1541
1567
  }
1542
1568
 
1569
+ function yieldToEventLoop(): Promise<void> {
1570
+ return new Promise((resolve) => setImmediate(resolve));
1571
+ }
1572
+
1543
1573
  function sleep(ms: number): Promise<void> {
1544
1574
  return new Promise((resolve) => setTimeout(resolve, ms));
1545
1575
  }
@@ -34,6 +34,12 @@ export interface DurablePackInput {
34
34
  readonly opId: string;
35
35
  readonly planDigest: string;
36
36
  readonly entries: readonly DurablePackEntryInput[];
37
+ /**
38
+ * "transfer" 表示调用方放弃 `variants[].bytes` 的所有权(通常是刚从 store 读出的
39
+ * 独占 buffer);pack 直接引用这些 buffer,不再复制一份完整 payload。
40
+ * 默认 "copy" 保留对调用方之后改写输入的隔离。
41
+ */
42
+ readonly payloadOwnership?: "copy" | "transfer";
37
43
  }
38
44
 
39
45
  export interface DurablePackPreparationOptions {
@@ -170,7 +176,7 @@ export async function createDurablePack(
170
176
  const planDigest = input.planDigest;
171
177
  if (opId !== journal.operationId) throw new Error("durable pack opId 与 mutation journal 不匹配");
172
178
  assertDigest(planDigest, "planDigest");
173
- const entries = canonicalEntries(input.entries);
179
+ const entries = canonicalEntries(input.entries, true, input.payloadOwnership ?? "copy");
174
180
  reportDurablePackTiming(options, "pack.validate", validationStarted);
175
181
  const encodingStarted = performance.now();
176
182
  const payloads: Buffer[] = [];
@@ -218,10 +224,13 @@ export async function createDurablePack(
218
224
  reportDurablePackTiming(options, "pack.encode", encodingStarted);
219
225
  let writeCalls = 0;
220
226
  let handle;
227
+ // 写入时同步累积 pack checksum:writeAll 按实际写出的顺序哈希全部 buffer,
228
+ // 发布后不再完整遍历一遍 payload。
229
+ const digest = createHash("sha256");
221
230
  try {
222
231
  const writeStarted = performance.now();
223
232
  handle = await open(temporary, "wx", 0o600);
224
- writeCalls = await writeAll(handle, [MAGIC, lengthBytes, headerBytes, ...payloads]);
233
+ writeCalls = await writeAll(handle, [MAGIC, lengthBytes, headerBytes, ...payloads], digest);
225
234
  reportDurablePackTiming(options, "pack.write", writeStarted);
226
235
  checkOperation();
227
236
  const syncStarted = performance.now();
@@ -240,11 +249,6 @@ export async function createDurablePack(
240
249
  throw error;
241
250
  }
242
251
  const checksumStarted = performance.now();
243
- const digest = createHash("sha256");
244
- digest.update(MAGIC);
245
- digest.update(lengthBytes);
246
- digest.update(headerBytes);
247
- for (const payload of payloads) digest.update(payload);
248
252
  const packChecksum = digest.digest("hex");
249
253
  reportDurablePackTiming(options, "pack.checksum", checksumStarted);
250
254
  const residentStarted = performance.now();
@@ -303,11 +307,13 @@ export async function loadDurablePack(
303
307
  if (start < payloadStart || end > bytes.length) throw new Error("durable pack payload 越界");
304
308
  const content = bytes.subarray(start, end);
305
309
  if (checksum(content) !== variant.dataChecksum) throw new Error("durable pack payload checksum 不匹配");
310
+ // payload 共享同一次 readFile 的 buffer;`leaf()` 返回时再复制,
311
+ // 避免为每个 variant 额外保留一份完整 payload。
306
312
  leaf = {
307
313
  kind: "file",
308
314
  fingerprint: variant.fingerprint,
309
315
  mode: variant.mode!,
310
- bytes: new Uint8Array(content),
316
+ bytes: content,
311
317
  };
312
318
  }
313
319
  const semanticFingerprint = leaf.kind === "absent"
@@ -490,6 +496,7 @@ async function assertSameFileIdentity(original: string, artifact: string, logica
490
496
  function canonicalEntries(
491
497
  entries: readonly DurablePackEntryInput[],
492
498
  validateSemanticFingerprints = true,
499
+ payloadOwnership: "copy" | "transfer" = "copy",
493
500
  ): DurablePackEntryInput[] {
494
501
  const sorted = [...entries].sort((left, right) => left.path.localeCompare(right.path));
495
502
  let previous: string | undefined;
@@ -503,8 +510,9 @@ function canonicalEntries(
503
510
  if (entry.targetArtifact !== null) assertArtifact(entry.path, entry.targetArtifact, "target");
504
511
  assertDigest(entry.sourceFingerprint, "sourceFingerprint");
505
512
  if (entry.targetFingerprint !== null) assertDigest(entry.targetFingerprint, "targetFingerprint");
506
- // 在校验及任何回调、await 之前取得所有权;调用方之后改写输入不影响 pack。
507
- const variants = entry.variants.map((variant): DurableLeafInput => variant.kind === "file"
513
+ // 默认在校验及任何回调、await 之前复制 payload;调用方之后改写输入不影响 pack。
514
+ // "transfer" 只用于内部刚读出的独占 buffer,避免再复制一份完整 payload。
515
+ const variants = entry.variants.map((variant): DurableLeafInput => variant.kind === "file" && payloadOwnership === "copy"
508
516
  ? { ...variant, bytes: new Uint8Array(variant.bytes) }
509
517
  : { ...variant }).sort((left, right) => left.fingerprint.localeCompare(right.fingerprint));
510
518
  const fingerprints = new Set<string>();
@@ -626,7 +634,11 @@ function durablePackFromOwnedEntries(
626
634
  );
627
635
  }
628
636
 
629
- async function writeAll(handle: FileHandle, buffers: readonly Uint8Array[]): Promise<number> {
637
+ async function writeAll(
638
+ handle: FileHandle,
639
+ buffers: readonly Uint8Array[],
640
+ digest?: ReturnType<typeof createHash>,
641
+ ): Promise<number> {
630
642
  let calls = 0;
631
643
  let batch: Uint8Array[] = [];
632
644
  let batchBytes = 0;
@@ -642,12 +654,15 @@ async function writeAll(handle: FileHandle, buffers: readonly Uint8Array[]): Pro
642
654
  }
643
655
  remainingBytes -= bytesWritten;
644
656
  // 短写可能停在任意 buffer 内,也可能跨过多个 buffer。
657
+ // digest 只累积实际写出的字节,顺序与文件内容一致。
645
658
  let consumed = bytesWritten;
646
659
  let index = 0;
647
660
  while (index < remaining.length && consumed >= remaining[index]!.byteLength) {
661
+ digest?.update(remaining[index]!);
648
662
  consumed -= remaining[index]!.byteLength;
649
663
  index += 1;
650
664
  }
665
+ if (consumed > 0) digest?.update(remaining[index]!.subarray(0, consumed));
651
666
  remaining = remaining.slice(index);
652
667
  if (consumed > 0) remaining[0] = remaining[0]!.subarray(consumed);
653
668
  }
@@ -52,7 +52,11 @@ export class NativeDirectoryScanner implements NativeDirectoryScanPort {
52
52
  private readonly executable: string | undefined;
53
53
  private capabilities: Promise<ReadonlySet<string>> | undefined;
54
54
  private cacheDirectory: Promise<string> | undefined;
55
- private resident: { readonly workspaceRoot: string; readonly client: ResidentScanClient } | undefined;
55
+ private resident: {
56
+ readonly workspaceRoot: string;
57
+ readonly cachePath: string | undefined;
58
+ readonly client: ResidentScanClient;
59
+ } | undefined;
56
60
  private prewarmInFlight: { readonly workspaceRoot: string; readonly promise: Promise<void> } | undefined;
57
61
 
58
62
  constructor(executable = nativeExecutable()) {
@@ -86,23 +90,29 @@ export class NativeDirectoryScanner implements NativeDirectoryScanPort {
86
90
  try {
87
91
  const capabilities = await this.probeCapabilities(requestDirectory);
88
92
  if (!capabilities.has("scan-serve-v1")) return;
89
- const client = this.ensureResident(workspaceRoot);
93
+ const cachePath = capabilities.has("scan-serve-cache-v1")
94
+ ? await this.directoryCachePath(workspaceRoot, temporaryRoot, requestDirectory)
95
+ : undefined;
96
+ const client = this.ensureResident(workspaceRoot, cachePath);
90
97
  if (client !== undefined) await client.prewarm();
91
98
  } finally {
92
99
  await rm(requestDirectory, { recursive: true, force: true }).catch(() => {});
93
100
  }
94
101
  }
95
102
 
96
- private ensureResident(workspaceRoot: string): ResidentScanClient | undefined {
103
+ private ensureResident(workspaceRoot: string, cachePath: string | undefined): ResidentScanClient | undefined {
97
104
  if (this.executable === undefined) return undefined;
98
- if (this.resident?.workspaceRoot === workspaceRoot) return this.resident.client;
105
+ if (this.resident?.workspaceRoot === workspaceRoot && this.resident.cachePath === cachePath) {
106
+ return this.resident.client;
107
+ }
99
108
  if (this.resident !== undefined) void this.resident.client.close();
100
109
  const client = new ResidentScanClient(
101
110
  this.executable,
102
111
  workspaceRoot,
103
112
  configuredTimeout("PI_UNDO_OPERATION_TIMEOUT_MS", 300_000),
113
+ cachePath,
104
114
  );
105
- this.resident = { workspaceRoot, client };
115
+ this.resident = { workspaceRoot, cachePath, client };
106
116
  return client;
107
117
  }
108
118
 
@@ -122,8 +132,11 @@ export class NativeDirectoryScanner implements NativeDirectoryScanPort {
122
132
  : capabilities.has("scan-directories-v1") ? "v1" : undefined;
123
133
  if (version === undefined) return undefined;
124
134
 
135
+ // 旧 helper 不认识握手里的 cachePath(deny_unknown_fields);能力未声明时不发送。
136
+ const cachePath = version === "v2" && capabilities.has("scan-serve-cache-v1")
137
+ ? await this.directoryCachePath(workspaceRoot, temporaryRoot, requestDirectory) : undefined;
125
138
  if (capabilities.has("scan-serve-v1")) {
126
- const client = this.ensureResident(workspaceRoot);
139
+ const client = this.ensureResident(workspaceRoot, cachePath);
127
140
  if (client !== undefined) {
128
141
  const response = await client.scan();
129
142
  checkOperation();
@@ -138,8 +151,6 @@ export class NativeDirectoryScanner implements NativeDirectoryScanPort {
138
151
 
139
152
  const budget = operationProcessOptions(configuredTimeout("PI_UNDO_OPERATION_TIMEOUT_MS", 300_000));
140
153
  const requestPath = join(requestDirectory, "request.json");
141
- const cachePath = version === "v2"
142
- ? await this.directoryCachePath(workspaceRoot, temporaryRoot, requestDirectory) : undefined;
143
154
  await writeFile(requestPath, JSON.stringify({
144
155
  schemaVersion: version === "v2" ? 2 : 1,
145
156
  workspaceRoot,