Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(links): filter get_backlinks type in SQL before the cap (#6876)
time-attackbee4df7deb50
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.tsindex bd142543db..a90f6643fc 100644--- a/src/core/engine-sql/links.ts+++ b/src/core/engine-sql/links.ts@@ -57,12 +57,17 @@ function linkPageSql(opts?: LinkReadScope) {? sqlFragment` ${temporalWalkFilter('l', { temporal: rel.policy, excludePrivate: opts?.excludePrivate })}`: sqlFragment` ${trustedSql(`AND NOT (${relationshipFilterSql('l', { ...rel.policy, excludePrivate: opts?.excludePrivate })})`)}`;const linkType = page.linkType !== undefined ? sqlFragment` AND l.link_type = ${page.linkType}` : sqlFragment``;+ const ft = page.fromType;+ const fromType = !ft+ ? sqlFragment``+ : sqlFragment` AND (f.type = ${ft.type}${ft.type === 'untyped' ? sqlFragment` OR f.type IS NULL OR f.type = ''` : sqlFragment``}+ OR EXISTS (SELECT 1 FROM unnest(${ft.aliasSources}::text[], ${ft.aliases}::text[]) AS k(s, t) WHERE k.s = f.source_id AND k.t = f.type))`;const after = page.afterId !== undefined ? sqlFragment` AND l.id > ${page.afterId}` : sqlFragment``;const through = page.throughId !== undefined ? sqlFragment` AND l.id <= ${page.throughId}` : sqlFragment``;return {context,id: sqlFragment`, l.id AS link_id`,- where: sqlFragment`${linkType}${after}${through}${relationship}`,+ where: sqlFragment`${linkType}${fromType}${after}${through}${relationship}`,limit: page.limit !== undefined ? sqlFragment` LIMIT ${page.limit}` : sqlFragment``,};}diff --git a/src/core/link-validity.ts b/src/core/link-validity.tsindex d12ae110f5..218c413c3e 100644--- a/src/core/link-validity.ts+++ b/src/core/link-validity.ts@@ -392,6 +392,8 @@ export interface LinkReadPage {throughId?: number;limit?: number;linkType?: string;+ /** Only rows whose from page has `type` (stored, `untyped` for none, or a stored alias `aliases[i]` that source `aliasSources[i]` maps to it). */+ fromType?: { type: string; aliasSources: string[]; aliases: string[] };/** Keep the rows that match the temporal policy, or only the rows it hides. */relationship?: { policy: EdgeTemporalOpts; keep: 'match' | 'hidden' };/** Context longer than this is cut, ending in an ellipsis. */diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.tsindex 8a27477ba8..60e04eae16 100644--- a/src/core/ops/backlinks-paged.ts+++ b/src/core/ops/backlinks-paged.ts@@ -12,7 +12,8 @@import { opError, type OperationContext } from './contract.ts';import type { Link, PageReadPolicy } from '../types.ts';-import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';+import { canonicalTypeOf, loadSourcePack, typeAliasPairs } from '../mentions/policy.ts';+import type { LinkReadPage } from '../link-validity.ts';import {canonicalRecordTypes, decodeCursor, readPageStatusByRef, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,} from '../mentions/referrers.ts';@@ -117,26 +118,25 @@ export async function withLinkPageStatus(ctx: OperationContext, policy: () => Pr}/**- * Array mode with `type`: one page of link rows (ops/links.ts, #6876 keyset- * paging), kept when the referring page has that type. The page is cut before- * this filter, so a page can hold fewer rows than `limit`; the cursor still- * continues the same listing.+ * Array mode with `type`: the referring-page type filter for the keyset page+ * SQL (ops/links.ts, #6876), so LIMIT counts only rows of that type. A row is+ * kept when its referrer's stored type is `type` (`untyped` for none) or a+ * stored alias its own source's pack maps to `type`.*/-export async function filterBacklinkRows(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy, links: Link[]): Promise<Link[]> {+export async function backlinkTypeFilter(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<LinkReadPage['fromType']> {const type = typeof p.type === 'string' && p.type ? p.type : undefined;- if (!type) return links;+ if (!type) return undefined;const resolved = await referrerScope(ctx, String(p.slug), policy);if (resolved) await assertKnownType(ctx, resolved.scope, type);- const keys = [...new Set(links.map(l => `${l.from_source_id}\0${l.from_slug}`))];- const types = new Map((await ctx.engine.executeRaw<{ source_id: string; slug: string; type: string | null }>(- `SELECT p.source_id, p.slug, p.type FROM pages p JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON p.source_id = k.s AND p.slug = k.g`,- [keys.map(k => k.split('\0')[0]), keys.map(k => k.split('\0')[1])])).map(r => [`${r.source_id}\0${r.slug}`, r.type]));- const packs = new Map<string, Awaited<ReturnType<typeof loadSourcePack>>>();- const filtered: Link[] = [];- for (const l of links) {- if (!packs.has(l.from_source_id)) packs.set(l.from_source_id, await loadSourcePack(ctx.engine, l.from_source_id));- const stored = types.get(`${l.from_source_id}\0${l.from_slug}`) ?? null;- if (stored === type || canonicalTypeOf(stored, packs.get(l.from_source_id) ?? null) === type) filtered.push(l);+ const aliasSources: string[] = [];+ const aliases: string[] = [];+ for (const { id } of await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')) {+ const pairs = typeAliasPairs(await loadSourcePack(ctx.engine, id));+ pairs.stored.forEach((stored, i) => {+ if (pairs.canonical[i] !== type) return;+ aliasSources.push(id);+ aliases.push(stored);+ });}- return filtered;+ return { type, aliasSources, aliases };}diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 842e9d39ef..f70bac22f2 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -1,5 +1,5 @@import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';-import { filterBacklinkRows, readBacklinkPage, withLinkPageStatus } from './backlinks-paged.ts';+import { backlinkTypeFilter, readBacklinkPage, withLinkPageStatus } from './backlinks-paged.ts';import { cutLinkPage, finishLinkPage, linkId, parseLinkListing, reportLinkPage } from './link-paging.ts';/*** Links + graph operation cluster — pure move from operations.ts (v0.46.x@@ -277,8 +277,8 @@ const linkIdentity = (l: Link) => JSON.stringify([* merges, de-duplicated on link identity: the scalar branch keeps the* cross-source far-endpoint view local callers rely on, which the* all-endpoints branch would drop for far pages in non-federated sources.- * Every other caller runs one read. Each read is a keyset page with link_type- * and the temporal policy in SQL; the cap applies after the merge and the+ * Every other caller runs one read. Each read is a keyset page with link_type,+ * get_backlinks' referrer type and the temporal policy in SQL; the cap applies after the merge and the* identity union, and hidden former relationships never count toward it.*/async function readLinkEdges(@@ -292,6 +292,7 @@ async function readLinkEdges(const temporal = await resolveEdgeTemporal(ctx, p, opName);const listing = parseLinkListing(ctx, opName, p, policy);const linkType = typeof p.link_type === 'string' && p.link_type ? p.link_type : undefined;+ const fromType = direction === 'in' ? await backlinkTypeFilter(ctx, p, policy) : undefined;// Rows come back annotated with their relationship status; the policy// itself runs in SQL (and a second read counts what it hid).const annotate = temporal.disabled ? undefined : { ...temporal, status: 'all' as const, during: undefined };@@ -326,7 +327,7 @@ async function readLinkEdges(}return { streams, rows: [...merged.values()].sort((a, b) => linkId(a) - linkId(b)) };};- const base: LinkReadPage = { ...(linkType ? { linkType } : {}), contextChars: LINK_READ_CONTEXT_MAX_CHARS };+ const base: LinkReadPage = { ...(linkType ? { linkType } : {}), ...(fromType ? { fromType } : {}), contextChars: LINK_READ_CONTEXT_MAX_CHARS };const out: Link[] = [];let hidden = 0;let afterId = listing.afterId;@@ -341,7 +342,7 @@ async function readLinkEdges(} while (listing.all && nextId !== undefined);const { kept, hidden: hiddenAfterRead } = filterTemporalLinks(out, temporal);reportTemporal(ctx, opName, p, temporal, hidden + hiddenAfterRead);- if (out.length === 0 && hidden === 0 && listing.afterId === undefined) await hintScopedLinkMiss(ctx, p, requested, policy, direction);+ if (out.length === 0 && hidden === 0 && listing.afterId === undefined && !fromType) await hintScopedLinkMiss(ctx, p, requested, policy, direction);return { links: kept, nextCursor: reportLinkPage(ctx, opName, p, listing, { returned: kept.length, nextId }) };}@@ -435,8 +436,7 @@ const get_backlinks: Operation = {if (p.group !== undefined) return readBacklinkPage(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy);const { links, nextCursor } = await readLinkEdges(ctx, p, 'get_backlinks', 'in');const policy = async () => (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy;- const typed = p.type !== undefined ? await filterBacklinkRows(ctx, p, await policy(), links) : links;- return finishLinkPage(await withLinkPageStatus(ctx, policy, typed), nextCursor);+ return finishLinkPage(await withLinkPageStatus(ctx, policy, links), nextCursor);},scope: 'read',cliHints: { name: 'backlinks', positional: ['slug'] },diff --git a/test/helpers/link-paging-scenarios.ts b/test/helpers/link-paging-scenarios.tsindex 90d3c7fa71..07ffb18487 100644--- a/test/helpers/link-paging-scenarios.ts+++ b/test/helpers/link-paging-scenarios.ts@@ -29,8 +29,8 @@ function fan(from: string, n: number, opts: { reverse?: boolean; prefix?: string});}-async function put(engine: BrainEngine, slug: string, sourceId = 'default') {- await engine.putPage(slug, { type: 'note' as never, title: slug, compiled_truth: `${slug} body`, frontmatter: {} }, { sourceId });+async function put(engine: BrainEngine, slug: string, sourceId = 'default', type = 'note') {+ await engine.putPage(slug, { type: type as never, title: slug, compiled_truth: `${slug} body`, frontmatter: {} }, { sourceId });}export async function seedLinkPagingFixture(engine: BrainEngine): Promise<void> {@@ -39,7 +39,8 @@ export async function seedLinkPagingFixture(engine: BrainEngine): Promise<void>ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`);await engine.executeRaw(`UPDATE sources SET config = '{"federated": true}'::jsonb WHERE id = 'default'`);for (const slug of [...TARGETS, 'hubs/at-cap', 'hubs/over-cap', 'hubs/many', 'hubs/typed', 'hubs/wide', 'hubs/backlinked',- 'hubs/temporal', 'people/alice-example', 'companies/acme-example', 'fed/hub', 'idn/a', 'idn/b']) await put(engine, slug);+ 'hubs/temporal', 'people/alice-example', 'companies/acme-example', 'fed/hub', 'idn/a', 'idn/b', 'hubs/people']) await put(engine, slug);+ await put(engine, 'people/bob-example', 'default', 'person');for (const slug of ['fed/hub', ...TARGETS]) await put(engine, slug, 'second');await engine.addLinksBatch([...fan('hubs/at-cap', LINK_READ_DEFAULT_LIMIT),@@ -47,7 +48,10 @@ export async function seedLinkPagingFixture(engine: BrainEngine): Promise<void>...fan('hubs/many', 1203),...fan('hubs/typed', 700),...fan('hubs/backlinked', LINK_READ_DEFAULT_LIMIT + 1, { reverse: true }),+ ...fan('hubs/people', LINK_READ_DEFAULT_LIMIT + 1, { reverse: true }),]);+ // One person backlink after 501 note backlinks: get_backlinks' type filter runs before the cap.+ await engine.addLink('people/bob-example', 'hubs/people', 'bob', 'k000', 'manual');// Three 'cites' edges after 700 others: the link_type filter runs before the cap.await engine.addLinksBatch(TARGETS.slice(0, 3).map(t => ({ from_slug: 'hubs/typed', to_slug: t, link_type: 'cites', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' })));await engine.addLink('hubs/wide', TARGETS[0], 'w'.repeat(10_000), 'k000', 'manual');@@ -76,7 +80,8 @@ export async function seedLinkPagingFixture(engine: BrainEngine): Promise<void>async function call(engine: BrainEngine, op: string, args: Record<string, unknown>, opts: Record<string, unknown> = LOCAL) {const r = await dispatchToolCall(engine, op, args, opts as never);- return { isError: r.isError === true, text: r.content[0].text, json: r.isError ? null : JSON.parse(r.content[0].text) as Row[], notices: r.content.slice(1).map(c => c.text) };+ return { isError: r.isError === true, text: r.content[0].text, json: r.isError ? null : JSON.parse(r.content[0].text) as Row[], notices: r.content.slice(1).map(c => c.text),+ pagination: (r as { _meta?: { pagination?: Row } })._meta?.pagination };}const key = (r: Row) => `${r.from_source_id}:${r.from_slug}->${r.to_source_id}:${r.to_slug}:${r.link_type}:${r.origin_slug ?? ''}`;@@ -142,6 +147,24 @@ export function registerLinkPagingTests(getEngine: () => BrainEngine): void {const { json } = await call(getEngine(), 'get_links', { slug: 'hubs/typed', link_type: 'cites' });expect(json!.map(r => r.to_slug).sort()).toEqual(TARGETS.slice(0, 3));expect(json!.some(r => 'truncated' in r)).toBe(false);+ const paged = await pages(getEngine(), 'get_links', { slug: 'hubs/typed', link_type: 'cites', limit: 2 });+ expect(paged.map(p => p.length)).toEqual([2, 1]);+ expect(paged.flat().map(r => r.to_slug).sort()).toEqual(TARGETS.slice(0, 3));+ });++ test('get_backlinks type filters in SQL before the cap: a hub\'s one person backlink is on the first page', async () => {+ for (const opts of [LOCAL, REMOTE]) {+ const first = await call(getEngine(), 'get_backlinks', { slug: 'hubs/people', type: 'person' }, opts);+ expect(first.json!.map(r => r.from_slug)).toEqual(['people/bob-example']);+ expect(first.json!.some(r => 'truncated' in r)).toBe(false);+ expect(first.pagination).toEqual({ limit: LINK_READ_DEFAULT_LIMIT, returned: 1, truncated: false });+ }+ const notes = await pages(getEngine(), 'get_backlinks', { slug: 'hubs/people', type: 'note', limit: 200 });+ expect(notes.map(p => p.length)).toEqual([200, 200, 101]);+ expect(new Set(notes.flat().map(key)).size).toBe(LINK_READ_DEFAULT_LIMIT + 1);+ expect(notes.flat().some(r => r.from_slug === 'people/bob-example')).toBe(false);+ const cut = await call(getEngine(), 'get_backlinks', { slug: 'hubs/people', type: 'note', limit: 200 });+ expect(cut.pagination).toEqual(expect.objectContaining({ returned: 200, truncated: true }));});test('a wide context is bounded in the op; the engine read stays complete', async () => {