LibreChat/api/server/controllers/agents/__tests__/client.contextMetadata.spec.js
Marco Beretta e95e696d70
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
🧾 fix: Count the Tool Results a Tool-Limit Stop Retains (#15893)
* 🧾 fix: Count the Tool Results a Tool-Limit Stop Retains

Context snapshots reach the client only through the SDK's pre-invoke
`ON_CONTEXT_USAGE`, so the results of the tools a call requests are never in that
call's snapshot — the next call's snapshot carries them as kept-message context.
A run that stops at the tool-call limit makes no next call, so the tool result it
retains lives in the response and in no snapshot: the gauge reported
`(budget − remaining) + completedOutputTokens` and left the retained result out
of used tokens and out of the tool-call share until the following turn.

The save path now counts those results with the run's own tokenizer and persists
them as `retainedToolTokens`, a second post-snapshot delta alongside
`completedOutputTokens` rather than a number folded into the provider-reconciled
`messageTokens`. `resolveRetainedToolTokens` owns the rule that only a tool-limit
stop retains anything, and the snapshot handler records where its content ended
so the count starts at the right boundary.

Counting had to avoid `Tokenizer.getTokenCount`, whose fallbacks would have put a
guess inside exact accounting: above 4 KiB it returns byte length, several times
the real count on ordinary text, and it estimates from character length while an
encoding loads. `countExactTokens` tokenizes in bounded slices cut on code-point
boundaries and returns nothing at all when the encoding is cold, so an
uncountable result withdraws the figure instead of inflating it.

The client adds the field to used tokens, subtracts it from the runway headroom
and widens the tool-call share, in the live snapshot after finalization and in
the persisted blob after a reload.

* 🧹 style: Wrap the Retained-Counter Assertion as Prettier Requires

* 🧮 fix: Address the Review of the Retained-Tool Count

Three findings from the first round, each a real defect in how the figure was
produced rather than a style point.

The boundary was a content index recorded mid-run, but completion reshapes the
array — skill cards are unshifted onto the front and `hide_sequential_outputs`
replaces it with a filtered one — so a saved index no longer means the same
position. The snapshot now records the tool-call ids it already accounts for, and
the save path counts the results of the calls missing from that set: ids survive
every reshape, and a filtered-away call is correctly left out.

Counting in 4 KiB slices was not exact either: a BPE merge spanning a seam is
charged twice, measured at ~1 token per slice, and the field exists precisely to
be an exact addend. `countExactTokens` now tokenizes the whole input — ~60 ms/MB,
paid once at the end of a stopped turn — and refuses content past 8 MiB rather
than estimating it.

The counter takes its exact-count function instead of reaching for the tokenizer
singleton, so `resolveRetainedToolTokens` owns the default (the run's own
encoding) and a caller or test can supply another. That also removes the mock of
global state from the specs.

`compactionReclaim` now includes the retained result in the total it subtracts the
kept exchange from. `latestExchangeTokens` already counts that result on the
other side, so leaving it out subtracted content the total never carried and
understated the savings — to zero on a large final result.

* 🧯 fix: Bound One Turn's Retained-Result Tokenization

The tokenizer refuses a single result past 8 MiB, but a final call that requested
several tools in parallel would pay that bound once per result. The counter now
holds a budget for the whole turn and withdraws its figure past it, so the save
path cannot be made to tokenize an unbounded pile of output.

* 🎚️ feat: Configure the Retained-Result Tokenization Budget

The exact count the gauge adds costs ~60 ms/MB of retained tool output, and the
ceiling on that work was hard-coded in two places. It is now one lever:
`endpoints.agents.maxRetainedToolCountChars`, defaulting to the 8 MiB that
reproduces today's behavior, shared by the schema and the save path through
`DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS`. Deployments whose tools legitimately
return more can raise it; slower hardware can lower it, or set `0` to withhold
the figure entirely.

`Tokenizer.countExactTokens` no longer carries a bound of its own — the caller
owns the budget — and `resolveRetainedToolTokens` passes the configured value to
the counter, which spends it across all of a final call's parallel results.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-13 22:20:25 -04:00

221 lines
8.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** The counting itself is exercised in packages/api (it needs a loaded encoding,
* which this environment cannot load); here the resolver stands in so the WIRING
* is pinned: which content the save path hands it, and where its figure lands. */
const mockResolveRetainedToolTokens = jest.fn();
jest.mock('@librechat/api', () => ({
...jest.requireActual('@librechat/api'),
resolveRetainedToolTokens: (...args) => mockResolveRetainedToolTokens(...args),
}));
const AgentClient = require('../client');
/** Minimal post-(maybe-)summary snapshot. baseUsed = maxContextTokens(1000) -
* remainingContextTokens(700) = 300, so the marker (summaryUsedTokens) is 300. */
const snapshot = (summaryTokens) => ({
runId: 'run-1',
agentId: 'agent-1',
breakdown: {
maxContextTokens: 1000,
instructionTokens: 50,
systemMessageTokens: 50,
dynamicInstructionTokens: 0,
toolSchemaTokens: 0,
summaryTokens,
toolCount: 0,
messageCount: 1,
messageTokens: 20,
availableForMessages: 900,
},
contextBudget: 1000,
remainingContextTokens: 700,
prePruneContextTokens: 300,
effectiveInstructionTokens: 50,
calibrationRatio: 1,
});
const primary = { input_tokens: 10, output_tokens: 5, total_tokens: 15 };
const summarizationUsage = { ...primary, usage_type: 'summarization' };
const primaryFor = (runId, output_tokens) => ({
input_tokens: 10,
output_tokens,
total_tokens: 10 + output_tokens,
provider: 'openAI',
runId,
});
const toolPart = (id, name, output) => ({
type: 'tool_call',
tool_call: { id, name, args: '{"path":"a"}', output },
});
function buildMeta({
snap,
latestUsageIndex,
usageEvents,
stepLimitReached = false,
latestToolCallIds,
contentParts,
maxRetainedToolCountChars,
}) {
const self = {
collectedThoughtSignatures: null,
usageEmitSink: usageEvents,
stepLimitReached,
contentParts,
getEncoding: () => 'o200k_base',
options: {
req: { config: { endpoints: { agents: { maxRetainedToolCountChars } } } },
},
contextUsageSink: snap
? { latest: snap, count: 1, latestUsageIndex, latestToolCallIds }
: { latest: null, count: 0 },
};
return AgentClient.prototype.buildResponseMetadata.call(self);
}
describe('AgentClient.buildResponseMetadata — snapshot persistence + summary marker', () => {
beforeEach(() => {
mockResolveRetainedToolTokens.mockReset();
});
it('persists the snapshot when a primary usage follows it (normal turn)', () => {
const meta = buildMeta({ snap: snapshot(0), latestUsageIndex: 0, usageEvents: [primary] });
expect(meta.contextUsage).toBeDefined();
expect(meta.summaryUsedTokens).toBeUndefined();
});
it('persists the post-summary snapshot when the only pre-primary usage is the summarization', () => {
/** A summarized turn: the summarization usage precedes the post-summary
* snapshot (index 1), then the model's primary usage follows it. The old
* count guard miscounted and dropped this; the new guard keeps it. The
* marker subtracts the summarization output (5): the generated summary is in
* the snapshot baseline (summaryTokens) AND the response tokenCount, so
* 300 − 5 = 295 keeps the client estimate from counting it twice. */
const meta = buildMeta({
snap: snapshot(80),
latestUsageIndex: 1,
usageEvents: [summarizationUsage, primary],
});
expect(meta.contextUsage).toBeDefined();
expect(meta.summaryUsedTokens).toBe(295);
});
it('still emits the summary marker when the final call emitted no usage', () => {
/** Interrupted summarized turn: no primary usage follows the latest snapshot,
* so the snapshot is (correctly) not persisted — but the coarse marker
* survives so the client estimate still caps the discarded history. The
* summarization output (5) is subtracted (300 − 5 = 295). */
const meta = buildMeta({
snap: snapshot(80),
latestUsageIndex: 1,
usageEvents: [summarizationUsage],
});
expect(meta.contextUsage).toBeUndefined();
expect(meta.summaryUsedTokens).toBe(295);
});
it('drops the snapshot and emits no marker when the final call had no usage and no summary', () => {
const meta = buildMeta({ snap: snapshot(0), latestUsageIndex: 1, usageEvents: [primary] });
expect(meta.contextUsage).toBeUndefined();
expect(meta.summaryUsedTokens).toBeUndefined();
});
it('does not persist the snapshot when only a parallel run produced post-snapshot usage', () => {
/** A snapshot (run-1) → B snapshot (run-1 is latest) but the only following
* usage belongs to a sibling run (run-2). The guard must NOT persist run-1's
* snapshot with run-2's output — it falls back to the per-message estimate. */
const meta = buildMeta({
snap: snapshot(0),
latestUsageIndex: 0,
usageEvents: [primaryFor('run-2', 99)],
});
expect(meta.contextUsage).toBeUndefined();
});
it('persists with the snapshot run output when its own primary usage follows', () => {
const meta = buildMeta({
snap: snapshot(0),
latestUsageIndex: 0,
usageEvents: [primaryFor('run-2', 99), primaryFor('run-1', 7)],
});
expect(meta.contextUsage).toBeDefined();
expect(meta.contextUsage.completedOutputTokens).toBe(7);
});
it('subtracts earlier tool-loop output from the summary marker (interrupted turn)', () => {
/** Multi-call summarized turn stopped before the final usage: the earlier
* call (output 40) is baked into baseUsed (300), so the marker is 300 − 40 =
* 260. No primary follows the snapshot, so the full snapshot is not persisted
* and the client uses this marker — which must not double-count the 40 that
* the response tokenCount also carries. */
const meta = buildMeta({
snap: snapshot(80),
latestUsageIndex: 1,
usageEvents: [primaryFor('run-1', 40)],
});
expect(meta.contextUsage).toBeUndefined();
expect(meta.summaryUsedTokens).toBe(260);
});
it('subtracts only this run’s earlier output, not a parallel run’s', () => {
const meta = buildMeta({
snap: snapshot(80),
latestUsageIndex: 2,
usageEvents: [primaryFor('run-2', 999), primaryFor('run-1', 40), primaryFor('run-1', 5)],
});
/** baseUsed 300 − run-1's earlier 40 = 260; run-2's 999 is ignored. */
expect(meta.summaryUsedTokens).toBe(260);
/** run-1's own primary follows the snapshot → snapshot persisted with output 5. */
expect(meta.contextUsage.completedOutputTokens).toBe(5);
});
/** A turn that stops at the tool-call limit keeps the results of the tools its
* final call ran. The snapshot describing that call precedes them and no further
* call is made, so the counted figure has to ride along or the client's gauge
* misses the retained result until the next turn. */
it('hands the resolver this snapshot’s call boundary and persists its figure', () => {
mockResolveRetainedToolTokens.mockReturnValue(180);
const contentParts = [
toolPart('call_1', 'grep', 'the result the snapshot already counts'),
toolPart('call_2', 'read_file', 'the retained result'),
];
const latestToolCallIds = new Set(['call_1']);
const meta = buildMeta({
snap: snapshot(0),
latestUsageIndex: 0,
usageEvents: [primary],
stepLimitReached: true,
latestToolCallIds,
contentParts,
maxRetainedToolCountChars: 1_048_576,
});
expect(mockResolveRetainedToolTokens).toHaveBeenCalledWith({
stoppedAtToolLimit: true,
contentParts,
/** The calls the snapshot already saw; only the rest are retained. */
priorToolCallIds: latestToolCallIds,
encoding: 'o200k_base',
/** The deployment's ceiling on the tokenization this costs. */
maxCountChars: 1_048_576,
});
expect(meta.contextUsage.retainedToolTokens).toBe(180);
});
it('reports a turn that did not stop at the tool-call limit as such', () => {
mockResolveRetainedToolTokens.mockReturnValue(undefined);
const meta = buildMeta({
snap: snapshot(0),
latestUsageIndex: 0,
usageEvents: [primary],
latestToolCallIds: new Set(),
contentParts: [toolPart('call_1', 'read_file', 'a result the next call re-counted')],
});
expect(mockResolveRetainedToolTokens).toHaveBeenCalledWith(
expect.objectContaining({ stoppedAtToolLimit: false }),
);
/** Nothing to add, so the blob stays exactly as it was before this change. */
expect(Object.prototype.hasOwnProperty.call(meta.contextUsage, 'retainedToolTokens')).toBe(
false,
);
});
});