Repository navigation
【中文】Compaction 中两处独立缓存失效(补丁 + 回归测试)— Two independent cache breaks in compaction on master @ 687f282e86: patch and regression specs #10573
Replies: 3 comments
|
Fix for both causes above, as a patch on 🔧 FixEnvelope. Note
Prune order (
Pruning the region saves nothing when a summary runs, because the checkpoint shadows it anyway; the summarizer now also reads full-fidelity tool output. The retained tail is re-prefilled after the checkpoint regardless (its position shifts), so pruning it costs nothing extra. 📊 MeasuredReal agent loop, token meter, pruner and compaction-basic; only the provider is simulated. The simulated cache keys a request family on (provider, model, effort, temperature, stop) and reuses the longest byte prefix of any earlier request in that family;
Each cause in isolation: effort only puts every fold at 0–0.8% on At a 512k prefix on V4-Pro off-peak pricing, one fold goes from about $0.22 to about $0.008. A miss costs 30× (Pro) to 50× (Flash) a cache hit per token, so the gap grows linearly with every token of context. Tip The simulator is a worst case for cause 1: an effort mismatch misses everything, as on @bulhenvaster's server. DeepSeek's own endpoint still served the ~18k static head in @deepseekv41flash's data. Same conclusion: the conversation body misses. ✅ Verification
¹ The structural guard passes on both trees by design; see below. Patch: With the patch the compaction suite is green (236 passed), The window-scaling case, verbatim from the new spec ( it.each([32_000, 128_000, 512_000])('bounds the uncached summary prompt independently of a %i-token window', async (window) => {
const run = await runWorkload({ window, steps: 60, effort: 'max', pruner: 'rewrite-only' })
const summaries = run.cache.compactions()
expect(summaries.length).toBeGreaterThanOrEqual(2)
for (const summary of summaries) {
expect(hitRatio(summary)).toBeGreaterThanOrEqual(0.95)
expect(uncached(summary)).toBeLessThanOrEqual(MAX_UNCACHED_SUMMARY_TOKENS)
}
assertNoSilentRewrite(run)
}, 60_000)
🧭 Scope
📦 Patch and reproduce# save the full patch below as compaction-cache-integrity.patch
git checkout 687f282e86 && git apply compaction-cache-integrity.patch
# a full `pnpm install` currently fails behind proxies on cdn.sheetjs.com;
# the filtered install is enough:
pnpm install --frozen-lockfile --filter "@deepseek-ai/dsh-compaction-basic..." --filter "@deepseek-ai/dsh-compaction-tool-result-pruner..."
npx vitest run packages/compaction/Full patch:
|
|
Both causes still exist on master; the anchors moved. At
So both fixes are still needed, and a blind One part of your note still checks out and matters for the rebase: the summarizer passes Next step: apply the rebased patch on |
Important TL;DR: Both causes are still on Thank you, @PerryLink, for re-checking both causes against 🔍 Both causes are still on
|
| Cause | At fcc0ad46 (your check) |
At 4b399c39a6 |
|
|---|---|---|---|
| 1 | Envelope: the summary call sends no reasoningEffort, temperature or stop |
summarizer.ts:152-162 |
summarizer.ts:150-160 |
| 2 | Prune first: the model-free pass rewrites the surface before the range is chosen | index.ts:344-349 |
index.ts:362-367, range at :372 |
What is new is 9ebb02afb7 (summarize on the model that last answered). summarizeWithLlm now receives the answered route as conversation (summarizer.ts:129, resolved at index.ts:293) and no longer reads the request header. My old summarizer hunk was anchored on that header read, so it stopped applying.
Cause 1. The agent loop spreads the durable header into every request (agent.ts:725-732). The summary call keeps only provider and model, so the DeepSeek adapter falls back to effort high and sends it as thinking plus output_config.effort (serialize.ts:147-156). The summary then belongs to another request family and is prefilled cold.
Cause 2. The base bundle mounts the pruner at 8,192 characters (cordis.patch.yml:446-451). Under pressure it rewrites oversized tool results before the range is chosen, so the summary replays a history that departs from the cached request at the first rewritten result.
A provider prefix cache reuses an earlier request only while the request settings match, and only up to the first byte that differs; everything after that point is computed and billed again.
%%{init: {"flowchart": {"rankSpacing": 28, "nodeSpacing": 24, "padding": 8}}}%%
flowchart TB
subgraph R1 ["① cached: last request"]
direction LR
a1["tools +<br/>system prompt"] --> a2["turns<br/>1 … k"] --> a3["tool result j<br/>original"] --> a4["turns<br/>j+1 … n"] ~~~ a5["summary<br/>instruction"]
end
subgraph R2 ["② cause 1: effort dropped"]
direction LR
b1["tools +<br/>system prompt"] --> b2["turns<br/>1 … k"] --> b3["tool result j<br/>original"] --> b4["turns<br/>j+1 … n"] --> b5["summary<br/>instruction"]
end
subgraph R3 ["③ cause 2: pruned first"]
direction LR
c1["tools +<br/>system prompt"] --> c2["turns<br/>1 … k"] --> c3["tool result j<br/>rewritten"] --> c4["turns<br/>j+1 … n"] --> c5["summary<br/>instruction"]
end
subgraph R4 ["④ patched summary call"]
direction LR
d1["tools +<br/>system prompt"] --> d2["turns<br/>1 … k"] --> d3["tool result j<br/>original"] --> d4["turns<br/>j+1 … n"] --> d5["summary<br/>instruction"]
end
R1 ~~~ R2 ~~~ R3 ~~~ R4
classDef ref fill:#f6f8fa,stroke:#8c959f,color:#1f2328
classDef hit fill:#dafbe1,stroke:#1a7f37,color:#0f3d1c
classDef miss fill:#ffebe9,stroke:#cf222e,color:#6e0b12
classDef fresh fill:#ddf4ff,stroke:#0969da,color:#0a3069
classDef ghost fill:transparent,stroke:transparent,color:transparent
class a1,a2,a3,a4 ref
class b1,b2,b3,b4,c3,c4 miss
class c1,c2,d1,d2,d3,d4 hit
class b5,c5,d5 fresh
class a5 ghost
style R1 fill:transparent,stroke:#8c959f
style R2 fill:transparent,stroke:#8c959f
style R3 fill:transparent,stroke:#8c959f
style R4 fill:transparent,stroke:#8c959f
🟩 served from cache · 🟥 recomputed at full price · 🟦 new input, unavoidable · ⬜ cached by the previous request
On master both rows ② and ③ apply at once: the simulated 128k fold leaves 83,945 tokens uncached, the patched call 469.
🔧 Fix, rebased onto 4b399c39a6
One change per cause, plus one optional field:
- Envelope.
inheritedCallControls()copiesreasoningEffort,temperatureandstopfrom the latest request header, but only when that header names exactly the provider and model the summary will use. Since the target is now the answered route,summarizeWithLlmreads the header for these three fields alone. - Prune order.
planPrune()prices the pass without touching the log. If the pass alone clears the threshold, it lands everywhere, as before. If a summary runs anyway, only the retained tail is pruned and the summarized range replays byte-identical. - Record.
compaction/summarygains an optionalreasoningEffort, so a cold fold can be diagnosed from the log alone. The persistence record issame-version; existing logs and readers stay valid.
Compared with the patch in my first reply, the logic is the same. The rebase adapted three spots: meter.measure() now receives the header (an upstream change before fcc0ad46), summarizeWithLlm reads the header itself (since 9ebb02afb7), and the test fixture now comes from dsh-tool-testkit. New are the seventh spec, the docs in English and Chinese, the regenerated catalogs and a persistence record for the new field.
Note
maxTokens stays out of inheritedCallControls() on purpose, as you noted: the summarizer keeps sending the headroom-derived config.maxTokens (summarizer.ts:156). It caps output and is not part of the cached prompt. Inheriting the adapter default of 256,000 (defaults.ts:10) could push prompt + max_tokens past the window.
📊 Measured
Same simulated-cache harness, now on 4b399c39a6. The simulator in tests/support/prefix-cache.ts keys a request family on provider, model, effort, temperature and stop, reuses the longest byte prefix within that family and counts 4 characters per token. Workload: 60 tool steps, effort max, pruner budgets that rewrite every third result without clearing pressure on their own.
| Window | master: uncached per fold (3 folds) |
With the patch | Hit rate, master → patch |
|---|---|---|---|
| 32,000 | 21,845 / 22,282 / 21,898 | 469 / 470 / 470 | 0.0–0.7 % → 97.9 % |
| 128,000 | 83,945 / 85,282 / 83,998 | 469 / 470 / 470 | 0.0–0.2 % → 99.4–99.5 % |
| 512,000 | 332,345 / 337,282 / 332,398 | 469 / 470 / 470 | 0.0 % → 99.9 % |
The uncached part no longer grows with the window: what remains is the instruction and its framing. The figures match my run on fcc0ad46 token for token, so the rebase changes nothing on this path.
Live summary calls on rc.4. Provider deepseek-official, model deepseek-flash, window 1,048,576 tokens; build A is rc.4 (3f321d32bf), build B is rc.4 plus this change before the rebase. The setup column names the trigger and the routed effort. Each result cell shows hit rate · uncached tokens of the summary call, as the provider reported them on its compaction/summary event; the last column counts tool results rewritten inside the replayed region.
| Run | Setup | A (rc.4) | B (patch) | Rewritten, A / B |
|---|---|---|---|---|
| E1-1 | manual /compact, max |
12.2 % · 63,437 | 99.4 % · 404 | 0 / 0 |
| E1-2 | manual /compact, max |
13.9 % · 54,912 | 99.3 % · 425 | 0 / 0 |
| E2 | pressure + pruner, high |
20.0 % · 71,127 | 99.8 % · 439 | 21 / 0 |
Controls. The last conversation turn before each fold hit 99.6–99.8 % in all four E1 sessions and 96.2 % (A) / 95.6 % (B) in E2. No session left a turn or a compaction open, and none logged a compaction error. The misses in column A therefore come from the summary call itself, not from a cold conversation. With B, every E1 compaction/summary event records reasoningEffort: "max"; A records none.
E2 setup. E2 used retainTokens: 8000 and a threshold derived from the first control turn of each session: system prompt, tools and a one-line control message.
| First control turn | A | B |
|---|---|---|
| Uncached input tokens | 7,931 | 3,196 |
| Tokens read from cache | 8,832 | 13,568 |
| Prompt total | 16,763 | 16,764 |
(16,763 + 30,000) / 1,048,576 = 0.0446, rounded to thresholdRatio: 0.045, so each fold triggers at about 47k tokens, roughly 30k tokens into the conversation. Both sessions start from the same prompt within one token; the split between cached and uncached only reflects what the provider held when each session began.
E2 counts the first fold of each build. Both sessions then ran one smaller follow-up fold (A: 4,421 uncached, 66.6 %; B: 3,690, 70.5 %; no rewritten tool results in either), which the patch does not change and the table leaves out.
Tip
E1 and E2 are split on purpose. E1 has no pruning, so it isolates cause 1; E2 runs the pruner under pressure, so it isolates cause 2. A combined run could not tell which cause costs what.
✅ Verification on 4b399c39a6
| File | On master |
With the patch |
|---|---|---|
compaction-basic/tests/prefix-cache-integrity.spec.ts (new, 7 specs) |
6 failing, 1 passing | 7 passing |
compaction-basic/tests/compaction-basic.spec.ts (1 spec changed) |
1 failing, 129 passing | 130 passing |
packages/compaction/ (14 files) |
7 failing, 257 passing | 264 passing |
What each spec catches on master:
| Spec | Failure on master |
|---|---|
replays the routed reasoning effort in the summary call |
effort high, expected max |
does not rewrite the replayed region with the model-free prune pass |
hit ratio 0.125, expected at least 0.95 |
keeps a second agent in the same context on its own routed effort |
no effort sent, expected low |
bounds the uncached summary prompt … for 32,000, 128,000 and 512,000 tokens |
hit ratio 0 in all three, expected at least 0.95 |
summarizes the byte-identical region and prunes only the retained tail … (changed) |
replay is not a prefix of the routed history |
never breaks the cache without a durable rewrite event |
passes on both: a structural guard by design |
Further checks with the patch:
tsc -bfor the four touched packages (compaction,compaction-tool-result-pruner,compaction-basic,tool-cordis): clean. The new and changed spec files type-check clean undertsconfig.host.json.- oxlint with the repository config (type-aware, 90 rules) on every touched path: 0 warnings, 0 errors.
- Generated files and docs:
verify-cordis-api,verify-cordis-catalog,verify-cordis-inspect-catalog,verify-type-equiv,verify-persistence-catalog,verify-persistence-changesandverify-translation-pairing(1,398 pairs) all exit 0. The catalog and persistence tooling specs report 221 passed, 28 skipped, 0 failed. git apply --checkon a fresh clone at4b399c39a6: clean, no offsets.- The suite, the new specs,
tsc -band the apply check give the same results on macOS, where the repository's pre-push typecheck (pnpm run typecheck) also passed all 5 gates.
Seven specs fail on master (six new, one changed); all pass with the change, and tsc -b is clean.
🧭 Scope
- Overflow recovery still prunes before it summarizes (
index.ts:321): there the summary prompt itself has to fit the window. - No inheritance across routes. When the latest header names a route other than the one that last answered (the overflowed model switch from
9ebb02afb7), the summary call inherits nothing and uses the adapter defaults, exactly as onmaster. - After the checkpoint, the first request still prefills the summary and the retained tail again, because their positions shift. This change does not address that cost.
- Seven specs instead of six. I added
keeps a second agent in the same context on its own routed effort: a second agent in one context (a stand-in for a delegated child) must summarize with its own routed effort, never with the parent's or with none. - Where each number comes from. E1 and E2 ran on rc.4 builds with the pre-rebase version (same logic; it applies to rc.4 with line offsets). I did not repeat them on 0.2.3-alpha.2. Specs, simulator, gates and the apply check ran on
4b399c39a6.
📦 Patch and reproduce
The commit sits directly on master, so it can be picked as it is: 9053ca9bc8 on Trove-design/deepseek-harness · fix/compaction-cache, parent 4b399c39a6. The same change as a plain diff: 9053ca9bc8.diff. No pull request was opened; whether and how to adopt it is up to the maintainers.
| Part | Files | Lines |
|---|---|---|
Source (compaction-basic, compaction-tool-result-pruner, compaction) |
7 | +209 / −25 |
| Specs and simulator | 3 | +480 / −4 |
| Docs (en / zh), generated catalogs, persistence record | 20 | +374 / −121 |
| Total | 30 | +1063 / −150 |
# pick the commit
git fetch https://github.com/Trove-design/deepseek-harness.git fix/compaction-cache
git cherry-pick 9053ca9bc8d4d7850effb2da30b20710e4b54be4
# reproduce
npx vitest run packages/compaction/compaction-basic/tests/prefix-cache-integrity.spec.ts --reporter=verbose
npx vitest run packages/compaction/ --reporter=dot
npx tsc -b packages/compaction/compaction/tsconfig.json \
packages/compaction/compaction-tool-result-pruner/tsconfig.json \
packages/compaction/compaction-basic/tsconfig.json \
packages/extensions/tool-cordis/tsconfig.jsonSource diff (7 files, +209 / −25)
diff --git a/packages/compaction/compaction-basic/src/cache-aware-prune.ts b/packages/compaction/compaction-basic/src/cache-aware-prune.ts
new file mode 100644
index 0000000000..be869e3cb5
--- /dev/null
+++ b/packages/compaction/compaction-basic/src/cache-aware-prune.ts
@@ -0,0 +1,93 @@
+/**
+ * Cache-aware ordering of the model-free prune pass relative to the summary.
+ *
+ * The summary call is cache-warm only while `[tools, system, region]` is a
+ * byte prefix of the last routed request. Rewriting any node of that region
+ * before the call moves the first divergent byte from the instruction to the
+ * first rewritten tool result, and the provider prefills everything after it
+ * again. When a summary will run anyway, region nodes are about to be
+ * shadowed by the checkpoint, so pruning them saves nothing; only the
+ * retained tail is pruned, and the tail is re-prefilled after the replacement
+ * regardless because its position shifts.
+ *
+ * @module @deepseek-ai/dsh-compaction-basic/cache-aware-prune
+ */
+
+import type { ToolResultPruner, PlannedPrune } from '@deepseek-ai/dsh-compaction-tool-result-pruner'
+import { freezeMessage } from '@deepseek-ai/dsh-llm'
+import type { ToolResultMessage } from '@deepseek-ai/dsh-llm'
+import type { Session, SessionSeq } from '@deepseek-ai/dsh-session'
+import type { TokenMeasurement, TokenMeter } from '@deepseek-ai/dsh-token-meter'
+import { selectCompactableRange } from './region.ts'
+
+/** What the pressure path should do with the model-free pass. */
+export type PrunePlan =
+ /** Nothing is over budget. */
+ | { readonly kind: 'none' }
+ /** The pass alone clears pressure: land it everywhere, as before. */
+ | { readonly kind: 'prune-only' }
+ /** A summary runs anyway: land only the nodes after the summarized region. */
+ | { readonly kind: 'tail-only'; readonly tail: ReadonlySet<SessionSeq> }
+
+/**
+ * Re-price a measurement as if the planned replacements had landed, using the
+ * same heuristic the shadow-price protocol records for each replacement.
+ * @param meter - effective token meter.
+ * @param measurement - current measurement of the unpruned surface.
+ * @param plan - replacements the pass would land.
+ * @returns a measurement over the same seqs with projected prices.
+ */
+export function projectPrunedMeasurement(
+ meter: TokenMeter,
+ measurement: TokenMeasurement,
+ plan: readonly PlannedPrune[],
+): TokenMeasurement {
+ const savings = new Map<SessionSeq, number>()
+ for (const { seq, original, content } of plan) {
+ const replacement = freezeMessage<ToolResultMessage>({ ...original, content })
+ savings.set(seq, Math.max(0, meter.estimateMessage(original) - meter.estimateMessage(replacement)))
+ }
+ let saved = 0
+ const nodes = measurement.nodes.map((node) => {
+ const delta = Math.min(node.tokens, savings.get(node.seq) ?? 0)
+ if (delta === 0) return node
+ saved += delta
+ return { ...node, tokens: node.tokens - delta, heuristicTokens: Math.max(0, node.heuristicTokens - delta) }
+ })
+ return {
+ ...measurement,
+ nodes,
+ surfaceTokens: measurement.surfaceTokens - saved,
+ totalTokens: Math.max(0, measurement.totalTokens - saved),
+ }
+}
+
+/**
+ * Decide how the prune pass lands for one pressure compaction.
+ * @param prune - the optional sibling pruner service.
+ * @param meter - effective token meter.
+ * @param session - session under pressure.
+ * @param measurement - current measurement at or above the threshold.
+ * @param thresholdTokens - resolved pressure threshold.
+ * @param retainTokens - verbatim tail budget the summary keeps.
+ * @returns the landing decision.
+ */
+export function planPrune(
+ prune: Pick<ToolResultPruner, 'planSession'>,
+ meter: TokenMeter,
+ session: Session,
+ measurement: TokenMeasurement,
+ thresholdTokens: number,
+ retainTokens: number,
+): PrunePlan {
+ const plan = prune.planSession(session)
+ if (plan.length === 0) return { kind: 'none' }
+ const projected = projectPrunedMeasurement(meter, measurement, plan)
+ if (projected.totalTokens < thresholdTokens) return { kind: 'prune-only' }
+ // Select on projected prices so the retained tail matches what the
+ // summary would keep after a full pass; the tail is then pruned for real.
+ const range = selectCompactableRange(session, projected, retainTokens)
+ const nodes = session.surface.nodes
+ const tailStart = range === null ? 0 : nodes.indexOf(range.end) + 1
+ return { kind: 'tail-only', tail: new Set(nodes.slice(tailStart)) }
+}
diff --git a/packages/compaction/compaction-basic/src/index.ts b/packages/compaction/compaction-basic/src/index.ts
index dc361d8f5e..4df5e79faf 100644
--- a/packages/compaction/compaction-basic/src/index.ts
+++ b/packages/compaction/compaction-basic/src/index.ts
@@ -29,6 +29,7 @@ import {
compactSurfaceRegion,
selectCompactableRange,
} from './region.ts'
+import { planPrune } from './cache-aware-prune.ts'
import { summarizeWithLlm } from './summarizer.ts'
import type { SummarizationInput, SummaryResult, SummaryRoute } from './summarizer.ts'
import type {
@@ -359,11 +360,30 @@ export class BasicCompactionEngine extends CompactionEngine {
)
if (measurement.totalTokens < spec.thresholdTokens) return null
- // Once pressure qualifies, land the model-free pass before choosing a
- // summary range, then remeasure through the singleton replay fold.
+ // Once pressure qualifies, the model-free pass runs first. When it alone
+ // clears pressure it lands everywhere. When a summary runs anyway, it must
+ // not rewrite the region the summary call replays, or that call misses
+ // the provider prefix cache from the first rewritten node on; only the
+ // retained tail is pruned (see cache-aware-prune.ts).
if (prune !== undefined) {
- prune.pruneSession(agent.session)
- measurement = meter.measure(agent.session, header)
+ const decision = planPrune(
+ prune, meter, agent.session, measurement, spec.thresholdTokens, spec.retainTokens,
+ )
+ switch (decision.kind) {
+ case 'none':
+ break
+ case 'prune-only':
+ prune.pruneSession(agent.session)
+ measurement = meter.measure(agent.session, header)
+ break
+ case 'tail-only':
+ prune.pruneSession(agent.session, seq => decision.tail.has(seq))
+ measurement = meter.measure(agent.session, header)
+ break
+ /* v8 ignore next -- closed-union exhaustiveness guard */
+ default:
+ assertNever(decision, 'prune decision')
+ }
}
if (measurement.totalTokens < spec.thresholdTokens) return null
diff --git a/packages/compaction/compaction-basic/src/region.ts b/packages/compaction/compaction-basic/src/region.ts
index 6b5ceca60c..08850a182a 100644
--- a/packages/compaction/compaction-basic/src/region.ts
+++ b/packages/compaction/compaction-basic/src/region.ts
@@ -487,6 +487,7 @@ function commitCompactionBody(
summary,
provider,
model,
+ reasoningEffort,
maxTokens,
usage,
checkpointMessage,
@@ -506,6 +507,7 @@ function commitCompactionBody(
shadowedTokenCount,
provider,
model,
+ ...reasoningEffort === undefined ? {} : { reasoningEffort },
...maxTokens === undefined ? {} : { maxTokens },
...usage === undefined ? {} : { usage },
})
diff --git a/packages/compaction/compaction-basic/src/summarizer.ts b/packages/compaction/compaction-basic/src/summarizer.ts
index c9184d1ed4..1d64c213e8 100644
--- a/packages/compaction/compaction-basic/src/summarizer.ts
+++ b/packages/compaction/compaction-basic/src/summarizer.ts
@@ -8,8 +8,9 @@ import type { Context } from '@deepseek-ai/cordis'
import { contentHasImage, BlockAssembler, LlmError } from '@deepseek-ai/dsh-llm'
import { deepFreeze } from '@deepseek-ai/dsh-util-values'
import type {
- ContentBlock, FinishReason, GenerateOptions, Message, RequestMessage, TokenUsage, ToolSchema,
+ ContentBlock, FinishReason, GenerateOptions, Message, ReasoningEffortId, RequestMessage, TokenUsage, ToolSchema,
} from '@deepseek-ai/dsh-llm'
+import type { EpochHeader } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
interface SummaryConfig {
@@ -91,6 +92,8 @@ export type SummaryResult = {
summary: ContentBlock[]
provider: string
model: string
+ /** The reasoning effort the summarize call sent, when one was inherited. */
+ reasoningEffort?: ReasoningEffortId
maxTokens?: number
/** Provider-reported usage for this summarization request. */
usage?: TokenUsage
@@ -109,14 +112,41 @@ export type SummaryResult = {
}
)
+/**
+ * Prompt-shaping controls the summarization call copies from the latest
+ * durable request header when it targets exactly that route. dsh-llm's
+ * call-config documents provider, model, reasoning effort, and sampling as
+ * request-header state that can affect cache reuse; without them the replayed
+ * prefix belongs to a different request family and is prefilled cold (#1944,
+ * #3002). `maxTokens` is deliberately not inherited: it caps output rather
+ * than shaping the cached prompt, and the policy sizes it against the
+ * reserved compaction headroom so the call still fits the window.
+ * @param header - latest durable request header, when one was routed.
+ * @param target - provider/model the summarization call will use.
+ * @returns the controls to spread into the summarization request.
+ */
+export function inheritedCallControls(
+ header: Pick<EpochHeader, 'config'> | undefined,
+ target: { readonly provider: string; readonly model: string },
+): Pick<GenerateOptions, 'reasoningEffort' | 'temperature' | 'stop'> {
+ const config = header?.config
+ if (config === undefined || config.provider !== target.provider || config.model !== target.model) return {}
+ return {
+ ...config.reasoningEffort === undefined ? {} : { reasoningEffort: config.reasoningEffort },
+ ...config.temperature === undefined ? {} : { temperature: config.temperature },
+ ...config.stop === undefined ? {} : { stop: [...config.stop] },
+ }
+}
+
/**
* Run the default cache-reusing `ctx.llm.stream()` summarization call: replay
- * the conversation prefix, then append the compaction instruction as the final
- * user message so the provider's warm prefix cache is reused.
+ * the conversation prefix with the routed request's prompt-shaping controls,
+ * then append the compaction instruction as the final user message so the
+ * provider's warm prefix cache is reused.
* @param ctx - context providing the LLM service.
* @param config - resolved backend configuration.
* @param input - replayed conversation prefix (system, tools, and leading messages) to condense.
- * @param agent - supplies tool history and session id.
+ * @param agent - supplies the latest request header, tool history, and session id.
* @param conversation - route used when `config` names no summary target; `undefined` when the conversation has none.
* @param signal - optional cancellation forwarded to the adapter.
* @returns safe text-only summary blocks and the exact call envelope and output.
@@ -129,6 +159,7 @@ export async function summarizeWithLlm(
conversation: SummaryRoute | undefined,
signal?: AbortSignal,
): Promise<SummaryResult> {
+ const header = agent.session.requestHeader()
const configured = config.summarizationProvider.length === 0
? undefined
: { provider: config.summarizationProvider, model: config.summarizationModel }
@@ -150,6 +181,7 @@ export async function summarizeWithLlm(
const options: GenerateOptions = {
provider: target.provider,
model: target.model,
+ ...inheritedCallControls(header, target),
messages,
toolHistory: agent.session.toolHistory(),
...input.tools === undefined ? {} : { tools: [...input.tools] },
@@ -173,6 +205,7 @@ export async function summarizeWithLlm(
llmStreamCall: true,
provider: options.provider,
model: options.model,
+ ...options.reasoningEffort === undefined ? {} : { reasoningEffort: options.reasoningEffort },
maxTokens: config.maxTokens,
...(assembler.usage === undefined ? {} : { usage: assembler.usage }),
}
diff --git a/packages/compaction/compaction-tool-result-pruner/src/index.ts b/packages/compaction/compaction-tool-result-pruner/src/index.ts
index 5f536bfc9b..267a259083 100644
--- a/packages/compaction/compaction-tool-result-pruner/src/index.ts
+++ b/packages/compaction/compaction-tool-result-pruner/src/index.ts
@@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-compaction'
import type {} from '@deepseek-ai/dsh-token-meter'
import { codePointLength, DEFAULTS, PRUNE_MARKER, resolveConfig } from './config.ts'
import type {
+ PlannedPrune,
PrunedEntry,
PruneResult,
ResolvedConfig,
@@ -23,6 +24,7 @@ import type {
export { codePointLength, DEFAULTS, PRUNE_MARKER, resolveConfig } from './config.ts'
export type {
+ PlannedPrune,
PrunedEntry,
PruneResult,
ResolvedConfig,
@@ -35,8 +37,7 @@ declare module '@deepseek-ai/cordis' {
}
}
-interface SnapshotCandidate {
- readonly seq: SessionSeq
+interface SnapshotCandidate extends PlannedPrune {
readonly event: SessionEvent<'tool/result'>
}
@@ -121,6 +122,19 @@ export class ToolResultPruner extends Service {
return pruned
}
+ /**
+ * Compute the replacements a pass would land, without appending anything.
+ * Callers that must keep part of the surface byte-stable (a cache-warm
+ * replay of the history prefix, for example) price the plan first and then
+ * land only the nodes they choose.
+ * @param session - session whose current surface is inspected.
+ * @param include - optional filter over current surface seqs; defaults to every node.
+ * @returns over-budget tool-result nodes with their pruned content, in surface order.
+ */
+ planSession(session: Session, include?: (seq: SessionSeq) => boolean): PlannedPrune[] {
+ return this.snapshot(session, include).map(({ seq, original, content }) => ({ seq, original, content }))
+ }
+
/**
* Prune every over-budget tool result from one stable current-surface snapshot.
* Each replacement preserves the complete event data except for `content`,
@@ -129,25 +143,15 @@ export class ToolResultPruner extends Service {
* shadowed node through the injected token meter, so pure consumers can
* subtract it without per-node state.
* @param session - session whose current surface is rewritten.
+ * @param include - optional filter over current surface seqs; omitted nodes stay byte-identical.
* @returns landed replacements and aggregate Unicode-code-point savings.
* @throws when the session rejects a replacement; replacements committed
* earlier in the pass remain durable.
*/
- pruneSession(session: Session): PruneResult {
- const candidates: SnapshotCandidate[] = []
- for (const seq of [...session.surface.nodes]) {
- // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
- const event = session.eventAt(seq)
- /* v8 ignore next -- surface seqs are validated contiguous log references. */
- if (event?.type === 'tool/result') candidates.push({ seq, event })
- }
-
+ pruneSession(session: Session, include?: (seq: SessionSeq) => boolean): PruneResult {
const pruned: PrunedEntry[] = []
let charsRemoved = 0
- for (const { seq, event } of candidates) {
- const original = session.deriveEventMessage(event) as ToolResultMessage
- const content = this.pruneContent(original.content)
- if (content === null) continue
+ for (const { seq, event, original, content } of this.snapshot(session, include)) {
const charsBefore = this.measureContent(original.content)
const charsAfter = this.measureContent(content)
const message = freezeMessage<ToolResultMessage>({
@@ -180,6 +184,22 @@ export class ToolResultPruner extends Service {
}
return { pruned, charsRemoved }
}
+
+ /** Snapshot every included over-budget tool-result node before any replacement lands. */
+ private snapshot(session: Session, include?: (seq: SessionSeq) => boolean): SnapshotCandidate[] {
+ const candidates: SnapshotCandidate[] = []
+ for (const seq of [...session.surface.nodes]) {
+ if (include !== undefined && !include(seq)) continue
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
+ const event = session.eventAt(seq)
+ /* v8 ignore next -- surface seqs are validated contiguous log references. */
+ if (event?.type !== 'tool/result') continue
+ const original = session.deriveEventMessage(event) as ToolResultMessage
+ const content = this.pruneContent(original.content)
+ if (content !== null) candidates.push({ seq, event, original, content })
+ }
+ return candidates
+ }
}
export default ToolResultPruner
diff --git a/packages/compaction/compaction-tool-result-pruner/src/types.ts b/packages/compaction/compaction-tool-result-pruner/src/types.ts
index 8cc6934b10..c108879c1b 100644
--- a/packages/compaction/compaction-tool-result-pruner/src/types.ts
+++ b/packages/compaction/compaction-tool-result-pruner/src/types.ts
@@ -1,4 +1,4 @@
-import type { ToolCallId } from '@deepseek-ai/dsh-llm'
+import type { ContentBlock, ToolCallId, ToolResultMessage } from '@deepseek-ai/dsh-llm'
import type { SessionSeq } from '@deepseek-ai/dsh-session/types'
/** Character-budget policy for deterministic tool-result pruning. */
@@ -32,6 +32,16 @@ export interface PrunedEntry {
readonly charsAfter: number
}
+/** One replacement a pass would land, computed without touching the log. */
+export interface PlannedPrune {
+ /** Current surface node whose tool result is over budget. */
+ readonly seq: SessionSeq
+ /** Model-visible message the node derives today. */
+ readonly original: ToolResultMessage
+ /** Pruned content the replacement would carry. */
+ readonly content: ContentBlock[]
+}
+
/** Aggregate outcome of one stable-surface pruning pass. */
export interface PruneResult {
/** Replacements in the snapshotted surface order. */
diff --git a/packages/compaction/compaction/src/types.ts b/packages/compaction/compaction/src/types.ts
index b35dc283a5..8936dfbdae 100644
--- a/packages/compaction/compaction/src/types.ts
+++ b/packages/compaction/compaction/src/types.ts
@@ -7,7 +7,7 @@
* @module @deepseek-ai/dsh-compaction/types
*/
-import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
+import type { ContentBlock, ReasoningEffortId, TokenUsage } from '@deepseek-ai/dsh-llm'
import type { CommandId } from '@deepseek-ai/dsh-commands/types'
import type { SessionSeq } from '@deepseek-ai/dsh-session/types'
import type { CompactionId } from './brand.ts'
@@ -47,6 +47,12 @@ declare module '@deepseek-ai/dsh-session/types' {
* this summary" has a durable answer (the reconstructability Agent Note).
*/
model: string
+ /**
+ * The reasoning effort the summarize call sent, when one applied. It is
+ * part of the call's cache-relevant envelope, so a fold that missed the
+ * prefix cache can be diagnosed from the log alone.
+ */
+ reasoningEffort?: ReasoningEffortId
/** The generation cap the summarize call sent, when one applied. */
maxTokens?: number
/** Provider-reported token usage for the summarization request, when emitted. */If you would like the change in a different shape, for example code and docs as separate commits, other names, or the new specs folded into compaction-basic.spec.ts, I am happy to adjust it. I can also repeat E1 and E2 on a build you name.
Thanks again, @PerryLink, and a good start to the week, everyone.
Uh oh!
There was an error while loading. Please reload this page.
master@687f282e86上仍可复现。原因有两个,彼此独立:① 摘要请求没有继承请求头中的reasoningEffort/temperature/stop;② 新发现:tool-result 修剪器在摘要之前改写了摘要请求要重放的历史,从第一个被改写的字节起全部重新计算。只修复 ① 解决不了 ②。master上 6 个失败,打补丁后全部通过(见下方回答);packages/compaction/共 236 个测试通过,tsc -b与 oxlint 无报错。git apply到687f282e86(即当前master),见下方回答。Important
TL;DR: The summary call misses the prefix cache for two independent reasons. Effort parity, as discussed in #1944 and #3002, fixes the first; the second survives it. The answer below has a patch that fixes both, with regression specs. Through the real agent loop on a simulated prefix cache, the uncached part of every summary call drops to the ~470-token instruction, at 32k, 128k and 512k windows alike (
master: about 22k / 84k / 332k).🔍 Two independent causes
masterreasoningEffort,temperatureandstopfrom the routed headersummarizer.ts#L152-L162vs. the loop'sagent.ts#L695-L702highvsnone(@bulhenvaster)index.ts#L321-L326Both break a guarantee the package README states twice: the replayed prefix "match[es] the conversation's last routed request byte-for-byte" (README#L108, README#L233).
Cause 1: the request envelope
The loop builds every request by spreading the durable request header,
...header.config(agent.ts#L696).summarizeWithLlmreads the very same header (summarizer.ts#L127) but keeps onlyproviderandmodel, sodsh-llmsubstitutes the adapter's default effort. The package's own doc names exactly these fields as cache-relevant (call-config.ts#L1-L7), and the DeepSeek adapter serializes effort asthinkingplusoutput_config.effort(serialize.ts#L147-L157).masterprovider,modelreasoningEffortmaxhightemperature,stoptoolsmaxTokensCause 2: the prune pass rewrites the replayed region
The base bundle mounts the tool-result pruner by default (cordis.patch.yml#L425-L430, 8,192 chars). Once pressure qualifies,
compactIfNeededlandspruneSession()over the whole surface and only then builds the summary input, from the rewritten surface. Oversized tool results admitted since the last checkpoint are still verbatim in the cached prefix, so the first one rewritten becomes the first divergent byte. Effort parity cannot touch this.How a prefix cache bills: a request is charged at the cache-hit price up to the first byte that differs from an earlier request, and at the full price from that byte on.
%%{init: {"flowchart": {"rankSpacing": 28, "nodeSpacing": 24, "padding": 8}}}%% flowchart TB subgraph A ["① cached: last request"] direction LR a1["tools +<br/>system prompt"] --> a2["turns<br/>1 … k"] --> a3["tool result j<br/>original"] --> a4["turns<br/>j+1 … n"] ~~~ a5[" "] end subgraph B ["② master: summary call"] direction LR b1["tools +<br/>system prompt"] --> b2["turns<br/>1 … k"] --> b3["tool result j<br/>rewritten ✗"] --> b4["turns<br/>j+1 … n"] --> b5["summary<br/>instruction"] end subgraph C ["③ patched: summary call"] direction LR c1["tools +<br/>system prompt"] --> c2["turns<br/>1 … k"] --> c3["tool result j<br/>original ✓"] --> c4["turns<br/>j+1 … n"] --> c5["summary<br/>instruction"] end A ~~~ B ~~~ C classDef ref fill:#f6f8fa,stroke:#8c959f,color:#1f2328 classDef hit fill:#dafbe1,stroke:#1a7f37,color:#0f3d1c classDef miss fill:#ffebe9,stroke:#cf222e,color:#6e0b12 classDef fresh fill:#ddf4ff,stroke:#0969da,color:#0a3069 classDef ghost fill:transparent,stroke:transparent,color:transparent class a1,a2,a3,a4 ref class b1,b2,c1,c2,c3,c4 hit class b3,b4 miss class b5,c5 fresh class a5 ghost style A fill:transparent,stroke:#8c959f style B fill:transparent,stroke:#8c959f style C fill:transparent,stroke:#8c959f🟩 served from the cache · 🟥 computed again at full price · 🟦 new input, unavoidable · ⬜ what the cache already holds
In the 128k run measured in the answer below, with the effort already aligned, the red part of the first summary call was 73,241 of 83,945 tokens (87%). Patched, only the 469-token instruction is new.
Fix, measurements, verification and the full patch follow in the answer below.
All reactions