From 0fadb08fbdd3316c4605fc4e6be96cb9990b56c6 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Fri, 18 Sep 2026 14:59:36 +0800 Subject: [PATCH] fix(compaction): gate pressure on the message budget, not the whole window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Proactive pressure scaled `thresholdRatio` by the routed model's entire context window, but a request also reserves output tokens the provider charges to that same window — the LLM service deliberately never clamps them (`packages/llm/llm/src/index.ts`). With a 1,000,000-token window and the default 256,000-token request cap the gate therefore sat at 800,000 while the provider refused any prompt above 792,576. Observed in a real session: three requests died at 792,850 / 797,639 / 793,352 message tokens ("maximum context length is 1048576 ... you requested 1048850 tokens"), no pressure compaction ever fired, and the overflow recovery that did run could not condense an ~800k-token history into the 8192-token summary cap. Scale both ratios by the message budget left after the reserve, sourced from the effective request envelope's `maxTokens` and falling back to the adapter's per-request output default. A reserve that leaves no message budget reports a target-specific pressure configuration error, matching the existing per-route warning policy rather than silently disabling proactive compaction. The headless compaction e2e advertises a coherent capacity/cap pair so its 8000-token message budget and 4000-token threshold are unchanged. Related #1841 --- ...el-context-and-compaction-policy.i18n.yaml | 4 +- ...ted-model-context-and-compaction-policy.md | 6 +- ...-model-context-and-compaction-policy.zh.md | 6 +- .../profiles/headless/tests/compaction.e2e.ts | 7 +- .../tests/profiles/headless/tests/harness.ts | 20 ++++- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- .../compaction-basic/README.i18n.yaml | 4 +- .../compaction/compaction-basic/README.md | 6 +- .../compaction/compaction-basic/README.zh.md | 6 +- .../compaction/compaction-basic/src/config.ts | 31 +++++++- .../compaction/compaction-basic/src/index.ts | 21 ++++- .../compaction/compaction-basic/src/types.ts | 6 +- .../tests/compaction-basic.spec.ts | 76 +++++++++++++++++++ 15 files changed, 172 insertions(+), 33 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.i18n.yaml index 98f54d5d26..de3cbb444a 100644 --- a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md -2026-07-20-routed-model-context-and-compaction-policy.md: 26d8a4a85c284e50b9635017f0dd0bf905a4427f -2026-07-20-routed-model-context-and-compaction-policy.zh.md: 8656200a4b25c2ca70160e8f5949a7518e390168 +2026-07-20-routed-model-context-and-compaction-policy.md: 0c0dd2d13ffc11af3e4da155dc75c7dd5c4e8226 +2026-07-20-routed-model-context-and-compaction-policy.zh.md: 53e9b97f6814fbf2f880014992528b9671c86adf diff --git a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md index 26d8a4a85c..0c0dd2d13f 100644 --- a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md +++ b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md @@ -26,7 +26,7 @@ The hand-rolled DeepSeek adapter accepts optional `contextWindow` on each config Compact-basic owns consumer policy. Top-level fields define defaults; `modelPolicies` contains partial overrides keyed by the exact `{ provider, model }` pair. Duplicate targets and unknown or invalid fields fail plugin load. `thresholdRatio` defaults to `0.8`, and retention defaults to `retainRatio: 0.16`; callers may use an absolute `retainTokens` instead, but the two retention forms are mutually exclusive. After inheritance, a ratio retention that is not below its threshold ratio also fails plugin load because no model capacity can make that policy valid. -For proactive pressure, compaction-basic reads the latest durable request route, resolves its adapter capacity and exact-target policy, and scales ratios into a `ResolvedCompactSpec`. It performs this resolution on every check, so a provider or model switch in one session changes capacity and policy immediately. An absolute retained budget that is not below the scaled threshold fails when the target capacity first makes that comparison possible. +For proactive pressure, compaction-basic reads the latest durable request route, resolves its adapter capacity and exact-target policy, and scales ratios into a `ResolvedCompactSpec`. Ratios scale the route's *message budget* — its context window minus the output tokens one request reserves — because a provider charges the prompt and that reservation to the same window. Scaling the whole window instead places the threshold above the point where the provider refuses the request, so proactive pressure can never fire and only provider-confirmed overflow can condense. The reservation is the effective envelope's `maxTokens`, else the adapter's per-request output default. It performs this resolution on every check, so a provider or model switch in one session changes capacity and policy immediately. An absolute retained budget that is not below the scaled threshold fails when the target capacity first makes that comparison possible. The same exact-target override can select summarization provider/model, summarization output cap, convergence retries, and overflow retry cap. These are compaction concerns and never enter an LLM provider. @@ -36,7 +36,7 @@ An adapter that lacks capacity metadata remains a valid LLM route. Manual proact ## Testing -Service tests cover detached context metadata, invalid adapter output, catalog independence, and default absence. Adapter tests cover DeepSeek exact/default/unlisted resolution, invalid capacities, and pi-ai exact descriptor resolution. Compact tests cover ratio scaling, exact provider/model overrides, load-time rejection of invalid merged ratios, runtime absolute-budget validation, same-model-id provider switches, target-specific warning suppression, and capacity-independent overflow recovery. Loader fixtures reject the removed token-meter capacity setting, and examples configure capacity on adapters. +Service tests cover detached context metadata, invalid adapter output, catalog independence, and default absence. Adapter tests cover DeepSeek exact/default/unlisted resolution, invalid capacities, and pi-ai exact descriptor resolution. Compact tests cover ratio scaling against the message budget left after the routed request's reservation (envelope cap and adapter-default fallback), exact provider/model overrides, load-time rejection of invalid merged ratios, runtime absolute-budget validation, same-model-id provider switches, target-specific warning suppression, and capacity-independent overflow recovery. Loader fixtures reject the removed token-meter capacity setting, and examples configure capacity on adapters. ## Alternatives considered @@ -52,6 +52,6 @@ Service tests cover detached context metadata, invalid adapter output, catalog i - The same compaction-basic instance safely handles different windows, provider switches, and identical model ids under different providers without consulting discovery metadata. - LLM-only and meter-only compositions remain valid; loading compaction-basic adds no reverse dependency from adapters. - DeepSeek deployments may set exact per-model capacities, or use `defaultContextWindow` for entries without capacity and unlisted pass-through ids. -- Ratio defaults scale naturally across models, while exact-target absolute retention remains available for deployment-specific behavior. +- Ratio defaults scale naturally across models and exclude the output tokens each request reserves, while exact-target absolute retention remains available for deployment-specific behavior. This note supersedes the global-capacity and no-model-policy parts of the [replay token meter service Agent Note](../../archived/architecture/2026-07-15-replay-token-meter-service.md). Its single-fold measurement decision remains unchanged. diff --git a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.zh.md b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.zh.md index 8656200a4b..53e9b97f68 100644 --- a/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.zh.md @@ -26,7 +26,7 @@ Status: implemented Compact-basic 拥有消费方策略。顶层字段定义默认值;`modelPolicies` 包含以精确 `{ provider, model }` 组合为键的部分覆盖。重复目标、未知字段或无效字段都会让插件加载失败。`thresholdRatio` 默认为 `0.8`,保留策略默认为 `retainRatio: 0.16`;调用方也可以改用绝对 `retainTokens`,但两种保留形式互斥。完成继承后,如果保留比例不小于阈值比例,插件也会加载失败,因为任何模型容量都无法让该策略有效。 -对于主动压力检查,compaction-basic 读取最新持久请求路由,解析其适配器容量与精确目标策略,再把比例缩放为 `ResolvedCompactSpec`。每次检查都会重新解析,因此同一会话切换提供方或模型后,容量与策略会立即变化。若绝对保留预算不小于缩放后的阈值,系统会在目标容量首次允许比较两者时失败。 +对于主动压力检查,compaction-basic 读取最新持久请求路由,解析其适配器容量与精确目标策略,再把比例缩放为 `ResolvedCompactSpec`。比例缩放的是该路由的**消息预算**——其上下文窗口减去单次请求预留的输出 token——因为提供方把提示词与这份预留计入同一个窗口。若改为按整个窗口缩放,阈值就会落在提供方开始拒绝请求的位置之上,主动压力将永远无法触发,只剩提供方确认溢出这一条路可走。这份预留取自生效信封的 `maxTokens`,否则取适配器按请求输出的默认值。每次检查都会重新解析,因此同一会话切换提供方或模型后,容量与策略会立即变化。若绝对保留预算不小于缩放后的阈值,系统会在目标容量首次允许比较两者时失败。 同一精确目标覆盖还可以选择摘要提供方/模型、摘要输出上限、收敛重试次数与溢出重试上限。这些都属于压缩问题,不会进入任何 LLM 提供方。 @@ -36,7 +36,7 @@ Compact-basic 拥有消费方策略。顶层字段定义默认值;`modelPolici ## 测试 -服务测试覆盖与适配器内部状态分离的上下文元数据、无效适配器输出、目录独立性与默认缺失行为。适配器测试覆盖 DeepSeek 的精确容量、默认容量、未列出模型解析及无效容量,以及 pi-ai 的精确描述符解析。压缩测试覆盖比例缩放、精确提供方/模型覆盖、加载期拒绝无效合并比例、运行时校验绝对预算、相同模型 id 的提供方切换、目标专用警告抑制与不依赖容量的溢出恢复。Loader fixture(测试前置数据)会拒绝已经移除的 token-meter 容量设置,示例则在适配器上配置容量。 +服务测试覆盖与适配器内部状态分离的上下文元数据、无效适配器输出、目录独立性与默认缺失行为。适配器测试覆盖 DeepSeek 的精确容量、默认容量、未列出模型解析及无效容量,以及 pi-ai 的精确描述符解析。压缩测试覆盖按已路由请求预留之后的消息预算进行比例缩放(生效信封上限与适配器默认回退两条路径)、精确提供方/模型覆盖、加载期拒绝无效合并比例、运行时校验绝对预算、相同模型 id 的提供方切换、目标专用警告抑制与不依赖容量的溢出恢复。Loader fixture(测试前置数据)会拒绝已经移除的 token-meter 容量设置,示例则在适配器上配置容量。 ## 考虑过的替代方案 @@ -52,6 +52,6 @@ Compact-basic 拥有消费方策略。顶层字段定义默认值;`modelPolici - 同一个 compaction-basic 实例无需查询发现元数据,就能安全处理不同窗口、提供方切换,以及不同提供方下的相同模型 id。 - 仅 LLM 与仅 meter 的组合仍然有效;加载 compaction-basic 不会让适配器产生反向依赖。 - DeepSeek 部署可以设置精确的逐模型容量,也可以让未提供容量的模型项与未列出的透传 id 使用 `defaultContextWindow`。 -- 比例默认值会随模型自然缩放,同时仍可按精确目标使用绝对保留值,以满足部署专用行为。 +- 比例默认值会随模型自然缩放,并扣除每次请求预留的输出 token;同时仍可按精确目标使用绝对保留值,以满足部署专用行为。 本记录取代[回放式 token 计量服务 Agent Note](../../archived/architecture/2026-07-15-replay-token-meter-service.md) 中的全局容量与无模型策略部分,单折叠计量决策保持不变。 diff --git a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts index b2f470e3be..6cf3c71401 100644 --- a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts @@ -35,7 +35,12 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa // Reasoning tokens require a larger generation cap than the retained checkpoint. ctx = await codingHarness(workdir, { personaPrefix: SYSTEM_PROMPT, - modelContextWindow: 8000, + // Pressure counts only the message budget left after the request's + // reserved output tokens, so the advertised capacity must exceed that + // cap: 15_000 - 7_000 leaves the 8000-token window this scenario used to + // advertise on its own, and a threshold of 4000 tokens unchanged. + modelContextWindow: 15_000, + modelMaxTokens: 7_000, compact: { thresholdRatio: 0.5, retainTokens: 400, diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index 05d4a9e814..9c17fa27f4 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -49,8 +49,18 @@ export interface CodingHarnessOptions { * compaction plugin (the default suites run without it). */ compact?: BasicCompactionConfig - /** Test-only context capacity advertised for `deepseek-v4-flash`. */ + /** + * Test-only context capacity advertised for `deepseek-v4-flash`. Automatic + * pressure scales the message budget left after the request's reserved + * output tokens, so this capacity must exceed the advertised output cap. + */ modelContextWindow?: number + /** + * Test-only per-request output cap advertised for `deepseek-v4-flash`, which + * the adapter forwards as `max_tokens` and pressure excludes from the + * capacity above. + */ + modelMaxTokens?: number } export async function codingHarness(workdir: string, options: CodingHarnessOptions = {}): Promise { @@ -60,8 +70,12 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio }) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LlmDeepSeek, { - ...options.modelContextWindow === undefined ? {} : { - models: [{ id: 'deepseek-v4-flash', contextWindow: options.modelContextWindow }], + ...options.modelContextWindow === undefined && options.modelMaxTokens === undefined ? {} : { + models: [{ + id: 'deepseek-v4-flash', + ...options.modelContextWindow === undefined ? {} : { contextWindow: options.modelContextWindow }, + ...options.modelMaxTokens === undefined ? {} : { maxTokens: options.modelMaxTokens }, + }], }, }) await ctx.plugin(LocalSubprocessRuntime) diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 782c44337b..859b69315b 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 239da8f903a0031340deff551293ab96dd4333f0 -config-catalog.zh.md: e6279390fac6a81146e2ecebda56c7395415df30 +config-catalog.md: 422383d1a102fc2139897d581a6897efbc1ade29 +config-catalog.zh.md: fe156ebd82ed58cd021542f1395fb08532e29960 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 239da8f903..422383d1a1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -486,9 +486,9 @@ export interface BasicCompactionConfig extends CompactionPolicyConfig { /** Policy fields shared by the default policy and exact model overrides. */ export interface CompactionPolicyConfig { - /** Compact at this fraction of the model's context window. Defaults to `0.8`. */ + /** Compact at this fraction of the model's message budget: context window minus reserved output tokens. Defaults to `0.8`. */ thresholdRatio?: number - /** Recent context retained as a fraction of the model's window. Defaults to `0.16`. */ + /** Recent context retained as a fraction of that same message budget. Defaults to `0.16`. */ retainRatio?: number /** Absolute recent-context budget; mutually exclusive with `retainRatio`. */ retainTokens?: number diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e6279390fa..fe156ebd82 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -488,9 +488,9 @@ export interface BasicCompactionConfig extends CompactionPolicyConfig { /** Policy fields shared by the default policy and exact model overrides. */ export interface CompactionPolicyConfig { - /** Compact at this fraction of the model's context window. Defaults to `0.8`. */ + /** Compact at this fraction of the model's message budget: context window minus reserved output tokens. Defaults to `0.8`. */ thresholdRatio?: number - /** Recent context retained as a fraction of the model's window. Defaults to `0.16`. */ + /** Recent context retained as a fraction of that same message budget. Defaults to `0.16`. */ retainRatio?: number /** Absolute recent-context budget; mutually exclusive with `retainRatio`. */ retainTokens?: number diff --git a/packages/compaction/compaction-basic/README.i18n.yaml b/packages/compaction/compaction-basic/README.i18n.yaml index 51b885763b..cbe2298635 100644 --- a/packages/compaction/compaction-basic/README.i18n.yaml +++ b/packages/compaction/compaction-basic/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/compaction/compaction-basic/README.md -README.md: cb31438816088070fe996e7f3d38b8480404aa84 -README.zh.md: a038fecc9880160a4fc23377cd5fec6e931a7b01 +README.md: 31ec902ab5f2da3bc40a745f2c5e813408ad87b9 +README.zh.md: 28d151ba782c348818edfc8d619abb1dc90e3fea diff --git a/packages/compaction/compaction-basic/README.md b/packages/compaction/compaction-basic/README.md index cb31438816..31ec902ab5 100644 --- a/packages/compaction/compaction-basic/README.md +++ b/packages/compaction/compaction-basic/README.md @@ -59,12 +59,12 @@ You can verify success by watching the conversation continue past the point wher ### Tuning when condensation starts -All settings are optional. The defaults start condensing at 80% of the routed model's context window and keep the newest 16% verbatim; the table below is the complete policy surface, and the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-compaction-basic) is the exhaustive source. +All settings are optional. The defaults start condensing at 80% of the routed model's message budget — its context window minus the output tokens one request reserves — and keep the newest 16% of that budget verbatim; the table below is the complete policy surface, and the generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-compaction-basic) is the exhaustive source. | Field | Default | Meaning | |---|---|---| -| `thresholdRatio` | `0.8` | Start condensing at `floor(routedContextWindow × ratio)`. | -| `retainRatio` | `0.16` | Recent conversation kept verbatim as a fraction of the routed context window; mutually exclusive with `retainTokens`. | +| `thresholdRatio` | `0.8` | Start condensing at `floor(messageBudget × ratio)`, where `messageBudget` is the routed context window minus the output tokens one request reserves. | +| `retainRatio` | `0.16` | Recent conversation kept verbatim as a fraction of that same message budget; mutually exclusive with `retainTokens`. | | `retainTokens` | — | Absolute recent-conversation budget kept verbatim; mutually exclusive with `retainRatio` and must be below the resolved threshold. | | `summarizationProvider` | `''` | Set together with `summarizationModel`; an empty pair uses the latest routed request target, then the `AgentOptions` pair. | | `summarizationModel` | `''` | Set together with `summarizationProvider`; an empty pair uses the latest routed request target, then the `AgentOptions` pair. | diff --git a/packages/compaction/compaction-basic/README.zh.md b/packages/compaction/compaction-basic/README.zh.md index a038fecc98..28d151ba78 100644 --- a/packages/compaction/compaction-basic/README.zh.md +++ b/packages/compaction/compaction-basic/README.zh.md @@ -59,12 +59,12 @@ kind: "package-reference" ### 调整压缩开始的时机 -所有设置都可选。默认在已路由模型上下文窗口的 80% 处开始压缩,并逐字保留最新的 16%;下表是完整的策略面,生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-compaction-basic)是穷尽式真源。 +所有设置都可选。默认在对话达到已路由模型消息预算的 80% 处开始压缩——消息预算即其上下文窗口减去单次请求预留的输出 token——并逐字保留该预算最新的 16%;下表是完整的策略面,生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-compaction-basic)是穷尽式真源。 | 字段 | 默认值 | 含义 | |---|---|---| -| `thresholdRatio` | `0.8` | 在 `floor(routedContextWindow × ratio)` 处开始压缩。 | -| `retainRatio` | `0.16` | 以已路由上下文窗口的一部分表示逐字保留的近期对话;与 `retainTokens` 互斥。 | +| `thresholdRatio` | `0.8` | 在 `floor(messageBudget × ratio)` 处开始压缩,其中 `messageBudget` 为已路由上下文窗口减去单次请求预留的输出 token。 | +| `retainRatio` | `0.16` | 以同一消息预算的一部分表示逐字保留的近期对话;与 `retainTokens` 互斥。 | | `retainTokens` | — | 逐字保留的近期对话绝对预算;与 `retainRatio` 互斥,并且必须低于已解析阈值。 | | `summarizationProvider` | `''` | 与 `summarizationModel` 一起设置;空对使用最新已路由请求目标,再回退到 `AgentOptions` 对。 | | `summarizationModel` | `''` | 与 `summarizationProvider` 一起设置;空对使用最新已路由请求目标,再回退到 `AgentOptions` 对。 | diff --git a/packages/compaction/compaction-basic/src/config.ts b/packages/compaction/compaction-basic/src/config.ts index 9628c80178..042bd68204 100644 --- a/packages/compaction/compaction-basic/src/config.ts +++ b/packages/compaction/compaction-basic/src/config.ts @@ -126,13 +126,23 @@ export function resolveTargetPolicy( /** * Scale one routed policy into concrete token budgets for its model capacity. + * + * A routed request reserves output tokens that the provider charges to the same + * window as the prompt, so only the capacity left after that reservation is + * available to messages. Both budgets scale that message budget: scaling the + * whole window instead would place the pressure gate above the point where the + * provider starts rejecting the request, leaving proactive compaction + * unreachable. + * * @param policy - merged policy for the exact routed target. * @param contextWindow - positive adapter-owned capacity for that target. + * @param reservedCompletionTokens - output tokens one routed request reserves. * @returns detached immutable pressure and retention budgets. */ export function resolveCompactSpec( policy: ResolvedTargetPolicy, contextWindow: number, + reservedCompletionTokens = 0, ): ResolvedCompactSpec { const targetKey = `${policy.target.provider}/${policy.target.model}` if (!Number.isInteger(contextWindow) || contextWindow <= 0) { @@ -141,9 +151,25 @@ export function resolveCompactSpec( `BasicCompactionConfig: contextWindow (${contextWindow}) must be a positive integer`, ) } - const thresholdTokens = Math.floor(contextWindow * policy.thresholdRatio) + if (!Number.isInteger(reservedCompletionTokens) || reservedCompletionTokens < 0) { + throw new TargetPressureConfigError( + targetKey, + `BasicCompactionConfig: reservedCompletionTokens (${reservedCompletionTokens}) ` + + 'must be a non-negative integer', + ) + } + const messageBudgetTokens = contextWindow - reservedCompletionTokens + if (messageBudgetTokens <= 0) { + throw new TargetPressureConfigError( + targetKey, + `BasicCompactionConfig: ${targetKey} reserves ${reservedCompletionTokens} completion tokens ` + + `of its ${contextWindow}-token context window, leaving no message budget; the routed ` + + "request's output cap must be smaller than the declared context window", + ) + } + const thresholdTokens = Math.floor(messageBudgetTokens * policy.thresholdRatio) const retainTokens = policy.retainTokens === undefined - ? Math.floor(contextWindow * policy.retainRatio) + ? Math.floor(messageBudgetTokens * policy.retainRatio) : policy.retainTokens if (retainTokens >= thresholdTokens) { throw new TargetPressureConfigError( @@ -155,6 +181,7 @@ export function resolveCompactSpec( return deepFreeze({ target: { ...policy.target }, contextWindow, + reservedCompletionTokens, thresholdRatio: policy.thresholdRatio, thresholdTokens, retainTokens, diff --git a/packages/compaction/compaction-basic/src/index.ts b/packages/compaction/compaction-basic/src/index.ts index 8be02cb64a..a6d8b21177 100644 --- a/packages/compaction/compaction-basic/src/index.ts +++ b/packages/compaction/compaction-basic/src/index.ts @@ -56,6 +56,17 @@ function routedTarget( return { provider: config.provider, model: config.model } } +/** + * Output tokens the routed request reserves, which the provider charges to the + * same window as the prompt. The effective envelope's own cap wins; otherwise + * the adapter's per-request default, which the adapter materializes when that + * envelope omits one. No declared cap means no reservation. + */ +function reservedCompletionTokens(agent: Agent, defaultMaxTokens: number | undefined): number { + const configured = agent.session.requestHeader()?.config.maxTokens + return configured ?? defaultMaxTokens ?? 0 +} + /** Resolve the conversation target used to select an optional policy override. */ function conversationTarget( agent: Agent, @@ -287,17 +298,21 @@ export class BasicCompactionEngine extends CompactionEngine { return this.compactRegion(range.start, range.end, agent, signal) } - const context = (await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal)).context + const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal) assertNoActiveCompaction(agent.session, 'automatic pressure compaction') const targetKey = `${target.provider}/${target.model}` - if (context === undefined) { + if (info.context === undefined) { throw new TargetPressureConfigError( targetKey, `compaction-basic: no context capacity for ${targetKey}; ` + 'configure contextWindow on that adapter model', ) } - const spec = resolveCompactSpec(policy, context.contextWindow) + const spec = resolveCompactSpec( + policy, + info.context.contextWindow, + reservedCompletionTokens(agent, info.defaultMaxTokens), + ) if (measurement.totalTokens < spec.thresholdTokens) return null // Once pressure qualifies, land the model-free pass before choosing a diff --git a/packages/compaction/compaction-basic/src/types.ts b/packages/compaction/compaction-basic/src/types.ts index 05fc354573..d9dc6285bf 100644 --- a/packages/compaction/compaction-basic/src/types.ts +++ b/packages/compaction/compaction-basic/src/types.ts @@ -8,9 +8,9 @@ import type { LlmCallConfig } from '@deepseek-ai/dsh-llm' /** Policy fields shared by the default policy and exact model overrides. */ export interface CompactionPolicyConfig { - /** Compact at this fraction of the model's context window. Defaults to `0.8`. */ + /** Compact at this fraction of the model's message budget: context window minus reserved output tokens. Defaults to `0.8`. */ thresholdRatio?: number - /** Recent context retained as a fraction of the model's window. Defaults to `0.16`. */ + /** Recent context retained as a fraction of that same message budget. Defaults to `0.16`. */ retainRatio?: number /** Absolute recent-context budget; mutually exclusive with `retainRatio`. */ retainTokens?: number @@ -71,6 +71,8 @@ export type ResolvedTargetPolicy = ResolvedPolicyFields & ResolvedRetention & { /** One routed model's concrete pressure and retention budget. */ export type ResolvedCompactSpec = Omit & { readonly contextWindow: number + /** Output tokens one routed request reserves, excluded from both budgets. */ + readonly reservedCompletionTokens: number readonly thresholdTokens: number readonly retainTokens: number } diff --git a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts index 9c36961f81..28d01d22b4 100644 --- a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts @@ -397,6 +397,43 @@ describe('compact configuration and defaults', () => { }) }) + it('scales both budgets by the message budget left after the reserved completion tokens', () => { + const policy = resolveTargetPolicy(resolveConfig({ + thresholdRatio: 0.8, + retainRatio: 0.16, + }), { provider: MODEL, model: MODEL }) + + // 1_048_576 - 256_000 = 792_576 available to messages: a 256_000-token + // reserve must not leave the gate (800_000 on the whole window) above the + // point where the provider rejects the request. + expect(resolveCompactSpec(policy, 1_048_576, 256_000)).toMatchObject({ + contextWindow: 1_048_576, + reservedCompletionTokens: 256_000, + thresholdTokens: 634_060, + retainTokens: 126_812, + }) + + // No declared reserve keeps the whole window available, as before. + expect(resolveCompactSpec(policy, 1_000)).toMatchObject({ + reservedCompletionTokens: 0, + thresholdTokens: 800, + retainTokens: 160, + }) + }) + + it('rejects a reserve that leaves no message budget or is not a count', () => { + const policy = resolveTargetPolicy(resolveConfig({}), { provider: MODEL, model: MODEL }) + + expect(() => resolveCompactSpec(policy, 1_000, 1_000)) + .toThrow(/reserves 1000 completion tokens.*leaving no message budget/) + expect(() => resolveCompactSpec(policy, 1_000, 1_500)) + .toThrow(/leaving no message budget/) + expect(() => resolveCompactSpec(policy, 1_000, -1)) + .toThrow(/reservedCompletionTokens \(-1\) must be a non-negative integer/) + expect(() => resolveCompactSpec(policy, 1_000, 1.5)) + .toThrow(/reservedCompletionTokens \(1.5\) must be a non-negative integer/) + }) + it('inherits, clears, and replaces the summarization target as a pair', () => { const config = resolveConfig({ summarizationProvider: 'default-provider', @@ -565,6 +602,45 @@ describe('pressure measurement and retention', () => { await expect(compactIfNeeded(compact, session)).resolves.not.toBeNull() }) + it('gates pressure on the reserve the routed envelope records', async () => { + const ctx = createContext(1_000) + const compact = service({ auto: false, thresholdRatio: 0.8, retainRatio: 0.1 }, ctx) + const session = conversation(4) + const measured = ctx.tokenMeter.measure(session).totalTokens + + // Premise: the measured pressure clears 80% of the whole window, so the + // gate the reserve-free deployment uses stays closed. + expect(measured).toBeLessThan(800) + await expect(compactIfNeeded(compact, session)).resolves.toBeNull() + + // The same pressure exceeds 80% of the budget left once the request + // reserves its output tokens: a gate scaled by the whole window would miss it. + const maxTokens = 1_000 - Math.floor(measured / 0.8) - 1 + session.append('request/header', { + header: { config: { provider: MODEL, model: MODEL, maxTokens } }, + reason: 'change', + }) + await expect(compactIfNeeded(compact, session)).resolves.not.toBeNull() + }) + + it('falls back to the adapter request cap when the envelope records no reserve', async () => { + const ctx = createContext(1_000) + const compact = service({ auto: false, thresholdRatio: 0.8, retainRatio: 0.1 }, ctx) + const session = conversation(4) + const measured = ctx.tokenMeter.measure(session).totalTokens + expect(measured).toBeLessThan(800) + + vi.spyOn(ctx.llm, 'resolveModelInfo').mockImplementation((provider, model) => Promise.resolve({ + provider, + id: model, + name: model, + context: { contextWindow: 1_000 }, + defaultMaxTokens: 1_000 - Math.floor(measured / 0.8) - 1, + })) + + await expect(compactIfNeeded(compact, session)).resolves.not.toBeNull() + }) + it('requires capacity only for proactive pressure, not provider-confirmed overflow', async () => { const ctx = new Context() void new LlmRuntime(ctx)