perf(delivery): skip retaining failures that embed Evidence the ledger just refused (#16844)

When the retained representation allowance refuses completed Evidence,
the failure carries that Evidence inline as an unretained partial
observation, either as the capacity refusal itself or, after a cancel, as
the partial next to a capacity retention_error. Over the agent result
budget, budgetedFailure then hashed the whole failure and tried to record
it as mcp_tool_error Evidence. That record always failed: the failure
embeds the refused Evidence, so it needs more allowance than the record
the same ledger just refused. The reply was the same either way, and
after a cancel the client had already stopped waiting for it.

Skip the hash and the record attempt for both shapes. Replies stay
identical; both new tests fail without the matching condition because
the record callback is called once.

Refs #1065. The path came in with #15396.

🤖 Generated with Claude Code (Opus 5.5) 🦊

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cassie_FoxandClaude Opus 5.5 authored and GitHub committed 2026-12-04 18:13:12 -05:00
1 parent 7b1d1749e6
commit 486eab8477
2 files changed
+155 -2

No files matched your search

@@ -13,7 +13,11 @@ import {
AGENT_RESULT_BUDGET_ENVIRONMENT,
PARTIAL_OBSERVATION_DELIVERY,
} from "../domain/agentResultBudget.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
AnalysisResourceConstraintError,
cancelledBy,
OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import {
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
MAXIMUM_AGENT_RESULT_BUDGET_BYTES,
@@ -21,8 +25,9 @@ import {
/** In range, and far below the complete entropy Evidence. */
const VALID_SEED_BYTES = 8192;
import type { Evidence } from "../domain/evidence.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { err } from "../domain/result.js";
import { unknownTarget } from "../domain/targetIdentity.js";
import { McpToolRequest, runMcpToolRequest } from "./McpToolRequest.js";
import { ToolResultDelivery } from "./ToolResultDelivery.js";
import { measureMcpResultWithinBudget } from "./toolResultEncoding.js";
@@ -460,3 +465,122 @@ it("tells the caller not to repeat a retained call that had effects", async () =
"Do not repeat the completed call",
);
});
it("does not try to retain a refused-evidence capacity failure that is over the budget", () => {
const evidence = createEvidence(
unknownTarget("not-observed"),
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: contract.name,
parameters: {},
result: { filler: "x".repeat(256 * 1024) },
},
);
// An allowance too small for the analysis Evidence: the ledger refuses it
// and the refusal carries that Evidence unretained.
const ledger = new EvidenceLedger({ maximumRepresentationBytes: 64 * 1024 });
const refused = ledger.record(evidence);
expect(refused.ok).toBe(false);
const attempts: Evidence[] = [];
const request = new McpToolRequest(1, contract.name);
request.deliverySelection = {
detail: undefined,
pageable: true,
record: (value) => {
attempts.push(value);
return ledger.record(value);
},
};
const result = runMcpToolRequest(request, () =>
new ToolResultDelivery(64 * 1024 * 1024).toEvidenceToolResult(
evidence,
contract,
refused,
undefined,
(summary) => ledger.record(summary),
),
);
// The failure embeds the refused Evidence, so it could never fit where that
// Evidence did not: it is not hashed or offered to the ledger.
expect(attempts).toEqual([]);
expect(result.isError).toBe(true);
expect(result.content.map(({ type }) => type)).toEqual(["text"]);
const { error } = JSON.parse(
(result.content[0] as { text: string }).text,
) as {
readonly error: {
readonly code: string;
readonly details: Record<string, unknown>;
};
};
expect(error.code).toBe("resource_constraint");
expect(error.details).toMatchObject({
operation: "record_evidence",
resource: "capacity",
reason:
"The investigation's retained representation allowance is exhausted.",
reported_limits: { maximum_representation_bytes: 64 * 1024 },
});
// Delivered as before: the refused Evidence stays on the failure, unretained.
expect(error.details.partial_observation).toMatchObject({
kind: "unretained-evidence",
evidence: { evidence_id: evidence.evidence_id },
});
expect(ledger.statistics().evidenceRecords).toBe(0);
});
it("does not try to retain a cancelled call's failure whose over-budget partial the ledger refused", () => {
const partial = createEvidence(
unknownTarget("not-observed"),
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: contract.name,
parameters: {},
result: { filler: "x".repeat(256 * 1024) },
},
);
const ledger = new EvidenceLedger({ maximumRepresentationBytes: 64 * 1024 });
const attempts: Evidence[] = [];
const request = new McpToolRequest(1, contract.name);
request.deliverySelection = {
detail: undefined,
pageable: true,
record: (value) => {
attempts.push(value);
return ledger.record(value);
},
};
const result = runMcpToolRequest(request, () =>
new ToolResultDelivery(64 * 1024 * 1024).toPartialErrorToolResult(
cancelledBy(
contract.name,
OwnerCancellation.ownerClosed,
).retainPartialObservation(partial),
false,
(value) => ledger.record(value),
),
);
// The failure embeds the refused partial, so it could never fit where the
// partial did not: only the partial itself was offered to the ledger.
expect(attempts).toEqual([]);
expect(result.isError).toBe(true);
expect(result.content.map(({ type }) => type)).toEqual(["text"]);
const { error } = JSON.parse(
(result.content[0] as { text: string }).text,
) as {
readonly error: {
readonly code: string;
readonly details: Record<string, unknown>;
};
};
expect(error.code).toBe("cancelled");
expect(error.details.partial_observation).toMatchObject({
kind: "unretained-evidence",
evidence: { evidence_id: partial.evidence_id },
});
expect(error.details.retention_error).toMatchObject({
code: "resource_constraint",
details: { operation: "record_evidence", resource: "capacity" },
});
expect(ledger.statistics().evidenceRecords).toBe(0);
});
+29
View File
@@ -51,6 +51,7 @@ import {
failureEvidence,
} from "../domain/agentBudgetFailure.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
import { isRecord } from "../kernel/isRecord.js";
/** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */
export const mcpResponseOverflowProjection = (input: {
@@ -909,6 +910,33 @@ const budgetedPartialObservation = (
/** Bytes `{"error":}` adds around a projected failure on the wire. */
const ERROR_WRAPPER_BYTES = Buffer.byteLength('{"error":}');
/** A projected ledger refusal for want of retained representation allowance. */
const isRecordCapacityRefusal = (failure: unknown): boolean =>
isRecord(failure) &&
failure.code === "resource_constraint" &&
isRecord(failure.details) &&
failure.details.operation === "record_evidence" &&
failure.details.resource === "capacity";
/**
* A failure that carries completed Evidence the ledger refused for want of
* retained representation allowance and reports as unretained: the failure
* itself is that refusal, or the refusal is its `retention_error`. The failure
* embeds that Evidence, so the failure Evidence is larger than the record just
* refused and the same allowance refuses it.
*/
const isRefusedEvidenceCapacityFailure = (
projected: AnalysisErrorProjection,
): boolean => {
const partial = projected.details?.partial_observation;
return (
isRecord(partial) &&
partial.kind === "unretained-evidence" &&
(isRecordCapacityRefusal(projected) ||
isRecordCapacityRefusal(projected.details?.retention_error))
);
};
/**
* A failure whose wire text exceeds the agent result budget, retained whole
* as `mcp_tool_error` Evidence and replaced by its bounded summary, which
@@ -939,6 +967,7 @@ const budgetedFailure = (
const wire = { error: projected } as unknown as JsonValue;
if (jsonValueByteLength(wire, budget.bytes + 1) <= budget.bytes)
return undefined;
if (isRefusedEvidenceCapacityFailure(projected)) return undefined;
const evidence = failureEvidence("mcp", request.tool, wire);
if (!selection.record(evidence).ok) return undefined;
return {