Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): start every post-fusion read at stage entry
garrytanf4a0f13a2138
diff --git a/src/core/search/graph-signals.ts b/src/core/search/graph-signals.tsindex ecde80683e..0d5445dd22 100644--- a/src/core/search/graph-signals.ts+++ b/src/core/search/graph-signals.ts@@ -264,6 +264,17 @@ export function computeScoreDistribution(scores: number[]): ScoreDistribution {};}+/**+ * The deduped page ids of the first `topK` results, the input of the+ * adjacency read. Array order, not score, picks them, so runPostFusionStages+ * can start the read before the earlier stages mutate scores.+ */+export function graphSignalPageIds(results: SearchResult[], topK: number = DEFAULT_TOP_K): number[] {+ return Array.from(+ new Set(results.slice(0, topK).map(r => r.page_id).filter(id => typeof id === 'number' && id > 0)),+ );+}+// ===========================================================================// Main entry point// ===========================================================================@@ -327,9 +338,7 @@ export async function applyGraphSignals(// (page_id is documented as REQUIRED in SearchResult JSDoc) — skip// such rows from the dedup set; they can't be matched in the result// Map anyway.- const uniquePageIds = Array.from(- new Set(topK.map(r => r.page_id).filter(id => typeof id === 'number' && id > 0)),- );+ const uniquePageIds = graphSignalPageIds(results, topKSize);let adjacency: Map<number, AdjacencyRow>;try {diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 8830f8f7b0..cc5eb8cc22 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -34,6 +34,8 @@ import {isAmbiguousModalityQuery,} from './query-intent.ts';import { isTitlePhraseMatch } from './title-match.ts';+import { applyGraphSignals, graphSignalPageIds } from './graph-signals.ts';+import { applyAliasResolvedBoost, readAliasCanonicals } from './hybrid/alias-resolved.ts';import {textArmsNonEmpty,type VectorArm,@@ -561,17 +563,6 @@ export async function runPostFusionStages(// Phase E3 — metadata-axis stages gated as ONE block (see PostFusionOpts).const metadata = opts.skipMetadataBoosts !== true;- // Backlink stage (existing behavior, preserved).- if (metadata && opts.applyBacklinks) {- try {- const pageIds = Array.from(new Set(results.map(r => r.page_id)));- const counts = await engine.getBacklinkCounts(pageIds, policy);- applyBacklinkBoost(results, counts, floorThreshold);- } catch {- // Non-fatal; preserves the existing pre-v0.29.1 contract.- }- }-// Composite refs for the orthogonal axes (multi-source isolation).const refs = Array.from(new Map(@@ -579,20 +570,43 @@ export async function runPostFusionStages().values(),);+ // Every stage read is keyed by the entry result set (page ids, refs, array+ // order), never by a score an earlier stage mutates, so all of them start+ // here instead of costing one round trip each in turn. The stages below+ // still apply in their fixed order, and a failed read skips only its stage.+ const backlinkCounts = metadata && opts.applyBacklinks+ ? startRead(() => engine.getBacklinkCounts(Array.from(new Set(results.map(r => r.page_id))), policy))+ : undefined;+ const salienceScores = metadata && opts.salience !== 'off' ? startRead(() => engine.getSalienceScores(refs, policy)) : undefined;+ const effectiveDates = metadata && opts.recency !== 'off' ? startRead(() => engine.getEffectiveDates(refs, policy)) : undefined;+ const adjacency = metadata && opts.graphSignalsEnabled+ ? startRead(() => engine.getAdjacencyBoosts(graphSignalPageIds(results), policy))+ : undefined;+ const aliasCanonicals = metadata ? startRead(() => readAliasCanonicals(engine, refs, policy)) : undefined;+ const supersededBy = startRead(() => readSupersededBy(results, engine, policy));++ // Backlink stage (existing behavior, preserved).+ if (backlinkCounts) {+ try {+ applyBacklinkBoost(results, await backlinkCounts, floorThreshold);+ } catch {+ // Non-fatal; preserves the existing pre-v0.29.1 contract.+ }+ }+// Salience stage (mattering, no time).- if (metadata && opts.salience !== 'off') {+ if (salienceScores && opts.salience !== 'off') {try {- const scores = await engine.getSalienceScores(refs, policy);- applySalienceBoost(results, scores, opts.salience, floorThreshold);+ applySalienceBoost(results, await salienceScores, opts.salience, floorThreshold);} catch {// Non-fatal.}}// Recency stage (per-prefix decay, no mattering).- if (metadata && opts.recency !== 'off') {+ if (effectiveDates && opts.recency !== 'off') {try {- const dates = await engine.getEffectiveDates(refs, policy);+ const dates = await effectiveDates;// Resolve the effective decay map (defaults + gbrain.yml `recency:` +// GBRAIN_RECENCY_DECAY env) instead of the baked-in defaults. The// get_recent_salience SQL path already goes through resolveRecencyDecayMap()@@ -637,13 +651,13 @@ export async function runPostFusionStages(// shares the same floor-threshold so a weak hub gets the same// protection v0.35.6.0 added for other metadata boosts. Fail-open at// this level matches the per-stage non-fatal contract.- if (metadata && opts.graphSignalsEnabled) {+ if (adjacency) {try {- const { applyGraphSignals } = await import('./graph-signals.ts');await applyGraphSignals(results, engine, {...policy,enabled: true,floorThreshold,+ adjacencyFn: () => adjacency,onMeta: opts.onGraphMeta,onScoreDistribution: opts.onScoreDistribution,});@@ -659,9 +673,9 @@ export async function runPostFusionStages(// intent: "user explicitly disambiguated this as canonical." Defense-// in-depth: pre-v105 brains don't have slug_aliases table; the lookup// throws isUndefinedTableError and the stage no-ops.- if (metadata) {+ if (aliasCanonicals) {try {- await applyAliasResolvedBoost(results, engine, policy);+ applyAliasResolvedBoost(results, await aliasCanonicals);} catch {// Non-fatal; preserves the per-stage contract.}@@ -675,12 +689,23 @@ export async function runPostFusionStages(// facts. Fail-open per the per-stage contract: a brain with no `supersedes`// edges (or a pre-links schema) finds 0 rows / throws and no-ops.try {- await applySupersedeDownrank(results, engine, policy);+ stampSuperseded(results, await supersededBy);} catch {// Non-fatal; preserves the per-stage contract.}}+/**+ * Start a stage read now; the stage awaits the promise later. A synchronous+ * throw becomes a rejection, and the rejection counts as handled until the+ * stage awaits it, so a read that fails early is not an unhandled rejection.+ */+function startRead<T>(read: () => Promise<T>): Promise<T> {+ const pending = (async () => read())();+ pending.catch(() => undefined);+ return pending;+}+/*** Memoized per-engine gate for the supersession stage. Most brains carry zero* `supersedes` edges, so the downrank lookup would be a wasted roundtrip on@@ -749,12 +774,21 @@ export async function applySupersedeDownrank(engine: import('../engine.ts').BrainEngine,policy?: PageReadPolicy,): Promise<void> {- if (results.length === 0) return;+ stampSuperseded(results, await readSupersededBy(results, engine, policy));+}++/** Superseded page id → the superseding page's slug, for the results' pages; empty when the stage no-ops. */+async function readSupersededBy(+ results: SearchResult[],+ engine: import('../engine.ts').BrainEngine,+ policy?: PageReadPolicy,+): Promise<Map<number, string>> {+ const supersededBy = new Map<number, string>();const pageIds = Array.from(new Set(results.map(r => r.page_id).filter((id): id is number => typeof id === 'number')),);- if (pageIds.length === 0) return;- if (!(await hasAnySupersedeEdges(engine))) return;+ if (pageIds.length === 0) return supersededBy;+ if (!(await hasAnySupersedeEdges(engine))) return supersededBy;const params: unknown[] = [pageIds];const fromFilter = pageReadFilter('pf', policy, params, !!policy);const toFilter = pageReadFilter('pt', policy, params, !!policy);@@ -775,14 +809,16 @@ export async function applySupersedeDownrank();} catch {// Pre-links schema or SQL miss; no-op.- return;+ return supersededBy;}- if (rows.length === 0) return;- const supersededBy = new Map<number, string>();for (const row of rows) {const id = Number(row.to_page_id);if (!supersededBy.has(id)) supersededBy.set(id, row.by_slug);}+ return supersededBy;+}++function stampSuperseded(results: SearchResult[], supersededBy: Map<number, string>): void {for (const r of results) {const by = supersededBy.get(r.page_id);if (by !== undefined) {@@ -794,66 +830,6 @@ export async function applySupersedeDownrank(}}-/**- * v0.42 (T19) — apply 1.05x boost to results whose slug is a canonical_slug- * in slug_aliases. Stamps `alias_resolved_boost` on touched results so- * --explain can render the contribution.- *- * Single index-hit query bounded by top-K (slug_aliases is small relative- * to the result set; ALIASES <<< PAGES even on the 186K-page production- * brain where 5.5K aliases is ~3% of pages).- *- * Source-scoped (codex F9: keyed by {source_id, slug} not just slug).- */-const ALIAS_RESOLVED_BOOST = 1.05;--async function applyAliasResolvedBoost(- results: SearchResult[],- engine: import('../engine.ts').BrainEngine,- policy?: PageReadPolicy,-): Promise<void> {- if (results.length === 0) return;- // Build the (source_id, slug) composite list for the lookup.- const refs = Array.from(- new Map(- results.map(r => [- `${r.source_id ?? 'default'}::${r.slug}`,- { slug: r.slug, source_id: r.source_id ?? 'default' },- ]),- ).values(),- );- if (refs.length === 0) return;- // Find which refs are canonical of any slug_aliases row.- // Two-array unnest for source-scoped composite lookup.- const sourceIds = refs.map(r => r.source_id);- const slugs = refs.map(r => r.slug);- const params: unknown[] = [sourceIds, slugs];- const filter = pageReadFilter('p', policy, params, !!policy);- let rows: Array<{ source_id: string; canonical_slug: string }> = [];- try {- rows = await engine.executeRaw<{ source_id: string; canonical_slug: string }>(- `SELECT DISTINCT a.source_id, a.canonical_slug- FROM slug_aliases a JOIN pages p ON p.source_id = a.source_id AND p.slug = a.canonical_slug- WHERE (a.source_id, a.canonical_slug) IN (- SELECT * FROM unnest($1::text[], $2::text[])- ) AND ${filter}`,- params,- );- } catch {- // Pre-v104 brain or other SQL miss; no-op.- return;- }- if (rows.length === 0) return;- const canonicalSet = new Set(rows.map(r => `${r.source_id}::${r.canonical_slug}`));- for (const r of results) {- const key = `${r.source_id ?? 'default'}::${r.slug}`;- if (canonicalSet.has(key)) {- r.score *= ALIAS_RESOLVED_BOOST;- r.alias_resolved_boost = ALIAS_RESOLVED_BOOST;- }- }-}-export interface HybridSearchOpts extends SearchOpts {expansion?: boolean;/** System One: remote spend accounting, call site, S1-only re-runs (see search/decide-stage.ts). */diff --git a/src/core/search/hybrid/alias-resolved.ts b/src/core/search/hybrid/alias-resolved.tsnew file mode 100644index 0000000000..857d9e261a--- /dev/null+++ b/src/core/search/hybrid/alias-resolved.ts@@ -0,0 +1,55 @@+import type { BrainEngine } from '../../engine.ts';+import type { PageReadPolicy, SearchResult } from '../../types.ts';+import { pageReadFilter } from '../read-policy-sql.ts';++/**+ * v0.42 (T19) — apply 1.05x boost to results whose slug is a canonical_slug+ * in slug_aliases. Stamps `alias_resolved_boost` on touched results so+ * --explain can render the contribution.+ *+ * Single index-hit query bounded by top-K (slug_aliases is small relative+ * to the result set; ALIASES <<< PAGES even on the 186K-page production+ * brain where 5.5K aliases is ~3% of pages).+ *+ * Source-scoped (codex F9: keyed by {source_id, slug} not just slug).+ */+const ALIAS_RESOLVED_BOOST = 1.05;++export async function readAliasCanonicals(+ engine: BrainEngine,+ refs: Array<{ slug: string; source_id: string }>,+ policy?: PageReadPolicy,+): Promise<Set<string>> {+ if (refs.length === 0) return new Set();+ // Find which refs are canonical of any slug_aliases row.+ // Two-array unnest for source-scoped composite lookup.+ const sourceIds = refs.map(r => r.source_id);+ const slugs = refs.map(r => r.slug);+ const params: unknown[] = [sourceIds, slugs];+ const filter = pageReadFilter('p', policy, params, !!policy);+ let rows: Array<{ source_id: string; canonical_slug: string }> = [];+ try {+ rows = await engine.executeRaw<{ source_id: string; canonical_slug: string }>(+ `SELECT DISTINCT a.source_id, a.canonical_slug+ FROM slug_aliases a JOIN pages p ON p.source_id = a.source_id AND p.slug = a.canonical_slug+ WHERE (a.source_id, a.canonical_slug) IN (+ SELECT * FROM unnest($1::text[], $2::text[])+ ) AND ${filter}`,+ params,+ );+ } catch {+ // Pre-v104 brain or other SQL miss; no-op.+ return new Set();+ }+ return new Set(rows.map(r => `${r.source_id}::${r.canonical_slug}`));+}++export function applyAliasResolvedBoost(results: SearchResult[], canonicalSet: Set<string>): void {+ for (const r of results) {+ const key = `${r.source_id ?? 'default'}::${r.slug}`;+ if (canonicalSet.has(key)) {+ r.score *= ALIAS_RESOLVED_BOOST;+ r.alias_resolved_boost = ALIAS_RESOLVED_BOOST;+ }+ }+}diff --git a/test/search/post-fusion-concurrent-reads.test.ts b/test/search/post-fusion-concurrent-reads.test.tsnew file mode 100644index 0000000000..f54a9eb035--- /dev/null+++ b/test/search/post-fusion-concurrent-reads.test.ts@@ -0,0 +1,212 @@+/**+ * runPostFusionStages issues every read keyed only by the entry result set+ * (page ids, {slug, source_id} refs, array order) at once, then applies the+ * stages in their fixed order. On a pooled Postgres each serial read cost one+ * round trip; the scores and ordering must stay bit-for-bit identical to the+ * sequential stages.+ */+import { afterEach, describe, expect, test, setSystemTime } from 'bun:test';+import {+ applyBacklinkBoost,+ applyChronicleTypeBoost,+ applyRecencyBoost,+ applySalienceBoost,+ applySupersedeDownrank,+ applyTitleBoost,+ computeFloorThreshold,+ runPostFusionStages,+ type PostFusionOpts,+} from '../../src/core/search/hybrid.ts';+import { applyGraphSignals } from '../../src/core/search/graph-signals.ts';+import type { AdjacencyRow, SearchResult } from '../../src/core/types.ts';++type ReadName = 'backlinks' | 'salience' | 'dates' | 'graph' | 'alias' | 'supersede-probe' | 'supersede';++const NOW = new Date('2026-06-01T00:00:00Z');+const DECAY_MAP = { 'daily/': { halflifeDays: 30, coefficient: 0.4 }, 'concepts/': { halflifeDays: 0, coefficient: 0 } };+const FALLBACK = { halflifeDays: 90, coefficient: 0.3 };++function row(slug: string, page_id: number, score: number, extra: Partial<SearchResult> = {}): SearchResult {+ return {+ slug,+ page_id,+ title: slug,+ type: 'note',+ chunk_text: `${slug} body`,+ chunk_source: 'compiled_truth',+ chunk_id: page_id,+ chunk_index: 0,+ score,+ stale: false,+ source_id: 'default',+ ...extra,+ } as SearchResult;+}++function fixture(): SearchResult[] {+ return [+ row('people/alice-example', 1, 0.92, { title: 'Alice Example' }),+ row('companies/acme-example', 2, 0.88),+ row('daily/2026-05-20/standup', 3, 0.81, { type: 'event' }),+ row('daily/2026-05-20/retro', 4, 0.79, { type: 'diary' }),+ row('concepts/widget-pricing', 5, 0.74, { source_id: 'source-a' }),+ row('companies/acme-example', 6, 0.70, { source_id: 'source-a' }),+ row('notes/weak-hub', 7, 0.30),+ row('notes/alice-example-old', 8, 0.65),+ ];+}++const backlinkCounts = new Map([[1, 4], [2, 12], [3, 1], [6, 3], [7, 40]]);+const salience = new Map([['default::people/alice-example', 3], ['source-a::concepts/widget-pricing', 6], ['default::notes/weak-hub', 9]]);+const dates = new Map([+ ['default::daily/2026-05-20/standup', new Date('2026-05-20T00:00:00Z')],+ ['default::daily/2026-05-20/retro', new Date('2026-05-21T00:00:00Z')],+ ['default::companies/acme-example', new Date('2026-01-10T00:00:00Z')],+ ['source-a::concepts/widget-pricing', new Date('2025-02-01T00:00:00Z')],+]);+const adjacency = new Map<number, AdjacencyRow>([+ [2, { hits: 3, cross_source_hits: 2 } as AdjacencyRow],+ [1, { hits: 2, cross_source_hits: 0 } as AdjacencyRow],+ [7, { hits: 5, cross_source_hits: 3 } as AdjacencyRow],+]);+const aliasRows = [{ source_id: 'default', canonical_slug: 'people/alice-example' }];+const supersedeRows = [{ to_page_id: 8, by_slug: 'people/alice-example' }];++const answers: Record<ReadName, unknown> = {+ backlinks: backlinkCounts,+ salience,+ dates,+ graph: adjacency,+ alias: aliasRows,+ 'supersede-probe': [{ one: 1 }],+ supersede: supersedeRows,+};++function classify(sql: string): ReadName {+ if (/slug_aliases/.test(sql)) return 'alias';+ if (/SELECT 1 AS one FROM links/.test(sql)) return 'supersede-probe';+ if (/supersedes/.test(sql)) return 'supersede';+ throw new Error(`unexpected executeRaw: ${sql}`);+}++/**+ * Fake engine. `mode(name)` decides per read: 'resolve' answers at once,+ * 'defer' parks the read until release(), 'reject' fails it immediately.+ */+function fakeEngine(mode: (name: ReadName) => 'resolve' | 'defer' | 'reject' = () => 'resolve') {+ const issued: ReadName[] = [];+ const parked: Array<() => void> = [];+ const read = (name: ReadName) => {+ issued.push(name);+ const how = mode(name);+ if (how === 'reject') return Promise.reject(new Error(`${name} failed`));+ if (how === 'resolve') return Promise.resolve(answers[name]);+ return new Promise(resolve => parked.push(() => resolve(answers[name])));+ };+ const engine = {+ getBacklinkCounts: () => read('backlinks'),+ getSalienceScores: () => read('salience'),+ getEffectiveDates: () => read('dates'),+ getAdjacencyBoosts: () => read('graph'),+ executeRaw: (sql: string) => read(classify(sql)),+ };+ return { engine, issued, release: () => { while (parked.length) parked.shift()!(); } };+}++const opts = (overrides: Partial<PostFusionOpts> = {}): PostFusionOpts => ({+ applyBacklinks: true,+ salience: 'on',+ recency: 'strong',+ decayMap: DECAY_MAP,+ fallback: FALLBACK,+ floorRatio: 0.5,+ graphSignalsEnabled: true,+ query: 'alice example',+ titleBoost: 1.25,+ ...overrides,+});++/** The stages one after another, in runPostFusionStages' order. */+async function sequential(results: SearchResult[], o: PostFusionOpts, skip: ReadName[] = []): Promise<void> {+ for (const r of results) r.base_score = r.score;+ const floor = computeFloorThreshold(results, o.floorRatio);+ if (!skip.includes('backlinks')) applyBacklinkBoost(results, backlinkCounts, floor);+ if (!skip.includes('salience')) applySalienceBoost(results, salience, 'on', floor);+ if (!skip.includes('dates')) applyRecencyBoost(results, dates, 'strong', DECAY_MAP, FALLBACK, Date.now(), floor);+ applyChronicleTypeBoost(results, 'strong', floor);+ applyTitleBoost(results, o.query!, o.titleBoost!, floor);+ if (!skip.includes('graph')) {+ await applyGraphSignals(results, {} as never, { enabled: true, floorThreshold: floor, adjacencyFn: async () => adjacency });+ }+ if (!skip.includes('alias')) {+ for (const r of results) {+ if (r.source_id === 'default' && r.slug === 'people/alice-example') {+ r.score *= 1.05;+ r.alias_resolved_boost = 1.05;+ }+ }+ }+ if (!skip.includes('supersede')) await applySupersedeDownrank(results, fakeEngine().engine as never);+}++/** Release parked reads until the run settles (the supersede query parks only after its probe answers). */+async function settle(done: Promise<void>, release: () => void): Promise<void> {+ const tick = () => new Promise<boolean>(r => setTimeout(() => r(false), 0));+ while (!(await Promise.race([done.then(() => true), tick()]))) release();+ await done;+}++afterEach(() => { setSystemTime(); });++describe('runPostFusionStages — id-keyed reads run concurrently', () => {+ test('every enabled read is issued before any of them resolves', async () => {+ const { engine, issued, release } = fakeEngine(() => 'defer');+ const results = fixture();+ const done = runPostFusionStages(engine as never, results, opts());+ for (let i = 0; i < 5; i++) await new Promise(r => setTimeout(r, 0));+ expect([...issued].sort()).toEqual(['alias', 'backlinks', 'dates', 'graph', 'salience', 'supersede-probe']);+ await settle(done, release);+ expect(issued).toContain('supersede');+ expect(results[1].backlink_boost).toBeGreaterThan(1);+ expect(results[0].alias_resolved_boost).toBe(1.05);+ expect(results[7].superseded).toBe(true);+ });++ test('disabled stages issue no read', async () => {+ const { engine, issued } = fakeEngine();+ await runPostFusionStages(engine as never, fixture(), opts({ applyBacklinks: false, salience: 'off', recency: 'off', graphSignalsEnabled: false }));+ expect([...issued].sort()).toEqual(['alias', 'supersede', 'supersede-probe']);+ const skipped = fakeEngine();+ await runPostFusionStages(skipped.engine as never, fixture(), opts({ skipMetadataBoosts: true }));+ expect([...skipped.issued].sort()).toEqual(['supersede', 'supersede-probe']);+ });++ test('final scores, stamps and order equal the sequential stages bit for bit', async () => {+ setSystemTime(NOW);+ const expected = fixture();+ await sequential(expected, opts());+ const actual = fixture();+ await runPostFusionStages(fakeEngine().engine as never, actual, opts());+ expect(actual).toEqual(expected);+ const order = (rs: SearchResult[]) => [...rs].sort((a, b) => b.score - a.score).map(r => `${r.source_id}::${r.slug}#${r.page_id}`);+ expect(order(actual)).toEqual(order(expected));+ for (const stamp of ['backlink_boost', 'salience_boost', 'recency_boost', 'chronicle_boost', 'title_match_boost', 'graph_adjacency_boost', 'graph_session_demoted', 'alias_resolved_boost', 'superseded'] as const) {+ expect(actual.some(r => r[stamp] !== undefined)).toBe(true);+ }+ const weak = actual.find(r => r.slug === 'notes/weak-hub')!;+ expect(weak.score).toBe(weak.base_score!);+ });++ for (const failing of ['backlinks', 'salience', 'dates', 'graph', 'alias', 'supersede-probe', 'supersede'] as const) {+ test(`a rejecting ${failing} read skips only its own stage`, async () => {+ setSystemTime(NOW);+ const skip: ReadName[] = failing === 'supersede-probe' ? [] : [failing];+ const expected = fixture();+ await sequential(expected, opts(), skip);+ const actual = fixture();+ const { engine, release } = fakeEngine(name => (name === failing ? 'reject' : 'defer'));+ await settle(runPostFusionStages(engine as never, actual, opts()), release);+ expect(actual).toEqual(expected);+ });+ }+});