Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(recall): page delivery fills budget_tokens (facts share first, delivered blocks costed as delivery counted)

garrytan8a1810008b92
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5010b056a..5ae3b1ef29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `search.reranker.gate` (off by default) grades search candidates before the cross-encoder. `shadow` records how often the reranker was paying for an answer retrieval already found, in the response's `rerank_gate` metadata, on `--explain` and in a new `rerank_gate` section of `gbrain search stats`, and leaves results unchanged. `on` skips the cross-encoder when the top result is a strong vector match (cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page); that skip is reported as `rerank_gate.skipped`, not as a degradation. The cache key now includes the gate keys and `search.evidence_cosine_floor`.
- `scripts/bench-rerank-gate-latency.ts` measures the gate's latency: recall plus query per question with the gate off and on, warm-up, alternating arm order and fixed concurrency, reporting the mean saving per skipped query and the p95 change.
- `search.page_rank_budget_ratio` (off by default) lets a `return_unit: "page"` call's own budget size the ranked hit list. Today ranking cuts hits to the mode's `search.tokenBudget` whatever the caller asked for, so under tokenmax delivery is handed far more pages than fit and returns them as slivers. With a ratio set, `search`, `query` and `recall` cut to `min(mode cut, ratio × caller budget)` and report it as `page_rank_cut`. Calls without a budget and other units are unchanged.
+- `recall` with `return_unit` and `budget_tokens` fills its budget. Delivery used to be sized to the whole budget, and the facts-first packer then dropped whole delivered blocks. It also re-costed those blocks with a chars/4 estimate while delivery had counted cl100k tokens, so even a call with no facts came back about 7% short. Delivery now gets what the facts leave (except under `query_first`), and delivered blocks cost what delivery counted.
## [0.60.169.0] - 2026-10-11
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index aba60adec2..dbbc71e62c 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -103,6 +103,11 @@ Per-call params on `search`, `query`, `recall`:
`query`'s `token_budget` still prunes chunks (chunk mode), and `recall`'s
`budget_tokens` / `budget_policy` still pack chunks (facts first), so any of
them keeps an implied `auto` on `chunk`.
+- `recall` with a unit and `budget_tokens` packs saved facts first (unless
+ `budget_policy` is `query_first`). Delivery gets the budget the facts leave,
+ and each delivered block costs what delivery counted (text and title, in
+ `delivery.tokenizer`), so the facts and blocks together fill
+ `budget_tokens` and no delivered block is dropped afterwards.
- Page-unit ranking cut (off by default): ranking cuts its hits to the search
mode's `search.tokenBudget` (4,000 under conservative, none under tokenmax)
before delivery packs whole pages, whatever the caller's budget. With
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 97b2763203..2d51e09314 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -2,7 +2,7 @@ import { searchAnswerFeedback } from '../feedback/record.ts';
import { parseRelationalPlan } from '../search/relational-plan.ts';
import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
-import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
+import { countEvidenceTokens, deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
import { withFactDateHeaders } from '../search/evidence-date.ts';
import { randomUUID } from 'node:crypto';
import { readHolders } from './context.ts';
@@ -201,9 +201,29 @@ function packingArm<T>(candidates: T[], kept: T[], cost: (item: T) => number) {
return { candidates: candidates.length, kept: kept.length, dropped: candidates.length - kept.length, used: kept.reduce((sum, r) => sum + cost(r), 0) };
}
+/**
+ * A result row's cost in recall's packing. A delivered block costs what delivery counted (its text and title in
+ * delivery's tokenizer), so recall never re-cuts a set delivery already fit using a different estimator.
+ */
+function recallResultCost(delivery: DeliveryMeta | undefined): (r: SearchResult) => number {
+ if (!delivery) return resultTokens;
+ return r => r.delivered ? r.delivered.tokens + countEvidenceTokens(r.title ?? '', delivery.tokenizer) : resultTokens(r);
+}
+
+/**
+ * Facts pack first under a budget (every policy but query_first), so delivery gets only what they leave.
+ * Sized to the whole budget, delivery filled it and recall then dropped whole delivered blocks after the facts.
+ * Null when the facts leave nothing: delivery is skipped and the results arm packs empty.
+ */
+function recallDeliveryPlan(plan: EvidencePlan | null, policy: unknown, queryText: string | null, budgetTokens: number | null, rows: Array<{ fact: string }>): EvidencePlan | null {
+ if (!plan || budgetTokens === null || (policy === 'query_first' && queryText !== null)) return plan;
+ const left = Math.min(plan.budgetTokens, budgetTokens - packToBudget(rows, r => estimateTokens(r.fact), budgetTokens).meta.used);
+ return left > 0 ? { ...plan, budgetTokens: left } : null;
+}
+
/** recall's budget_packing meta: only policy-supplied calls carry it. */
function recallBudgetPacking<F extends { fact: string }>(policy: unknown, queryText: string | null, budgetTokens: number | null,
- arms: { rows: F[]; packedFacts: F[]; searchResults: SearchResult[]; packedResults: SearchResult[] }) {
+ arms: { rows: F[]; packedFacts: F[]; searchResults: SearchResult[]; packedResults: SearchResult[] }, resultCost: (r: SearchResult) => number) {
if (policy !== 'facts_first' && policy !== 'query_first') return undefined;
const queryFirst = policy === 'query_first' && queryText !== null && budgetTokens !== null;
const { rows, packedFacts, searchResults, packedResults } = arms;
@@ -217,7 +237,7 @@ function recallBudgetPacking<F extends { fact: string }>(policy: unknown, queryT
: packedFacts.length + packedResults.length === 0 ? 'first_items_exceed_budget'
: 'packed',
facts: packingArm(rows, packedFacts, r => estimateTokens(r.fact)),
- results: packingArm(searchResults, packedResults, resultTokens),
+ results: packingArm(searchResults, packedResults, resultCost),
};
}
@@ -507,7 +527,7 @@ const recall: Operation = {
});
}
bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));
- const applied = effectivePlan(evidencePlan, searchResults);
+ const applied = recallDeliveryPlan(effectivePlan(evidencePlan, searchResults), p.budget_policy, queryText, budgetTokens, rows);
if (applied) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, applied, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));
searchResults = await stampPageTrust(ctx.engine, searchResults, eligibility.floor);
}
@@ -524,7 +544,7 @@ const recall: Operation = {
const queryFirst = p.budget_policy === 'query_first' && queryText !== null && budgetTokens !== null;
if (queryFirst) {
const resultsPack = budgetTokens > 0
- ? packToBudget(searchResults, resultTokens, budgetTokens)
+ ? packToBudget(searchResults, recallResultCost(delivery), budgetTokens)
: { items: [] as SearchResult[], meta: { used: 0, dropped: searchResults.length } };
packedResults = resultsPack.items;
const remaining = budgetTokens - resultsPack.meta.used;
@@ -540,14 +560,14 @@ const recall: Operation = {
const remaining = budgetTokens - factsPack.meta.used;
const resultsPack =
remaining > 0
- ? packToBudget(searchResults, resultTokens, remaining)
+ ? packToBudget(searchResults, recallResultCost(delivery), remaining)
: { items: [] as SearchResult[], meta: { budget: 0, used: 0, dropped: searchResults.length, kept: 0 } };
packedResults = resultsPack.items;
budgetUsed = factsPack.meta.used + resultsPack.meta.used;
droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;
}
- const budgetPacking = recallBudgetPacking(p.budget_policy, queryText, budgetTokens, { rows, packedFacts, searchResults, packedResults });
+ const budgetPacking = recallBudgetPacking(p.budget_policy, queryText, budgetTokens, { rows, packedFacts, searchResults, packedResults }, recallResultCost(delivery));
return {
facts: await withFactDateHeaders(ctx.engine, await stampRowTrust(ctx.engine, 'facts', packedFacts.map(r => ({ // #5575 A6: + trust_tier, origin, unconfirmed
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 745eec610f..3f50385367 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -106,6 +106,7 @@ test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
test/purge-fact.test.ts
test/purge-global-marker.test.ts
+test/recall-page-fill.test.ts
test/remediation-manual-only.test.ts
test/repair-embedding-effects.test.ts
test/repair-failed-writes-conflict-6429.test.ts
diff --git a/test/recall-page-fill.test.ts b/test/recall-page-fill.test.ts
new file mode 100644
index 0000000000..a4d5cd4135
--- /dev/null
+++ b/test/recall-page-fill.test.ts
@@ -0,0 +1,98 @@
+/**
+ * recall with `return_unit` and `budget_tokens` fills its budget.
+ *
+ * Protects: under facts_first (the default packing), delivery gets the budget
+ * the facts leave, and recall's packer costs delivered blocks the way delivery
+ * counted them, so no delivered block is dropped after the facts and
+ * `budget_used` lands within one block-title of the budget. query_first still
+ * hands delivery the whole budget.
+ * Fails when: delivery is sized to the whole budget under facts_first (recall
+ * then drops whole tail blocks), or recall re-costs delivered blocks with the
+ * chars/4 heuristic while delivery counted cl100k (blocks dropped with no
+ * facts at all). Before the fix: 7,426 of 8,000 with no facts, 7,740 with 40.
+ * Seams: keyword-only (embeddings off), synthetic conversation pages and
+ * facts; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { estimateTokens } from '../src/core/search/token-budget.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const BUDGET = 8000;
+const turn = (i: number, k: number) => `user: about the garden trip ${i} turn ${k}, we talked about tomatoes and the hiking plan.\n`
+ + `assistant: noted the garden trip detail ${k} for session ${i} and the weekend schedule.\n`;
+
+for (const backend of testBackends()) {
+ describe(`${backend}: recall page delivery fills budget_tokens`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void> = async () => {};
+ const ctx = () => ({ engine, config: { engine: backend, embedding_disabled: true }, remote: false, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} }, emitResponseMeta() {} }) as unknown as OperationContext;
+ const recall = (params: Record<string, unknown>) => operationsByName.recall.handler(ctx(), {
+ question: 'What did I say about the garden trip?', query: 'garden trip tomatoes', limit: 100, budget_tokens: BUDGET, return_unit: 'page', ...params,
+ }) as Promise<any>;
+
+ beforeAll(async () => {
+ if (backend === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ } else {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine;
+ close = pg.close;
+ }
+ for (let i = 0; i < 40; i++) {
+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `chat/session-${i}`,
+ content: `---\ntype: conversation\ntitle: Session ${i}\n---\n` + Array.from({ length: 10 + (i * 7) % 40 }, (_, k) => turn(i, k)).join('') } });
+ }
+ }, 180_000);
+
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await close();
+ });
+
+ test('no facts: delivered blocks are costed as delivery counted them, none dropped', async () => {
+ const out = await recall({ budget_policy: 'facts_first' });
+ expect(out.facts).toEqual([]);
+ expect(out.delivery.budget_tokens).toBe(BUDGET);
+ expect(out.budget_packing.results.dropped).toBe(0);
+ expect(out.budget_used).toBe(out.delivery.budget_used);
+ expect(out.budget_used).toBeGreaterThan(BUDGET * 0.98);
+ expect(out.budget_used).toBeLessThanOrEqual(BUDGET);
+ });
+
+ test('facts_first: delivery gets what the facts leave and the budget fills', async () => {
+ for (let i = 0; i < 40; i++) {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, created_at, source)
+ VALUES ('default', NULL, $1, 'fact', 'world', now(), now(), 'test')`,
+ [`The user mentioned the garden trip detail number ${i} about tomatoes and hiking on the weekend.`]);
+ }
+ for (const policy of ['facts_first', undefined]) {
+ const out = await recall(policy ? { budget_policy: policy } : {});
+ const factsUsed = out.facts.reduce((n: number, f: { fact: string }) => n + estimateTokens(f.fact), 0);
+ expect(out.facts.length).toBe(40);
+ expect(out.delivery.budget_tokens).toBe(BUDGET - factsUsed);
+ expect(out.dropped_count).toBe(0);
+ expect(out.budget_used).toBe(factsUsed + out.delivery.budget_used);
+ expect(out.budget_used).toBeGreaterThan(BUDGET * 0.98);
+ expect(out.budget_used).toBeLessThanOrEqual(BUDGET);
+ }
+ });
+
+ test('query_first: delivery still gets the whole budget and facts take the rest', async () => {
+ const out = await recall({ budget_policy: 'query_first' });
+ expect(out.delivery.budget_tokens).toBe(BUDGET);
+ expect(out.budget_packing.results.dropped).toBe(0);
+ expect(out.budget_used).toBeLessThanOrEqual(BUDGET);
+ });
+ });
+}