agent: leave a compaction range alone when a summary cannot bring the conversation under the limit

The Harness starts pressure compaction at a token count that depends on the window (profile.mjs compactionThreshold). A chat's fixed part (system
prompt and tools) is about 10.5K tokens (context-fit.mjs BASE_TOKENS). On a 16K window the threshold is 10,036, below that fixed part, so every step
started a compaction: a summary request over the conversation and a rewritten history that the engine reads again from the start (measured on an RTX
3060, SQ-20, one slot: cached_tokens 0 on every step, 31-36 s of prompt reading per step, plus 8-24 s per summary).

profile.mjs now also hands the plugin the limit of each route and model; strata-compaction.mjs skips a pressure compaction when the tokens outside the
range plus a minimal summary already reach that limit. The context-overflow trigger, ranges that do bring the conversation under the limit, models
without a limit, and an unmeasured total behave as before.
This commit is contained in:
Niko1221 committed 2026-12-02 00:07:01 +01:00
1 parent 7df45a4c02
commit 991fe4fc5b
4 files changed
+100 -10

No files matched your search

@@ -5,20 +5,30 @@ export const inject = ['compaction', 'tokenMeter'];
const wrapped = new WeakSet();
export function apply(ctx) {
export function apply(ctx, config = {}) {
// This plugin lives beside the isolated compaction service. Its pre-step
// listener calls the original Cordis instance, including its internal methods.
const compaction = ctx.compaction;
const log = (level, text) => { try { ctx.logger?.[level]?.(text); } catch { /* logging never blocks */ } };
guardPressureCompaction(compaction[Symbol.for('cordis.original')] ?? compaction, ctx.tokenMeter, log);
guardPressureCompaction(compaction[Symbol.for('cordis.original')] ?? compaction, ctx.tokenMeter, log, config?.limits);
}
// A checkpoint includes framing and instructions. Tiny prefixes are cheaper
// to keep verbatim, especially when a summary would displace a cached prompt.
const MIN_PRESSURE_SOURCE_TOKENS = 128;
/** The least a summary leaves in place of the range it replaces (its framing and a few lines). */
const MIN_SUMMARY_TOKENS = 256;
const SKIP_PRESSURE_COMPACTION = Symbol('skip pressure compaction');
export function guardPressureCompaction(compaction, meter, log) {
/**
* `limits` maps route, then model, to the token count where pressure compaction starts for that model ({ [route]: { [model]: tokens } }, profile.mjs). A summary replaces the
* range it covers, so what stays after it is the rest of the conversation (system prompt, tools, the newest steps) plus the summary. When that
* already reaches the limit, compaction cannot get the conversation under it: the next step would start another one, each one a model call that
* reads the conversation and a rewritten history the engine reads again from the start (a 16K window against the ~10.5K tokens of system prompt
* and tools: every step was a full re-read). That range is left alone; the request that really overflows still has its own recovery
* (`context-overflow`), which this guard never touches.
*/
export function guardPressureCompaction(compaction, meter, log, limits = null) {
if (!compaction || !meter || typeof compaction.compactIfNeeded !== 'function'
|| typeof compaction.compactRegion !== 'function' || wrapped.has(compaction)) return;
wrapped.add(compaction);
@@ -41,7 +51,7 @@ export function guardPressureCompaction(compaction, meter, log) {
if (pressure.getStore() !== agent) return compactRegion.call(this, start, end, agent, signal);
signal?.throwIfAborted();
const session = agent.session;
const { nodes } = meter.measure(session);
const { nodes, totalTokens } = meter.measure(session);
const first = nodes.findIndex(node => node.seq === start);
const last = nodes.findIndex(node => node.seq === end);
// The Harness still validates stale or unbalanced ranges itself.
@@ -51,6 +61,11 @@ export function guardPressureCompaction(compaction, meter, log) {
const config = session.requestHeader?.()?.config;
const key = JSON.stringify([config?.provider, config?.model, range.map(node => node.seq)]);
if (tokens < MIN_PRESSURE_SOURCE_TOKENS || failed.get(session) === key) throw SKIP_PRESSURE_COMPACTION;
const limit = limits?.[config?.provider]?.[config?.model];
if (limit > 0 && Number.isFinite(totalTokens) && totalTokens - tokens + Math.min(tokens, MIN_SUMMARY_TOKENS) >= limit) {
log('info', `skipping pressure compaction: the ${totalTokens - tokens} tokens outside this range already reach the ${limit}-token limit, a summary cannot bring the conversation under it`);
throw SKIP_PRESSURE_COMPACTION;
}
try {
const result = await compactRegion.call(this, start, end, agent, signal);
failed.delete(session);
+2 -2
View File
@@ -75,7 +75,7 @@ export function agentPromptFor(platform = process.platform, { modelNames = false
* @param {{platform?: string, search?: boolean}} [options]
* @returns {object} the `config` of the `preset-standard` row
*/
export function standardPreset({ platform = process.platform, search = false, off = new Set(), skillsDir = null, skillTool = true, compaction = [], modelNames = false } = {}) {
export function standardPreset({ platform = process.platform, search = false, off = new Set(), skillsDir = null, skillTool = true, compaction = [], compactionLimits = {}, modelNames = false } = {}) {
const windows = platform === 'win32';
const plugins = [
{ id: 'persona', name: '@deepseek-ai/dsh-persona', config: { prefix: agentPromptFor(platform, { modelNames }), complete: true, includeRuntimeContext: false } },
@@ -96,7 +96,7 @@ export function standardPreset({ platform = process.platform, search = false, of
id: 'compaction', name: 'cordis:group', group: true, isolate: { compaction: true, toolResultPruner: true },
config: [
{ id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic', ...(compaction.length ? { config: { modelPolicies: compaction } } : {}) },
{ id: 'strata-compaction', name: COMPACTION_PLUGIN, config: {} },
{ id: 'strata-compaction', name: COMPACTION_PLUGIN, config: { limits: compactionLimits } },
{ id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' },
{ id: 'tool-result-pruner', name: '@deepseek-ai/dsh-compaction-tool-result-pruner', config: { thresholdChars: 8192, headChars: 4096, tailChars: 1024 } },
],
+10 -4
View File
@@ -339,6 +339,12 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
let slots = 0;
/** Per-model compaction timing (see compactionHeadroom). */
const compaction = [];
/** Where pressure compaction starts for each route and model, in tokens (read by plugins/strata-compaction.mjs, which leaves a range alone when a summary could not bring the conversation under it). */
const compactionLimits = {};
const addCompaction = (provider, model, window, out) => {
compaction.push({ provider, model, headroomTokens: compactionHeadroom(window, out), thresholdRatio: thresholdRatio() });
(compactionLimits[provider] ??= {})[model] = compactionThreshold(window, out);
};
/** Routes the person's Response settings can reach: a copy of the provider whose address is this host's forwarding endpoint (see llm-shape.mjs). */
const shapeTargets = {};
function addShaped(route, def, realBase) {
@@ -348,7 +354,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
const key = `${route}~s${budget}`;
providers[key] = { ...def, displayName: `${def.displayName} (with your response settings)`, baseURL: `${proxyBase}/${key}/v1`, ...(budget ? { headers: { ...(def.headers ?? {}), 'x-strata-budget': String(budget) } } : {}) };
shapeTargets[key] = realBase;
for (const m of def.models) { const w = m.contextWindow, out = m.maxTokens; compaction.push({ provider: key, model: m.id, headroomTokens: compactionHeadroom(w, out), thresholdRatio: thresholdRatio() }); }
for (const m of def.models) addCompaction(key, m.id, m.contextWindow, m.maxTokens);
keys[budget] = key;
}
return keys;
@@ -383,7 +389,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
reasoningEfforts: isHy4Model ? HY4_LOCAL_EFFORTS : isInklingModel ? INKLING_LOCAL_EFFORTS : LOCAL_EFFORTS,
}],
};
compaction.push({ provider: route, model: inst.modelId, headroomTokens: compactionHeadroom(context, localOutputBudget(context)), thresholdRatio: thresholdRatio() });
addCompaction(route, inst.modelId, context, localOutputBudget(context));
slots = Math.max(slots, Number.isFinite(inst.slots) && inst.slots >= 1 ? Math.floor(inst.slots) : 1);
const shaped = addShaped(route, providers[route], inst.baseUrl);
routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', connectionName: 'this computer', instanceId: inst.id, modelId: inst.modelId, arch: inst.arch ?? null, name: inst.label || inst.modelId, contextWindow: context, vision: !!inst.vision, ...(shaped ? { shaped } : {}) });
@@ -432,7 +438,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
};
const fp = fingerprint(providers[route], conn.apiKey ?? '');
const shaped = ownServer ? addShaped(route, providers[route], baseURL) : null;
for (const m of conn.models) { const ctx = m.contextMax ?? ASSUMED_API_CONTEXT; compaction.push({ provider: route, model: m.id, headroomTokens: compactionHeadroom(ctx, reply(m)), thresholdRatio: thresholdRatio() }); }
for (const m of conn.models) addCompaction(route, m.id, m.contextMax ?? ASSUMED_API_CONTEXT, reply(m));
for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, connectionName: conn.name, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, ...(shaped ? { shaped } : {}) });
});
@@ -525,7 +531,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
...(mcp.length || ownRows.length ? [{ insert: [...mcp, ...ownRows] }] : []),
...webRows,
// The reminder tools would be a second scheduler beside the app's Tasks. The tool groups the person switched off in Settings -> Tools are left out.
{ id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir, compaction, modelNames: subagentRoutes.length > 0, skillTool: process.env.STRATA_AGENT_ALL_TOOLS === '1' || hasEnabledSkills(skillsDir) }) },
{ id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir, compaction, compactionLimits, modelNames: subagentRoutes.length > 0, skillTool: process.env.STRATA_AGENT_ALL_TOOLS === '1' || hasEnabledSkills(skillsDir) }) },
// Strata names its chats itself; the Harness's own title request would be an extra model call on
// every first prompt (and, for an API route, an unrequested one).
{ id: 'session-title-llm', disabled: true },
@@ -0,0 +1,69 @@
// Pressure compaction on a window the fixed part of an agent chat (system prompt + tools, about 10.5K tokens) nearly fills.
// At a 16K window compaction starts at 10,036 tokens, below that fixed part: every step started a compaction (a summary request that reads the
// conversation, then a rewritten history the engine reads again from the start). A range whose summary cannot bring the conversation under the
// limit is left alone. The scripted compaction service stands in for the Harness's.
import test from 'node:test';
import assert from 'node:assert/strict';
import { guardPressureCompaction } from '../server/agent/plugins/strata-compaction.mjs';
import { standardPreset } from '../server/agent/preset.mjs';
import { compactionThreshold, localOutputBudget } from '../server/agent/profile.mjs';
const limitOf = window => compactionThreshold(window, localOutputBudget(window));
function scripted({ total, nodes, provider = 'strata-local', model = 'inkling' }) {
const attempts = [];
const agent = { session: { requestHeader: () => ({ config: { provider, model } }) } };
const meter = { measure: () => ({ nodes, totalTokens: total() }) };
const compaction = {
async compactIfNeeded(owner, trigger, signal) { return this.compactRegion(nodes[0].seq, nodes.at(-1).seq, owner, signal); },
async compactRegion() { attempts.push('summary request'); return 'checkpoint'; },
};
return { agent, meter, compaction, attempts, compact: trigger => compaction.compactIfNeeded(agent, trigger, new AbortController().signal) };
}
test('the limits the profile writes: 16K starts below the fixed part, 32K and 128K leave room', () => {
assert.equal(limitOf(16384), 10036);
assert.equal(limitOf(32768), 20071);
assert.equal(limitOf(131072), 86016);
});
test('a range is left alone when the rest of the conversation already reaches the limit', async () => {
const limits = { 'strata-local': { inkling: limitOf(16384) } };
// 12,000 tokens in all: 1,500 in the range, 10,500 outside it (system prompt, tools, the newest steps)
const s = scripted({ total: () => 12000, nodes: [{ seq: 1, tokens: 600 }, { seq: 2, tokens: 900 }] });
guardPressureCompaction(s.compaction, s.meter, () => {}, limits);
assert.equal(await s.compact('pressure'), null);
assert.equal(await s.compact('pressure'), null, 'and the next step does not start another one');
assert.deepEqual(s.attempts, [], 'no summary request, so the engine keeps the conversation it holds');
assert.equal(await s.compact('context-overflow'), 'checkpoint', 'a real overflow keeps its recovery');
assert.deepEqual(s.attempts, ['summary request']);
});
test('a range that brings the conversation under the limit is still summarised', async () => {
const limits = { 'strata-local': { inkling: limitOf(32768) } };
// 20,200 tokens in all (over the 20,071 limit): 8,000 in the range, 12,200 outside it, under the limit once the range is a summary
const s = scripted({ total: () => 20200, nodes: [{ seq: 1, tokens: 3000 }, { seq: 2, tokens: 5000 }] });
guardPressureCompaction(s.compaction, s.meter, () => {}, limits);
assert.equal(await s.compact('pressure'), 'checkpoint');
assert.deepEqual(s.attempts, ['summary request']);
});
test('without a limit for the model, or without a measured total, nothing changes', async () => {
const none = scripted({ total: () => 50000, nodes: [{ seq: 1, tokens: 600 }, { seq: 2, tokens: 900 }] });
guardPressureCompaction(none.compaction, none.meter, () => {}, { 'strata-local': { other: 10036 } });
assert.equal(await none.compact('pressure'), 'checkpoint');
const unmeasured = scripted({ total: () => undefined, nodes: [{ seq: 1, tokens: 600 }, { seq: 2, tokens: 900 }] });
guardPressureCompaction(unmeasured.compaction, unmeasured.meter, () => {}, { 'strata-local': { inkling: 10036 } });
assert.equal(await unmeasured.compact('pressure'), 'checkpoint');
const old = scripted({ total: () => 50000, nodes: [{ seq: 1, tokens: 600 }, { seq: 2, tokens: 900 }] });
guardPressureCompaction(old.compaction, old.meter, () => {});
assert.equal(await old.compact('pressure'), 'checkpoint', 'the three-argument call of before');
});
test('the preset hands the limits to the compaction plugin and stays deterministic', () => {
const limits = { 'strata-local': { inkling: 10036 } };
const row = standardPreset({ compactionLimits: limits }).plugins.find(p => p.id === 'compaction').config.find(p => p.id === 'strata-compaction');
assert.deepEqual(row.config, { limits });
assert.equal(JSON.stringify(standardPreset({ compactionLimits: limits })), JSON.stringify(standardPreset({ compactionLimits: limits })));
assert.deepEqual(standardPreset().plugins.find(p => p.id === 'compaction').config.find(p => p.id === 'strata-compaction').config, { limits: {} });
});