pi-cache-optimizer 2.9.3 → 2.10.0

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
@@ -19,6 +19,7 @@ Pi extension for improving provider-side KV / prompt cache hit rates. It keeps s
19
19
  - [Persistent opt-out](#persistent-opt-out)
20
20
  - [Per-model `prompt_cache_key` opt-out](#per-model-prompt_cache_key-opt-out)
21
21
  - [Opt-in deterministic tool ordering](#opt-in-deterministic-tool-ordering)
22
+ - [Footer refresh (2.10)](#footer-refresh-210)
22
23
  - [Footer cache stats mode](#footer-cache-stats-mode)
23
24
  - [OpenAI-compatible proxy setup](#openai-compatible-proxy-setup)
24
25
  - [Prompt cache warming (Pi 0.86+)](#prompt-cache-warming-pi-086)
@@ -100,6 +101,9 @@ Doctor displays endpoint URLs without username/password, query parameters, or fr
100
101
  | `PI_CACHE_OPTIMIZER_NO_SKILL_COMPRESSION=1` | Keep Pi's verbose skill XML. |
101
102
  | `PI_CACHE_OPTIMIZER_NO_OPENAI_CACHE_KEY=1` | Disable the OpenAI-compatible `prompt_cache_key` fallback. Preferred explicit opt-out. |
102
103
  | `PI_CACHE_OPTIMIZER_OPENAI_CACHE_KEY=0` | Disable the same fallback via the legacy inverse switch. Values `0`, `false`, `no`, or `off` disable it. |
104
+ | `PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0` | Kill switch for the incremental footer refresh (see [Footer refresh](#footer-refresh-210)): every refresh stats every shard file again, as in 2.9.3. Values `0`, `false`, `no`, or `off` disable it. |
105
+ | `PI_CACHE_OPTIMIZER_STATS_TIMING=1` | Opt-in footer refresh timing log (JSON lines in `pi-cache-optimizer-stats-timing.jsonl` under the agent directory; an absolute path instead writes there). Off by default. |
106
+ | `PI_CACHE_OPTIMIZER_STATS_VERIFY=1` | Opt-in check, after each background full scan, that no shard file changed while its identity (inode, size, timestamps) stayed the same, which filesystems without inodes and with coarse timestamps (FAT, some SMB servers) can do. Such files are re-read; a warning suggests the kill switch once it happened twice. Off by default. |
103
107
 
104
108
  Persistent feature settings are managed under the Pi agent directory by the native command interface. They take precedence over their corresponding environment variables, including both OpenAI cache-key switches above. Runtime `disable` still suppresses optimization regardless of persistent settings:
105
109
 
@@ -109,6 +113,7 @@ Persistent feature settings are managed under the Pi agent directory by the nati
109
113
  /cache-optimizer config skill-compression on|off
110
114
  /cache-optimizer config openai-cache-key on|off
111
115
  /cache-optimizer config tool-order on|off
116
+ /cache-optimizer config stats-incremental on|off
112
117
  /cache-optimizer config footer-mode total|session|process
113
118
  /cache-optimizer config reset
114
119
  ```
@@ -133,6 +138,19 @@ bun .trellis/tasks/09-03-context-epoch-tool-ordering/verify.ts
133
138
 
134
139
  The fixture verifier reports numeric tool-order changes and confirms cache-marked payloads remain unchanged. Because it does not contact a provider, provider cache usage is explicitly unavailable and no synthetic cache hit is claimed.
135
140
 
141
+ ## Footer refresh (2.10)
142
+
143
+ Before 2.10 every footer refresh stat-ed every raw shard file (about 400 on a busy day), and Pi waited for it after every tool call, every assistant message and every settle; on Windows, where antivirus scanning makes each file stat expensive, that was about 28 ms per refresh on the agent loop's critical path. Since 2.10:
144
+
145
+ - **Pi no longer waits.** The refreshes after `tool_execution_end`, `agent_settled` and `message_end` run in the background (usage is still recorded synchronously in memory first). At most one refresh runs at a time; requests made meanwhile share one follow-up refresh that starts after it, so a result is never older than the request. Commands (`stats`, `doctor`, `reset`...), `session_shutdown` and model selection still wait for a fresh refresh, and the shutdown waits for background refreshes in flight before its final write, so print mode never exits mid-refresh.
146
+ - **Fewer file operations.** Each refresh lists the shard directory (new and deleted shards are seen immediately) and stats only new files and the *hot* set: active shards, shards updated within the last 15 minutes, and files the TUI watcher reported as changed. A file is read again only when it changed. This process's own shard is never read back (its in-memory copy is newer). On the benchmark fixture (about 400 raw shards, 0.2 ms per file operation), a refresh went from about 410 file operations and 29 ms to about 18 (2 listings, stats of the 10 active shards, 6 epoch reads) and under 3 ms.
147
+ - **Staleness bound.** A closed shard is rewritten only by the process that owns it, when it starts another session under the same shard (Pi keeps the extension across `/new`, `/resume` and fork: the shutdown closes the shard, the next session writes it active again). That is covered by the 15-minute window when it happens soon; closed shards older than that are re-checked by a background full scan at most every 30 seconds while refreshes happen (two file operations in flight at a time). So a change to such a file, including that late re-activation, shows in the footer after at most about 30 seconds plus the scan time. Active and recently updated shards (every live process's), new and deleted shards, reset epochs and this process's own usage are never stale. Commands and the shutdown flush always stat every file.
148
+ - **Same numbers.** The cached shards are re-aggregated in full on every refresh with the same aggregation as before, so the totals equal a full scan of the same files exactly. Reset epochs are read once per refresh, in parallel, and a slow read can no longer roll a newer epoch back. A Windows read error on an epoch file (`EPERM`/`EBUSY` while another process resets) no longer counts as "no reset ever happened"; before 2.10 it could clear this process's unsaved usage. The on-disk format, file names and write protocol are unchanged, so 2.8.x/2.9.x processes can share the directory.
149
+ - **Archive.** A new archive generation is parsed once as before; reducing it for the footer now only covers the current session (no per-bucket key strings), about a quarter less main-thread time on a 2 MB archive (the JSON parse itself remains). An unchanged generation is confirmed by the directory listing alone, and its file identity is still checked on every command and flush and at least every 30 seconds (a generation number is reused if the archive directory is deleted and rebuilt). 2.9.0's `archive.json`, a generation still being written in place, and an unreadable newest generation are still checked on every refresh, exactly as before.
150
+ - **Watcher.** The TUI shard watcher now has an `error` listener (on Windows, deleting the watched directory made Pi crash), is created after the background restore (it was missing for the whole process when the directory did not exist yet at startup), only marks changed files for the next refresh, ignores this process's own writes, and is closed at shutdown and reload.
151
+
152
+ Kill switch: `/cache-optimizer config stats-incremental off` or `PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0` makes every refresh stat every shard file again (the background refresh and the other fixes stay); the persisted setting wins over the environment, like every feature setting. Note: versions before 2.10 do not know this config key and ignore the whole config file (falling back to their defaults) while it is set, so if you run an older version against the same agent directory, prefer the environment variable. `PI_CACHE_OPTIMIZER_STATS_TIMING=1` logs per-refresh phase timings, the hot-set size and file counts; `PI_CACHE_OPTIMIZER_STATS_VERIFY=1` checks that the file identities the refresh relies on are trustworthy on your filesystem.
153
+
136
154
  ## Footer cache stats mode
137
155
 
138
156
  Current versions store stats under `pi-cache-optimizer-stats.d/shards/` in Pi's agent directory. Each loaded extension instance owns one active UUID-named daily shard and writes it through temp-file + atomic rename; at local midnight it closes the old shard and starts a new UUID without erasing session history. This prevents parent/child/parallel Pi processes from overwriting one another. Upgrading from the old v6 single-file format deletes the old local stats files and starts footer counters from zero; upstream provider caches are not affected.
package/README.zh-CN.md CHANGED
@@ -19,6 +19,7 @@
19
19
  - [持久 Opt-out](#持久-opt-out)
20
20
  - [按模型关闭 `prompt_cache_key`](#按模型关闭-prompt_cache_key)
21
21
  - [Opt-in 确定性工具排序](#opt-in-确定性工具排序)
22
+ - [Footer 刷新(2.10)](#footer-刷新210)
22
23
  - [Footer 缓存统计模式](#footer-缓存统计模式)
23
24
  - [OpenAI-compatible 代理配置](#openai-compatible-代理配置)
24
25
  - [Prompt cache 保温(Pi 0.86+)](#prompt-cache-保温pi-086)
@@ -100,6 +101,9 @@ Doctor 显示的 endpoint URL 会移除用户名/密码、查询参数和 fragme
100
101
  | `PI_CACHE_OPTIMIZER_NO_SKILL_COMPRESSION=1` | 保留 Pi 原始 verbose skill XML。 |
101
102
  | `PI_CACHE_OPTIMIZER_NO_OPENAI_CACHE_KEY=1` | 关闭 OpenAI-compatible `prompt_cache_key` fallback。推荐使用这个显式 opt-out。 |
102
103
  | `PI_CACHE_OPTIMIZER_OPENAI_CACHE_KEY=0` | 通过旧的反向开关关闭同一个 fallback。取值 `0`、`false`、`no`、`off` 时关闭。 |
104
+ | `PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0` | 增量 footer 刷新的 kill switch(见 [Footer 刷新(2.10)](#footer-刷新210)):每次刷新重新 stat 全部 shard 文件,与 2.9.3 相同。取值 `0`、`false`、`no`、`off` 时关闭。 |
105
+ | `PI_CACHE_OPTIMIZER_STATS_TIMING=1` | 开启 footer 刷新计时日志(JSON lines,写到 agent 目录下的 `pi-cache-optimizer-stats-timing.jsonl`;取值为绝对路径时写到该路径)。默认关闭。 |
106
+ | `PI_CACHE_OPTIMIZER_STATS_VERIFY=1` | 开启校验:每次后台全扫之后,检查有没有 shard 文件内容变了、文件身份(inode、大小、时间戳)却没变。没有 inode、时间戳精度又粗的文件系统(FAT、部分 SMB 服务器)会出现这种情况。发现的文件会被重新读取;出现两次后提示一次改用 kill switch。默认关闭。 |
103
107
 
104
108
  持久化 feature 配置由 Pi agent 目录中的原生命令管理,并且优先于对应环境变量,包括上面的两个 OpenAI cache-key 开关。运行时 `disable` 仍会抑制优化,不受持久配置影响:
105
109
 
@@ -109,6 +113,7 @@ Doctor 显示的 endpoint URL 会移除用户名/密码、查询参数和 fragme
109
113
  /cache-optimizer config skill-compression on|off
110
114
  /cache-optimizer config openai-cache-key on|off
111
115
  /cache-optimizer config tool-order on|off
116
+ /cache-optimizer config stats-incremental on|off
112
117
  /cache-optimizer config footer-mode total|session|process
113
118
  /cache-optimizer config reset
114
119
  ```
@@ -133,6 +138,19 @@ bun .trellis/tasks/09-03-context-epoch-tool-ordering/verify.ts
133
138
 
134
139
  该 verifier 只报告数字形式的工具排序变化,并确认带 cache marker 的 payload 不会变化。由于它不会连接 provider,provider cache usage 会明确报告为 unavailable,也不会虚构 cache hit。
135
140
 
141
+ ## Footer 刷新(2.10)
142
+
143
+ 2.10 之前,每次 footer 刷新都要 stat 每一个原始 shard 文件(忙碌的一天约 400 个),而且 Pi 在每次工具调用、每条 assistant 消息和每次 settle 之后都要等它完成。在 Windows 上,杀毒软件扫描让每次 stat 都很贵,一次刷新约 28 ms,直接压在 agent 循环的关键路径上。自 2.10 起:
144
+
145
+ - **Pi 不再等待。** `tool_execution_end`、`agent_settled`、`message_end` 之后的刷新改在后台进行(用量仍先同步记入内存)。同一时刻最多只有一个刷新在跑;期间到来的请求共享一个在它之后开始的后续刷新,所以拿到的结果不会早于请求时刻。命令(`stats`、`doctor`、`reset` 等)、`session_shutdown` 和切换模型仍然等待一次新鲜的刷新;shutdown 会先等后台刷新结束再做最后一次写入,所以 print 模式不会在刷新中途退出。
146
+ - **文件操作更少。** 每次刷新列一次 shard 目录(新增和删除的 shard 立刻可见),只 stat 新文件和"热"集合:active shard、最近 15 分钟内更新过的 shard,以及 TUI watcher 报告有变化的文件。文件只有变了才重新读取。本进程自己的 shard 从不读回(内存里的副本更新)。在基准夹具上(约 400 个原始 shard,每次文件操作 0.2 ms),一次刷新从约 410 次文件操作、29 ms 降到约 18 次(2 次列目录、10 个 active shard 的 stat、6 次 epoch 读取)、3 ms 以内。
147
+ - **陈旧上限。** 已关闭的 shard 只会被它所属的进程改写:该进程用同一个 shard 开始另一个 session 时(Pi 在 `/new`、`/resume`、fork 之间沿用同一个 extension:shutdown 把 shard 关闭,下一个 session 又把它写回 active)。如果很快发生,15 分钟窗口能覆盖;关闭超过 15 分钟的 shard 只在有刷新发生时由后台全扫复查,最多每 30 秒一次(同时最多 2 个文件操作)。所以这类文件的变化(包括这种较晚的重新激活)最迟约 30 秒加一次全扫的时间后反映到 footer。active 和最近更新的 shard(所有活着的进程的)、新增和删除的 shard、reset epoch 以及本进程自己的用量都不会陈旧。命令和 shutdown 的 flush 始终 stat 全部文件。
148
+ - **数字不变。** 每次刷新都用与以前相同的聚合,对缓存的 shard 做完整的重新聚合,所以总数与对同一批文件做全量扫描完全相同。reset epoch 每次刷新并行读取一次,慢的读取不能再把较新的 epoch 改回去。epoch 文件在 Windows 上的读取错误(另一个进程 reset 时的 `EPERM`/`EBUSY`)不再被当作"从未 reset";2.10 之前它可能清掉本进程尚未落盘的用量。磁盘格式、文件名和写入协议都不变,2.8.x/2.9.x 进程可以共用同一目录。
149
+ - **Archive。** 新的 archive generation 仍然只解析一次;为 footer 做的归约现在只覆盖当前 session(不再为每个 bucket 拼接键字符串),2 MB 的 archive 主线程耗时约减少四分之一(JSON 解析本身仍在)。未变化的 generation 只凭目录列表确认,但每次命令和 flush、以及至少每 30 秒仍会核对一次它的文件身份(archive 目录被删除重建时,generation 编号会被重复使用)。2.9.0 的 `archive.json`、仍在原地写入的 generation 和不可读的最新 generation,照旧每次刷新都核对。
150
+ - **Watcher。** TUI 的 shard watcher 现在有 `error` 监听(Windows 上删除被监视的目录曾让 Pi 崩溃),在后台 restore 之后才创建(以前启动时目录还不存在,整个进程都没有 watcher),只把变化的文件标记给下一次刷新,忽略本进程自己的写入,并在 shutdown 和 reload 时关闭。
151
+
152
+ Kill switch:`/cache-optimizer config stats-incremental off` 或 `PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0` 让每次刷新重新 stat 全部 shard 文件(后台刷新和其他修复保留);和其他功能设置一样,持久化配置优先于环境变量。注意:2.10 之前的版本不认识这个配置键,设置后会忽略整个配置文件(回到默认值),如果同一 agent 目录下还会运行旧版本,请优先使用环境变量。`PI_CACHE_OPTIMIZER_STATS_TIMING=1` 记录每次刷新的分阶段耗时、热集合大小和文件数;`PI_CACHE_OPTIMIZER_STATS_VERIFY=1` 检查刷新所依赖的文件身份在你的文件系统上是否可靠。
153
+
136
154
  ## Footer 缓存统计模式
137
155
 
138
156
  当前版本把统计保存在 Pi agent 目录的 `pi-cache-optimizer-stats.d/shards/` 下。每个已加载的 extension instance 独占一个当天的活跃 UUID shard,并通过临时文件 + 原子 rename 写入;本地日期切换时关闭旧 shard、创建新的 UUID,保留 session 历史,因此父/子/并行 Pi 进程不会互相覆盖。旧 v6 单文件统计在升级时直接删除,本地 footer 计数从零开始;不会影响上游 provider 的实际缓存。