Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): W5 page cut on by default (whole_pages, factor 1.5)

garrytane9b59f29b635
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e04a77d311..25205989c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,12 +12,12 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased] - memory proof wave 2 W3 + W5, confidence-gated reranking and the page-unit ranking cut (#6445)
-**Search can grade its candidates before the cross-encoder and report how often the reranker was paying for an answer retrieval already found, and a page-unit call's own budget can size its ranked hits. Both are off by default, and the grade never changes results.**
+**A page-unit call with its own budget now gets whole pages that fill that budget instead of many partial ones, and search can grade its candidates before the cross-encoder to report how often the reranker was paying for an answer retrieval already found. The page cut is on by default (`gbrain config set search.page_rank_cut off` restores the old path); the grade is off by default and never changes results.**
### Itemized changes
- `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. A grade is strong when the top result is a vector match with cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page. There is no skip mode: on the dev sets no question reached the 0.8 floor with voyage-4 embeddings, and the reranker changed about half the delivered tokens, so skipping it is not shipped. The cache key now includes the gate keys and `search.evidence_cosine_floor`.
-- `search.page_rank_cut: whole_pages` (off by default) lets a `return_unit: "page"` call's own budget decide how many pages delivery gets. Today ranking cuts hits by chunk tokens to the mode's `search.tokenBudget` whatever the caller asked for: under tokenmax delivery is handed far more pages than fit and returns them as slivers, and under a mode cut small pages under-fill the budget. With `whole_pages`, `search`, `query` and `recall` lift the mode cut, and delivery keeps ranked pages while their whole delivered size fits the budget (times `search.page_rank_cut_factor`, default 1.0), reporting `delivery.page_rank_cut`. Calls without a budget and other units are unchanged.
+- `search.page_rank_cut` (default `whole_pages`) lets a `return_unit: "page"` call's own budget decide how many pages delivery gets. Before, ranking cut hits by chunk tokens to the mode's `search.tokenBudget` whatever the caller asked for: under tokenmax delivery was handed far more pages than fit and returned them as slivers, and under a mode cut small pages under-filled the budget. Now `search`, `query` and `recall` lift the mode cut, and delivery keeps ranked pages while their whole delivered size fits `search.page_rank_cut_factor` (default 1.5) × the budget, reporting `delivery.page_rank_cut`. Calls without a budget and other units are unchanged. On 72 BEAM conversations it was non-inferior to the cut off: −0.25 points, lower bound −1.00 against a −3 margin, with delivered context at budget. Those conversations are regression evidence, not a held-out test, and the 1.5 factor was picked under a rule amended after the dev results ([gbrain-evals #126 results](https://github.com/garrytan/gbrain-evals/blob/8b764e3e/docs/benchmarks/2026-10-13-memory-proof-wave-2-results.md)).
- `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.194.0] - 2026-10-13
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 8d0de8fdb1..3ce7083f53 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.
- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.
-- `src/core/search/page-rank-cut.ts` — W5 page-unit ranking cut (default off): with `return_unit: page`, a caller budget and `search.page_rank_cut: whole_pages`, `resolveEvidencePlan` stores `rankCut` (`{mode, factor, caller_budget}`, factor from `search.page_rank_cut_factor`, default 1.0) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `liftModeCut` drops the mode's chunk-token `tokenBudget` in both the inner request and the cache resolver (`tb=` is in the knobs hash). Delivery applies the cut: `cutWholePages` (this file, pure) keeps rank-order pages while their whole delivered cost (evidence-delivery.ts `wholeCost`: floor plus every enrichment piece within the block char cap) fits `factor × the shared budget`, keeps the crossing page only when its floor fits what is left, and drops the rest as `rank_cut`. `delivery.page_rank_cut` reports mode, factor, caller budget, target, applied cost, candidates and kept. Tests: `test/search/page-rank-cut.test.ts` (both engines).
+- `src/core/search/page-rank-cut.ts` — W5 page-unit ranking cut (on by default; `search.page_rank_cut off` disables it): with `return_unit: page` and a caller budget, `resolveEvidencePlan` stores `rankCut` (`{mode, factor, caller_budget}`, factor from `search.page_rank_cut_factor`, default 1.5) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `liftModeCut` drops the mode's chunk-token `tokenBudget` in both the inner request and the cache resolver (`tb=` is in the knobs hash). Delivery applies the cut: `cutWholePages` (this file, pure) keeps rank-order pages while their whole delivered cost (evidence-delivery.ts `wholeCost`: floor plus every enrichment piece within the block char cap) fits `factor × the shared budget`, keeps the crossing page only when its floor fits what is left, and drops the rest as `rank_cut`. `delivery.page_rank_cut` reports mode, factor, caller budget, target, applied cost, candidates and kept. Tests: `test/search/page-rank-cut.test.ts` (both engines).
- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.
- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index d894e976ad..9fa168e109 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -108,23 +108,28 @@ Per-call params on `search`, `query`, `recall`:
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 by chunk
- tokens against the search mode's `search.tokenBudget` (4,000 under
- conservative, none under tokenmax), whatever the caller's budget, so under
- tokenmax delivery is handed more pages than it can deliver whole (slivers)
- and under a mode cut small pages under-fill the budget. With
- `gbrain config set search.page_rank_cut whole_pages`, a `return_unit:
- "page"` call that passes its own budget on `search`, `query` or `recall`
- lifts the mode cut and delivery walks the ranked pages, costing each at what
- it would deliver whole (text, title and date header in
- `delivery.tokenizer`, within the block char cap). It stops once they fill
- `search.page_rank_cut_factor` (default 1.0) × the budget the pages share;
- the page that crosses it stays only if its matching span still fits what
- the whole pages before it leave. Later pages are dropped as `rank_cut`.
- `delivery.page_rank_cut` reports `mode`, `factor`, `caller_budget`,
- `target`, `applied_cost` (the kept pages' whole cost), `candidates` and
- `kept`. A page call without a budget and every other unit are unchanged.
- `gbrain config unset search.page_rank_cut` turns it off.
+- Page-unit ranking cut (`search.page_rank_cut`, default `whole_pages`). A
+ `return_unit: "page"` call that passes its own budget on `search`, `query`
+ or `recall` lifts the search mode's chunk-token cut (`search.tokenBudget`:
+ 4,000 under conservative, none under tokenmax), and delivery walks the
+ ranked pages, costing each at what it would deliver whole (text, title and
+ date header in `delivery.tokenizer`, within the block char cap). It stops
+ once they fill `search.page_rank_cut_factor` (default 1.5) × the budget the
+ pages share; the page that crosses it stays only if its matching span still
+ fits what the whole pages before it leave, and later pages are dropped as
+ `rank_cut` (so a short page ranked after one that cannot be delivered even
+ in part is not reached). Without the cut, a mode cut under-filled the budget
+ on small pages, and tokenmax handed delivery more pages than it could
+ deliver whole, so each arrived as a sliver. `delivery.page_rank_cut`
+ reports `mode`, `factor`, `caller_budget`, `target`, `applied_cost` (the
+ kept pages' whole cost), `candidates` and `kept`. A page call without a
+ budget and every other unit are unchanged.
+ `gbrain config set search.page_rank_cut off` restores the old path.
+ Evidence: on 72 BEAM conversations the cut at 1.5 was non-inferior to the
+ cut off (−0.25 points, lower bound −1.00 against a −3 margin) with
+ delivered context at budget. Those conversations are regression evidence,
+ not a held-out test, and 1.5 was picked under a rule amended after the dev
+ results ([gbrain-evals #126, wave 2 results](https://github.com/garrytan/gbrain-evals/blob/8b764e3e/docs/benchmarks/2026-10-13-memory-proof-wave-2-results.md)).
Think reads `think.return_unit` (default `auto`) and never
`search.return_unit`, so changing search's default does not change `think`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1b385c396b..ba79270973 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -523,6 +523,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// W3 confidence-gated reranking (memory proof wave 2). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.194.0', text: '`gbrain search stats --json` and the `search_stats` tool now always include a `rerank_gate` section, all zeros until you set `search.reranker.gate` to `shadow`; search results and ranking are unchanged. The search cache key now includes `search.evidence_cosine_floor` and the new gate keys (the result cache stays disabled).' },
{ since: '0.60.194.0', text: '`recall` with `budget_tokens` and a `return_unit` now fills its budget: saved facts are packed first and the delivered evidence gets the budget they leave, so the same parameters return more evidence (up to about 16% more on long conversations). Before, delivered blocks were dropped after the facts and re-counted with a rougher estimate. `budget_policy: "query_first"` is unchanged.' },
+ // W5 adaptive page-unit cut, default on after memory proof wave 2 (gbrain-evals #126). `since` is the VERSION placeholder.
+ { since: '0.60.194.0', text: 'A `return_unit: "page"` call that passes its own budget (`token_budget` on `search` and `query`, `budget_tokens` on `recall`) now stops adding pages once their whole delivered pages fill 1.5 times that budget (`search.page_rank_cut: whole_pages`, `search.page_rank_cut_factor: 1.5`), and the search mode\'s chunk-token cut no longer limits it: you get fewer pages, more of them whole, filling the budget, instead of many partial ones. On 72 BEAM conversations (regression evidence, not held-out) accuracy moved -0.25 points against the cut off (lower bound -1.00, non-inferior at the -3 margin) with delivered context at budget. The response reports it as `delivery.page_rank_cut`. `gbrain config set search.page_rank_cut off` restores the old behavior.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index fff79d504d..b80bd28d2d 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1419,8 +1419,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.entity_anchoring', // entity-anchored retrieval for entity-scoped current-state query/search (default off; search/entity-anchor.ts)
'search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)
'search.temporal_fact_reserve', // temporal-cue queries reserve up to 15% of the token budget for question-ranked dated facts (default off; search/facts-arm.ts)
- 'search.page_rank_cut', // W5: off | whole_pages — page unit + caller token_budget stops adding pages once their whole pages fill the budget (default off; search/page-rank-cut.ts)
- 'search.page_rank_cut_factor', // W5: whole_pages target = factor x the budget (default 1.0)
+ 'search.page_rank_cut', // W5: whole_pages (default) | off — page unit + caller token_budget stops adding pages once their whole pages fill factor x the budget (search/page-rank-cut.ts)
+ 'search.page_rank_cut_factor', // W5: whole_pages target = factor x the budget (default 1.5)
'think.return_unit',
'think.pages_budget_chars', // #5461: total chars for the synthesize pages block (4000-200000, default 12000; soft: the 600-char floor wins); think/pages-budget.ts
'think.excerpt_ceiling_chars', // #5461: per-page excerpt cap for the synthesize pages block (600-200000, default 2400); think/pages-budget.ts
diff --git a/src/core/search/page-rank-cut.ts b/src/core/search/page-rank-cut.ts
index 4ee289e480..b98147a9fd 100644
--- a/src/core/search/page-rank-cut.ts
+++ b/src/core/search/page-rank-cut.ts
@@ -6,9 +6,10 @@
* mode's `search.tokenBudget` (4000 conservative, none under tokenmax). Under
* tokenmax delivery was handed far more pages than it could deliver whole, and
* each arrived as a sliver; under a mode cut, small pages under-filled the
- * budget. `search.page_rank_cut: whole_pages` (default off) instead stops
- * adding page candidates once their whole delivered pages fill
- * `factor x caller budget` (`search.page_rank_cut_factor`, default 1.0).
+ * budget. `search.page_rank_cut: whole_pages` (the default; `off` restores the
+ * old path) instead stops adding page candidates once their whole delivered
+ * pages fill `factor x caller budget` (`search.page_rank_cut_factor`, default
+ * 1.5, picked on memory proof wave 2 dev).
*
* Ranking lifts the mode's chunk-token cut for such a call (`liftModeCut`), so
* a mode cut can never under-fill the budget, and delivery applies the cut
@@ -20,7 +21,7 @@ import type { ResolvedSearchKnobs } from './mode.ts';
export const PAGE_RANK_CUT_KEY = 'search.page_rank_cut';
export const PAGE_RANK_CUT_FACTOR_KEY = 'search.page_rank_cut_factor';
-export const DEFAULT_PAGE_RANK_CUT_FACTOR = 1;
+export const DEFAULT_PAGE_RANK_CUT_FACTOR = 1.5;
/** The cut a page-unit plan asks for (resolved once per call). */
export interface PageRankCut {
@@ -47,9 +48,9 @@ async function readConfig(engine: BrainEngine, key: string): Promise<string | nu
}
}
-/** Undefined unless `search.page_rank_cut` is `whole_pages`; a factor that is not a positive finite number reads as 1.0. */
+/** Undefined only when `search.page_rank_cut` is `off`; any other value is `whole_pages`, and a factor that is not a positive finite number reads as the default. */
export async function resolvePageRankCut(engine: BrainEngine, callerBudget: number): Promise<PageRankCut | undefined> {
- if ((await readConfig(engine, PAGE_RANK_CUT_KEY))?.trim().toLowerCase() !== 'whole_pages') return undefined;
+ if ((await readConfig(engine, PAGE_RANK_CUT_KEY))?.trim().toLowerCase() === 'off') return undefined;
const raw = await readConfig(engine, PAGE_RANK_CUT_FACTOR_KEY);
const n = raw == null || raw === '' ? NaN : Number(raw);
return { mode: 'whole_pages', factor: Number.isFinite(n) && n > 0 ? n : DEFAULT_PAGE_RANK_CUT_FACTOR, caller_budget: callerBudget };
diff --git a/test/search-keyword-paging.test.ts b/test/search-keyword-paging.test.ts
index f4efc84439..8cc1dba9bc 100644
--- a/test/search-keyword-paging.test.ts
+++ b/test/search-keyword-paging.test.ts
@@ -217,6 +217,8 @@ describe('MCP: model-visible counts and paging (content blocks only, no _meta)',
await seedPage(engine, 'meetings/sos-1', `${TERM} ${TERM} ${TERM} sos short one.`, { type: 'meeting' });
await seedPage(engine, 'meetings/sos-2', `${TERM} sos oversized middle. ${'Filler sentence about logistics planning. '.repeat(400)}`, { type: 'meeting' });
await seedPage(engine, 'meetings/sos-3', `${TERM} sos short three.`, { type: 'meeting' });
+ // Delivery's own omission contract, without W5's whole-page cut (default on), which stops at the oversized page.
+ await engine.setConfig('search.page_rank_cut', 'off');
try {
const keyword = await callSearch(engine, { query: `${TERM} sos`, match: 'keyword', types: ['meeting'] });
const order = keyword.rows.map(r => String(r.slug));
@@ -227,6 +229,7 @@ describe('MCP: model-visible counts and paging (content blocks only, no _meta)',
expect(order).toEqual(['meetings/sos-1', 'meetings/sos-2', 'meetings/sos-3']);
expect(rows.filter(r => r.evidence_omitted).map(r => r.slug)).toEqual(['meetings/sos-2']);
} finally {
+ await engine.unsetConfig('search.page_rank_cut');
await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'meetings/sos-%'`);
}
});
diff --git a/test/search/page-rank-cut.test.ts b/test/search/page-rank-cut.test.ts
index dd54f1cd38..a3f3d39883 100644
--- a/test/search/page-rank-cut.test.ts
+++ b/test/search/page-rank-cut.test.ts
@@ -1,15 +1,16 @@
/**
- * W5 — `search.page_rank_cut: whole_pages`: with `return_unit: "page"` and a
- * caller budget, delivery stops adding page candidates once their whole
- * delivered pages fill `factor x budget`, and ranking lifts the mode's
- * chunk-token cut so it cannot stop earlier.
+ * W5 — `search.page_rank_cut: whole_pages` (the default, factor 1.5): with
+ * `return_unit: "page"` and a caller budget, delivery stops adding page
+ * candidates once their whole delivered pages fill `factor x budget`, and
+ * ranking lifts the mode's chunk-token cut so it cannot stop earlier.
*
- * Protects: off (unset, `off`, anything else) leaves query/search/recall
- * exactly as before; on, small pages fill at least 95% of the budget (even
- * under conservative's 4000-token mode cut) and large pages are delivered
- * whole, a few of them, like the old 0.40 ratio; a page call without a budget
- * and a chunk-unit call never engage it; `delivery.page_rank_cut` reports
- * mode, factor, caller budget, target, applied cost, candidates and kept.
+ * Protects: explicit `off` leaves query/search/recall exactly on the old path
+ * (no cut, the mode cut kept); on, small pages fill at least 95% of the budget
+ * (even under conservative's 4000-token mode cut) and large pages are
+ * delivered whole, a few of them, like the old 0.40 ratio; a page call
+ * without a budget and a chunk-unit call never engage it;
+ * `delivery.page_rank_cut` reports mode, factor, caller budget, target,
+ * applied cost, candidates and kept.
* Forced probe: the fixed-ratio path (a 0.40 x budget chunk-token cut, which
* is what `search.page_rank_budget_ratio` folded into `search.tokenBudget`)
* under-fills the small-page fixture.
@@ -110,44 +111,55 @@ for (const backend of testBackends()) {
await close();
});
- test('only whole_pages is on; a factor that is not a positive number reads as 1.0', async () => {
- for (const v of [null, '', 'off', 'whole-page', 'true']) {
+ test('whole_pages at factor 1.5 is the default; only `off` turns it off', async () => {
+ for (const v of [null, '', 'whole_pages', 'whole-page', 'true']) {
+ await cutMode(v);
+ expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1.5, caller_budget: BUDGET });
+ }
+ for (const v of ['off', ' OFF ']) {
await cutMode(v);
expect(await resolvePageRankCut(engine, BUDGET)).toBeUndefined();
}
- await cutMode('whole_pages');
+ await cutMode(null);
for (const bad of [null, '', 'big', '0', '-1', 'Infinity']) {
await set(PAGE_RANK_CUT_FACTOR_KEY, bad);
- expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1, caller_budget: BUDGET });
+ expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1.5, caller_budget: BUDGET });
}
await set(PAGE_RANK_CUT_FACTOR_KEY, '1.25');
expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1.25, caller_budget: BUDGET });
await set(PAGE_RANK_CUT_FACTOR_KEY, null);
});
- test('off: unset, `off` or an unknown value leaves rows and delivery identical', async () => {
- await cutMode(null);
+ test('explicit off is the old path: no cut, the mode cut kept, whatever the spelling', async () => {
+ await cutMode('off');
const base = await page(SMALL);
expect(base.meta!.delivery.page_rank_cut).toBeUndefined();
- for (const v of ['off', 'nonsense']) {
+ const conservative = await page(SMALL, { mode: 'conservative' });
+ expect(conservative.meta!.token_budget.budget).toBe(4000);
+ expect(conservative.meta!.delivery.page_rank_cut).toBeUndefined();
+ for (const v of ['OFF', ' off ']) {
await cutMode(v);
const again = await page(SMALL);
expect(slugs(again.out)).toEqual(slugs(base.out));
expect(again.meta!.delivery).toEqual(base.meta!.delivery);
expect(again.meta!.token_budget).toEqual(base.meta!.token_budget);
}
+ await cutMode(null);
+ expect((await page(SMALL)).meta!.delivery.page_rank_cut).toMatchObject({ mode: 'whole_pages', factor: 1.5 });
});
test('small pages fill at least 95% of the budget; the fixed 0.40 ratio under-fills (forced probe)', async () => {
- await cutMode(null);
+ await cutMode('off');
// The old ratio folded min(mode cut, 0.40 x budget) into search.tokenBudget, a chunk-token cut.
await set('search.tokenBudget', String(0.4 * BUDGET));
const ratio = await page(SMALL);
await set('search.tokenBudget', null);
expect(ratio.meta!.delivery.budget_used).toBeLessThan(0.6 * BUDGET);
- await cutMode('whole_pages');
+ await cutMode(null);
+ await set(PAGE_RANK_CUT_FACTOR_KEY, '1');
const on = await page(SMALL);
+ await set(PAGE_RANK_CUT_FACTOR_KEY, null);
const cut = on.meta!.delivery.page_rank_cut;
expect(cut).toMatchObject({ mode: 'whole_pages', factor: 1, caller_budget: BUDGET, target: BUDGET });
expect(on.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
@@ -156,26 +168,33 @@ for (const backend of testBackends()) {
expect(cut.candidates).toBeGreaterThan(cut.kept);
expect(cut.applied_cost).toBeGreaterThanOrEqual(0.95 * BUDGET);
expect(on.out.every((r: any) => r.delivered.truncated === false)).toBe(true);
+ // The default factor (1.5) hands delivery pages worth 12,000 tokens; delivery still fills and holds the 8,000 budget.
+ const dflt = await page(SMALL);
+ expect(dflt.meta!.delivery.page_rank_cut).toMatchObject({ factor: 1.5, target: 1.5 * BUDGET });
+ expect(dflt.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
+ expect(dflt.meta!.delivery.budget_used).toBeLessThanOrEqual(BUDGET);
});
test('the mode cut never under-fills: conservative (4000) still fills small pages', async () => {
- await cutMode(null);
+ await cutMode('off');
const off = await page(SMALL, { mode: 'conservative' });
expect(off.meta!.token_budget.budget).toBe(4000);
expect(off.meta!.delivery.budget_used).toBeLessThan(0.6 * BUDGET);
- await cutMode('whole_pages');
+ await cutMode(null);
const on = await page(SMALL, { mode: 'conservative' });
expect(on.meta!.token_budget).toBeUndefined();
expect(on.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
});
test('large pages: the same whole pages the 0.40 ratio delivered, without its slivers', async () => {
- await cutMode(null);
+ await cutMode('off');
await set('search.tokenBudget', String(0.4 * BUDGET));
const ratio = await page(LARGE);
await set('search.tokenBudget', null);
- await cutMode('whole_pages');
+ await cutMode(null);
+ await set(PAGE_RANK_CUT_FACTOR_KEY, '1');
const on = await page(LARGE);
+ await set(PAGE_RANK_CUT_FACTOR_KEY, null);
const cut = on.meta!.delivery.page_rank_cut;
expect(cut.kept).toBeLessThanOrEqual(4);
const whole = (rows: any[]) => rows.filter((r) => r.delivered.truncated === false).map((r) => r.slug);
@@ -187,20 +206,21 @@ for (const backend of testBackends()) {
});
test('factor scales the target', async () => {
- await cutMode('whole_pages');
+ await cutMode(null);
await set(PAGE_RANK_CUT_FACTOR_KEY, '0.5');
const half = await page(SMALL);
await set(PAGE_RANK_CUT_FACTOR_KEY, null);
const full = await page(SMALL);
expect(half.meta!.delivery.page_rank_cut).toMatchObject({ factor: 0.5, target: BUDGET / 2 });
+ expect(full.meta!.delivery.page_rank_cut).toMatchObject({ factor: 1.5, target: 1.5 * BUDGET });
expect(half.meta!.delivery.page_rank_cut.kept).toBeLessThan(full.meta!.delivery.page_rank_cut.kept);
});
test('no caller budget, or the chunk unit, is unchanged', async () => {
- await cutMode(null);
+ await cutMode('off');
const pageOff = await call('query', { query: SMALL, return_unit: 'page', limit: 50, mode: 'conservative' });
const chunkOff = await call('query', { query: SMALL, token_budget: 3000, limit: 50, mode: 'conservative' });
- await cutMode('whole_pages');
+ await cutMode(null);
const pageOn = await call('query', { query: SMALL, return_unit: 'page', limit: 50, mode: 'conservative' });
const chunkOn = await call('query', { query: SMALL, token_budget: 3000, limit: 50, mode: 'conservative' });
expect(pageOn.meta!.delivery.page_rank_cut).toBeUndefined();
@@ -212,7 +232,7 @@ for (const backend of testBackends()) {
});
test('search and recall page paths take the same cut', async () => {
- await cutMode('whole_pages');
+ await cutMode(null);
const s = await call('search', { query: SMALL, return_unit: 'page', token_budget: BUDGET, limit: 50, mode: 'tokenmax' });
expect(s.meta!.delivery.page_rank_cut).toMatchObject({ mode: 'whole_pages', caller_budget: BUDGET });
expect(s.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
@@ -224,10 +244,11 @@ for (const backend of testBackends()) {
const r = await call('recall', { query: SMALL, return_unit: 'page', budget_tokens: 2000, limit: 50 });
expect(r.out.search_degraded).toBeUndefined();
expect(r.out.delivery.page_rank_cut).toMatchObject({ mode: 'whole_pages', caller_budget: 2000 });
- await cutMode(null);
+ await cutMode('off');
const rOff = await call('recall', { query: SMALL, return_unit: 'page', budget_tokens: 2000, limit: 50 });
expect(rOff.out.delivery.page_rank_cut).toBeUndefined();
} finally {
+ await cutMode(null);
embeddingDisabled = true;
__setEmbedTransportForTests(null);
resetGateway();