Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): resolving the entity a query names is one round trip, not four (#6721)

garrytan45b692734c04
diff --git a/src/core/mentions/policy.ts b/src/core/mentions/policy.ts
index 49fa89f6a2..9fcd8824d5 100644
--- a/src/core/mentions/policy.ts
+++ b/src/core/mentions/policy.ts
@@ -20,6 +20,7 @@
import type { BrainEngine } from '../engine.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+import { requestConfigRows } from '../config-snapshot.ts';
export const ALWAYS_LINKABLE_TYPES = ['person', 'company', 'organization', 'entity'] as const;
const EXCLUDED_LINKABLE_ALIASES: ReadonlySet<string> = new Set(['product']);
@@ -66,8 +67,13 @@ export function parseNameList(value: unknown): string[] {
const POLICY_KEYS = ['auto_link', 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'mentions.exclude_slugs',
'mentions.alias_deny', 'mentions.multiword_aliases', 'mentions.sibling_merge'] as const;
-/** The policy keys in one config read when the engine can run SQL (the write path counts statements), else one read per key. */
+/**
+ * The policy keys from the request's config snapshot when one is open (no statement, #6721), else in one
+ * config read when the engine can run SQL (the write path counts statements), else one read per key.
+ */
async function readPolicyKeys(engine: Pick<BrainEngine, 'getConfig'> & Partial<Pick<BrainEngine, 'executeRaw' | 'kind'>>): Promise<Array<string | null>> {
+ const held = await requestConfigRows(engine);
+ if (held) return POLICY_KEYS.map(k => held[k] ?? null);
if (engine.executeRaw && (engine.kind === 'pglite' || engine.kind === 'postgres')) {
try {
const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[...POLICY_KEYS]]);
diff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.ts
index 324f770177..c1e03eb9fe 100644
--- a/src/core/search/alias-fanout.ts
+++ b/src/core/search/alias-fanout.ts
@@ -98,18 +98,26 @@ export async function resolveQueryEntities(engine: BrainEngine, query: string, s
}
}
const norms = [...new Set(grams.map(g => g.norm))];
- const aliasHits = await engine.resolveAliases(norms, scope).catch(() => new Map<string, Array<{ slug: string; source_id: string }>>());
const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];
- const policy = await readMentionPolicy(engine);
- const types = [...new Set((await Promise.all(sources.map(async s => linkableTypesFor(await loadSourcePack(engine, s), policy)))).flat())];
const { privatePagesFilterFragment } = await import('./private-visibility.ts');
- const titleRows = await engine.executeRaw<{ slug: string; source_id: string; t: string }>(
- `SELECT slug, source_id, lower(title) AS t FROM pages
- WHERE lower(title) = ANY($1::text[]) AND source_id = ANY($2::text[]) AND type = ANY($3::text[]) AND deleted_at IS NULL
- ${scope.excludePrivate ? `AND ${privatePagesFilterFragment('pages')}` : ''}`, [norms, sources, types]).catch(() => []);
- const caseRows = await engine.executeRaw<{ slug: string; alias_norm: string; alias_text: string | null }>(
- `SELECT slug, alias_norm, alias_text FROM page_aliases WHERE alias_norm = ANY($1::text[]) AND case_sensitive AND source_id = ANY($2::text[])`,
- [norms, sources]).catch(() => []);
+ // The alias, title and case-sensitive reads depend on nothing but the n-grams (the title read also on the
+ // linkable types, which the request's config snapshot answers), so they run at once: on a pooled Postgres
+ // one round trip of wall time instead of three in series (#6721). A policy or pack failure still throws.
+ const titleRead = (async () => {
+ const policy = await readMentionPolicy(engine);
+ const types = [...new Set((await Promise.all(sources.map(async s => linkableTypesFor(await loadSourcePack(engine, s), policy)))).flat())];
+ return engine.executeRaw<{ slug: string; source_id: string; t: string }>(
+ `SELECT slug, source_id, lower(title) AS t FROM pages
+ WHERE lower(title) = ANY($1::text[]) AND source_id = ANY($2::text[]) AND type = ANY($3::text[]) AND deleted_at IS NULL
+ ${scope.excludePrivate ? `AND ${privatePagesFilterFragment('pages')}` : ''}`, [norms, sources, types]).catch(() => []);
+ })();
+ const [aliasHits, titleRows, caseRows] = await Promise.all([
+ engine.resolveAliases(norms, scope).catch(() => new Map<string, Array<{ slug: string; source_id: string }>>()),
+ titleRead,
+ engine.executeRaw<{ slug: string; alias_norm: string; alias_text: string | null }>(
+ `SELECT slug, alias_norm, alias_text FROM page_aliases WHERE alias_norm = ANY($1::text[]) AND case_sensitive AND source_id = ANY($2::text[])`,
+ [norms, sources]).catch(() => []),
+ ]);
const covered = new Set<number>();
for (const g of grams) {
if ([...Array(g.to - g.from + 1).keys()].some(k => covered.has(g.from + k))) continue;
diff --git a/test/search-entity-resolve-concurrency.test.ts b/test/search-entity-resolve-concurrency.test.ts
new file mode 100644
index 0000000000..dca553f78d
--- /dev/null
+++ b/test/search-entity-resolve-concurrency.test.ts
@@ -0,0 +1,90 @@
+/**
+ * #6721: resolving the entity a query names costs one round trip of wall
+ * time, not four.
+ *
+ * 1. Protects: `resolveQueryEntities` (search's alias fan-out, provenance
+ * demotion and entity facts) issues its alias, title and case-sensitive
+ * alias reads at once, and inside a request's config snapshot the mention
+ * policy it needs costs no statement. On a pooled Postgres they were four
+ * reads in series (alias, `config WHERE key = ANY`, titles, page_aliases),
+ * about 30 ms each.
+ * 2. Fails when: the reads are awaited one after another again, or the
+ * policy is read with its own config statement inside a request snapshot.
+ * Outside a snapshot the policy keeps its one keyed read (the write path
+ * counts statements).
+ * 3. Existing coverage: test/search-alias-fanout.test.ts pins what the
+ * fan-out finds, not when its reads are issued.
+ * 4. Seam: a recording engine whose reads finish only when the test releases
+ * them, so a read issued after another finished is visible.
+ * Contributed by @troyhoffman-oss (#6734).
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withRequestConfigSnapshot } from '../src/core/config-snapshot.ts';
+import { readMentionPolicy } from '../src/core/mentions/policy.ts';
+import { resolveQueryEntities } from '../src/core/search/alias-fanout.ts';
+
+function gatedEngine() {
+ const started: string[] = [];
+ const gates: Array<() => void> = [];
+ const gate = <T>(label: string, value: T) => new Promise<T>(resolve => { started.push(label); gates.push(() => resolve(value)); });
+ const engine = {
+ kind: 'postgres',
+ resolveAliases: (norms: string[]) => gate('aliases', new Map([[norms.find(n => n === 'acme example')!, [{ slug: 'companies/acme-example', source_id: 'default' }]]])),
+ executeRaw: (sql: string) => gate(sql.includes('page_aliases') ? 'case-sensitive aliases' : sql.includes('lower(title)') ? 'titles' : `other: ${sql.slice(0, 40)}`, []),
+ getAllConfig: async () => { started.push('config (snapshot)'); return {}; },
+ getConfig: async () => null,
+ } as unknown as BrainEngine;
+ return { engine, started, release: () => { for (const open of gates.splice(0)) open(); } };
+}
+
+describe('resolveQueryEntities', () => {
+ test('the alias, title and case-sensitive reads are all issued before any of them answers', async () => {
+ const { engine, started, release } = gatedEngine();
+ const found = await withRequestConfigSnapshot(engine, async () => {
+ const pending = resolveQueryEntities(engine, 'Acme Example renewal', { sourceId: 'default', excludePrivate: true });
+ for (let i = 0; i < 50 && started.length < 4; i++) await new Promise(r => setTimeout(r, 1));
+ expect([...started].sort()).toEqual(['aliases', 'case-sensitive aliases', 'config (snapshot)', 'titles']);
+ release();
+ return pending;
+ });
+ expect(found.map(f => f.pages)).toEqual([[{ slug: 'companies/acme-example', source_id: 'default' }]]);
+ });
+});
+
+describe('readMentionPolicy', () => {
+ const config = { 'mentions.entity_types': '+product,-person', 'mentions.ignore': 'Acme', unrelated: 'x' };
+
+ test('inside a request snapshot: the policy keys come from the snapshot, with no config statement of their own', async () => {
+ const statements: string[] = [];
+ const engine = {
+ kind: 'postgres',
+ executeRaw: async (sql: string) => { statements.push(sql); return []; },
+ getAllConfig: async () => config,
+ getConfig: async () => { throw new Error('per-key read not expected'); },
+ } as unknown as BrainEngine;
+ const policy = await withRequestConfigSnapshot(engine, () => readMentionPolicy(engine));
+ expect(statements).toEqual([]);
+ expect(policy).toMatchObject({ enabled: true, typeAdds: ['product'], typeRemoves: ['person'], ignore: ['Acme'] });
+ });
+
+ test('outside a snapshot: one keyed config read, unchanged', async () => {
+ const statements: string[] = [];
+ const engine = {
+ kind: 'postgres',
+ executeRaw: async (sql: string) => { statements.push(sql); return Object.entries(config).map(([key, value]) => ({ key, value })); },
+ getAllConfig: async () => { throw new Error('whole-table read not expected'); },
+ getConfig: async () => { throw new Error('per-key read not expected'); },
+ } as unknown as BrainEngine;
+ const policy = await readMentionPolicy(engine);
+ expect(statements).toEqual(['SELECT key, value FROM config WHERE key = ANY($1::text[])']);
+ expect(policy).toMatchObject({ enabled: true, typeAdds: ['product'], typeRemoves: ['person'], ignore: ['Acme'] });
+ });
+
+ test('an engine without SQL reads each key', async () => {
+ const keys: string[] = [];
+ const policy = await readMentionPolicy({ getConfig: async (key: string) => { keys.push(key); return key === 'auto_link' ? 'false' : null; } });
+ expect(keys).toContain('mentions.entity_types');
+ expect(policy).toMatchObject({ enabled: false, disabledBy: 'auto_link' });
+ });
+});