Skip to content

Runtime tool-surface toggling (context_pivot, background lifecycle tools) breaks the prompt prefix cache on models without mid-conversation tool support #644

Closed as not planned

Description

@cuipengcx90

Environment

  • @earendil-works/pi-coding-agent 0.99.2 for all measurements below; I upgraded to 1.0.0 afterwards and diffed the code involved (pi-ai utils/transcript.js and api/openai-completions.js, extensions/runner.js): identical, so the mechanism is unchanged in 1.0.0. I did not re-run the session statistics on 1.0.0.
  • @tt-a1i/openpi 0.9.0, capabilities.discovery: "adaptive"
  • Model: DeepSeek deepseek-flash through the openai-completions API (official endpoint). Most traffic in the data below is this model.
  • Unrelated extensions installed (memory plugin, cache optimizer, MCP); see "Is OpenPI alone enough to reproduce it?" below.

Symptom

OpenPI adds and removes model tools while a session is running. On a model whose compat does not support in-place tool additions, every such change changes the top-level tools array that is sent to the provider. tools sits at the very front of the cached prefix, so the whole conversation is re-billed as uncached input for that request, and the request after it.

Measured over 2026-09-29 to 2026-10-01 (local time, UTC+08:00), 4,442 deepseek-flash requests across 133 session files:

Item Value
Requests that directly follow a system or tool change 147 (3.4% of requests)
Uncached input tokens in those requests about 21.8M, roughly equal to the other 4,273 requests combined
Cache hit rate of the request after a change 22% to 35% per day (overall daily hit rate stays 93% to 98%, which hides it)
Extra spend of those requests, priced as if their uncached input had been cache hits about $6.3 for the 147 requests, of $26.80 total spend over the three days. This also includes system-section changes from a separate memory plugin, so it is not all attributable to OpenPI; the OpenPI tool toggles alone account for roughly $3.5 (breakdown below)

Session forensics on first requests of a run (353 runs, excluding compaction):

Previous run contained a tool-set change Runs First request hit rate below 50%
No (and no system change at run start) 226 2%
Yes (and no system change at run start) 57 67%

Among the 47 requests that missed with no system change recorded and no model switch, 35 (69% of their uncached tokens) were runs whose previous run had a tool-set change. A tool change makes two consecutive request heads miss (the change run and the next one), the third recovers.

Which toggles

From ~/.pi/agent/sessions/*.jsonl system messages (toolsAdded / toolsRemoved), 09-29 to 10-01:

Toggle Source Observed
context_pivot added/removed as context crosses 30k extensions/context-pivot/index.ts setVisibleForContext, called on every agent_start 88 add/remove events, 0 calls to the tool in the same period
bg_status / bg_list / bg_kill / bg_watch hidden at every session_start, shown again after bg_start extensions/background-terminals/index.ts lines 305 and 431 19 adds and 19 removes, bg_start called 73 times in 9 sessions
Capability groups (fd/rg/git_*, subagents, workflows, goal/tasks) loaded by prompt intent extensions/capabilities, shared/capability-intent.ts a few per day; documented as session-stable once loaded

Cost of the next request only (deepseek, difference between uncached and cached input price): context_pivot toggles about $0.80, background lifecycle toggles about $2.70, over three days. The second miss request is not included.

Why only some models are affected

Pi preserves the cache across tool changes only where the model API can express additions in place (Pi 0.80.7 changelog: "supported Anthropic and OpenAI Responses models"; Pi 0.99 resolveTranscriptTools: additions are anchored only when supportsToolAdditions is true and no tool was removed or redefined). Otherwise resolveTranscriptTools returns the current full tool set as the top-level tools field.

I confirmed this at the request-body level with Pi 0.99.2's own openai-completions builder against a local capture server (no provider call). Two consecutive requests of one session, the second preceded by a later system message:

Change in the second request Leading messages identical to first request Top-level tools identical
text section update, model without supportsMidConvoSystemMessages 0 of 2 yes
text section update, model with supportsMidConvoSystemMessages: true 2 of 2 yes
one tool added, either setting 2 of 2 no

So supportsMidConvoSystemMessages fixes text-section changes but cannot fix tool-set changes on openai-completions. Anything that toggles tools at runtime breaks the prefix there, and supportsMidConvoToolAdditions (Kimi-style tools system messages) is not something DeepSeek's official API is known to support.

Is OpenPI alone enough to reproduce it?

Based on source reading, not on an isolated run: yes, the toggling is internal to OpenPI. context-pivot, background-terminals and capabilities call patchOwnedTools / setActiveTools on their own events, with no dependency on other extensions. The severity depends on the model path, not on which other plugins are installed. On Anthropic Messages or OpenAI Responses models with the matching compat flags the same toggles are cache-neutral.

What I did not do: run OpenPI in a clean agent directory with no other package. Other installed extensions (a memory plugin that rewrites a system section every turn, a cache optimizer) change the system section and are a separate, additive cause; they are not needed to see the tool-driven misses described above.

Is it new in Pi 0.99?

I do not think so, with one caveat.

  • The mechanism that stores system and tool changes as in-session messages and folds them for models without support arrived in Pi 0.86.0 (2026-09-19), not 0.99.
  • Tool-change events per session, same machine, by day: 09-28 1.00, 09-29 1.00, 09-30 1.09, 10-01 1.26. Per 1,000 requests: 16.8, 21.7, 31.8, 34.0. The per-session rate is roughly flat while overall volume grew, so the increase is usage, not a regression at 0.99.
  • Sessions older than 2026-09-27 are gone from this machine, so I cannot compare with Pi before 0.86.0 or OpenPI before 0.9.0.

Suggested changes

  1. Keep the model-visible tool set stable for the life of a session once a capability is loaded. For background terminals, do not hide bg_status / bg_list / bg_kill / bg_watch at session_start; expose them together with bg_start when the capability loads, so there is one change per session, not one per start/stop cycle.
  2. Do not toggle context_pivot by token threshold on every agent_start. Either keep it registered for the whole session, or let the threshold gate the tool's execution (it already rejects calls below 30k tokens) instead of its presence in the tool list.
  3. Consider a setting for "stable tool surface" that loads every enabled group's tools up front for models that report no in-place tool addition support, trading a larger but constant tool block for a cacheable prefix.
  4. Document the constraint next to "Capability discovery": the zero-resident design is cache-neutral only on Anthropic Messages and OpenAI Responses with the matching compat flags.

Related issues

Verification offered

The capture script (about 40 lines, uses @earendil-works/pi-ai's streamSimple against http.createServer and compares messages and tools of consecutive request bodies) and the per-session counting script are available if useful.

Activity

  1. cuipengcx90 commented on Oct 2, 2026

    @cuipengcx90
    ContributorAuthor

    Closing this one: after filing it I ran a follow-up test and the central claim does not hold.

    Real-flow check (Pi 1.0.0, OpenPI 0.9.0, DeepSeek deepseek-flash via openai-completions, three sessions of five turns, one turn triggering the background-terminal capability so that bg_* and fd/rg/git_* were added/removed): the request after each tool addition or removal still hit the prefix cache at 90% to 100%. So on this provider the runtime tool toggling does not break the cache, which is what the issue title asserted.

    What I got wrong: the session statistics in the issue (low hit rate after "tool changes") were a correlation. In those sessions the rules and tools system sections changed together with the tool set, and with a custom provider that does not declare supportsMidConvoSystemMessages, Pi folds such section changes into the leading system message. That folding, not the tool toggling, is the more likely cause. I did not verify the tool-array part separately beyond the test above.

    Apologies for the noise; nothing needs to change in OpenPI for this.

  2. outlier27-cell commented on Oct 2, 2026

    @outlier27-cell
    Contributor

    我希望承担此 Issue 的调查与修复。先在最新 main、隔离的 OpenPI 环境中复现动态工具显隐造成的请求前缀变化,再确定最小修复范围并补充回归测试。保留现有权限与能力发现边界,不预先承诺费用或性能改善。若已有同范围的工作,请告知以避免重复。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions