Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(recall): intersect entity and session before LIMIT (#6938)
time-attack42b63edae3d1
diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 4246c28ae5..d59b6c5a93 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -635,6 +635,7 @@ async function fetchRowsLocal(excludeAuditRows: true,}): await engine.listFactsByEntity(sourceId, slug, {+ sessionId: flags.sessionId || undefined,activeOnly: !flags.includeExpired,limit: flags.limit,grep: flags.grep ?? undefined,diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex 8a53b1db1d..a198df689b 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -396,7 +396,7 @@ export async function listFactsByEntity(const rows = (await exec.run<FactRowSqlShape>(sqlFragment`SELECT * FROM factsWHERE source_id = ${source_id}- AND entity_slug = ${entitySlug}+ AND entity_slug = ${entitySlug}${opts?.sessionId ? sqlFragment` AND source_session = ${opts.sessionId}` : sqlFragment``}${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 16dee01d32..663a046058 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -644,6 +644,8 @@ export interface FactListOpts {* semantics only.*/grep?: string;+ /** Intersect entity reads with this exact source_session before LIMIT/OFFSET. Also honored by listFactsSince. */+ sessionId?: string;/*** When true, `listFactsSince`'s `since` comparison and ORDER BY use* COALESCE(valid_from, created_at) — event time — instead of creationdiff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex d6e35d6072..4a247d7fbd 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -433,7 +433,7 @@ const recall: Operation = {const { resolveEntitySlug } = await import('../entities/resolve.ts');const resolvedLists = await Promise.all(factSources.map(async (src) => {const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;- return { slug, rows: await readEntityFacts(ctx, src, slug, limit, s => ctx.engine.listFactsByEntity(src, s!, listOpts)) };+ return { slug, rows: await readEntityFacts(ctx, src, slug, limit, s => ctx.engine.listFactsByEntity(src, s!, { ...listOpts, sessionId: sessionParam ?? undefined })) };}));ambiguousEntity = await unlinkedNamesakes(ctx.engine, resolvedLists.map(l => l.rows.map(r => ({ ...r, entity_slug: l.slug }))));rows = ambiguousEntity ? [] : mergeNewest(resolvedLists.map(l => l.rows), (rec) => rec.valid_from ?? rec.created_at);diff --git a/test/e2e/recall-entity-session-6938-postgres.test.ts b/test/e2e/recall-entity-session-6938-postgres.test.tsnew file mode 100644index 0000000000..3a72d4542c--- /dev/null+++ b/test/e2e/recall-entity-session-6938-postgres.test.ts@@ -0,0 +1,2 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../recall-entity-session-6938.test.ts'));diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 54e7bf44f8..b48f112e49 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -3633,6 +3633,7 @@"kinds?: FactKind[] | undefined","limit?: number | undefined","offset?: number | undefined",+ "sessionId?: string | undefined","unconsolidatedOnly?: boolean | undefined","visibility?: FactVisibility[] | undefined"],diff --git a/test/recall-budget-policy-thin-cli.test.ts b/test/recall-budget-policy-thin-cli.test.tsindex f9669fcaf7..fccc04844a 100644--- a/test/recall-budget-policy-thin-cli.test.ts+++ b/test/recall-budget-policy-thin-cli.test.ts@@ -214,4 +214,28 @@ describe('actual remote source selection', () => {expect(invalid.localStoreCreated).toBe(false);}}, 90_000);++ test('#6938 thin entity + session recall keeps the intersection before the remote LIMIT', async () => {+ const entity = 'people/thin-session-example';+ for (const [fact, session, date] of [+ ['older thin session match', 'wanted-session', '2020-01-01'],+ ['newer thin unrelated fact', 'other-session', '2024-01-01'],+ ]) {+ await remote.insertFact({ fact, source: 'synthetic', entity_slug: entity,+ source_session: session, valid_from: new Date(date), visibility: 'world' }, { source_id: 'default' });+ }+ const dispatch = (args: Record<string, unknown>) => dispatchToolCall(remote, 'recall', args, {+ remote: true, sourceId: 'default', config: { engine: 'pglite' },+ });+ for (const session of ['wanted-session', 'absent-session']) {+ const result = await thinCall('postgres', [entity, '--session', session, '--limit', '1',+ '--budget-policy', 'facts_first', '--source', 'default', '--json'], { dispatch });+ expect({ code: result.exitCode, stderr: result.stderr }).toMatchObject({ code: 0 });+ expect(JSON.parse(result.stdout).facts.map((f: { fact: string }) => f.fact))+ .toEqual(session === 'wanted-session' ? ['older thin session match'] : []);+ expect(result.calls).toHaveLength(1);+ expect(result.calls[0].arguments).toMatchObject({ entity, session_id: session, limit: 1 });+ expect(result.localStoreCreated).toBe(false);+ }+ }, 60_000);});diff --git a/test/recall-entity-session-6938.test.ts b/test/recall-entity-session-6938.test.tsnew file mode 100644index 0000000000..99adc22ec4--- /dev/null+++ b/test/recall-entity-session-6938.test.ts@@ -0,0 +1,98 @@+/** #6938: entity and session intersect before LIMIT, with or without a window. */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine, NewFact } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { runRecall } from '../src/commands/recall.ts';+import { testBackends } from './helpers/test-backends.ts';++const ENTITY = 'people/session-example';+const SESSION = "wanted-'%_session";+const WANTED = 'older desired fact with literal 50%_done';+const OTHER = 'newer unrelated session fact';++for (const backend of testBackends()) describe(`entity/session intersection (${backend})`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const { setupDB, getEngine } = await import('./e2e/helpers.ts');+ await setupDB();+ engine = getEngine();+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('other-source', 'Other source')");+ const seed = (fact: string, session: string, date: string, extra: Partial<NewFact> = {}, source = 'default') =>+ engine.insertFact({ fact, kind: 'fact', entity_slug: ENTITY, source: 'test', source_session: session,+ valid_from: new Date(date), visibility: 'world', ...extra }, { source_id: source });+ await seed(WANTED, SESSION, '2020-01-01');+ await seed(OTHER, 'other-session', '2026-01-01');+ await seed('wanted session but another entity', SESSION, '2025-01-01', { entity_slug: 'people/someone-else' });+ await seed('private newest fact', SESSION, '2025-02-01', { visibility: 'private' });+ await seed('expired newest fact', SESSION, '2025-03-01');+ await engine.executeRaw("UPDATE facts SET expired_at = '2025-04-01' WHERE fact = 'expired newest fact'");+ await seed('TTL-lapsed newest fact', SESSION, '2025-04-01', { valid_until: new Date('2025-05-01') });+ await seed('another source newest fact', SESSION, '2025-05-01', {}, 'other-source');+ }, 120_000);+ afterAll(async () => {+ if (backend === 'postgres') {+ const { teardownDB } = await import('./e2e/helpers.ts');+ await teardownDB();+ } else await engine?.disconnect();+ });++ async function op(params: Record<string, unknown>) {+ const result = await dispatchToolCall(engine, 'recall', { entity: ENTITY, session_id: SESSION, limit: 1, ...params },+ { remote: true, sourceId: 'default' });+ expect(result.isError).toBeFalsy();+ return (JSON.parse(result.content[0].text).facts as Array<{ fact: string }>).map(f => f.fact);+ }+ async function cli(args: string[]) {+ const original = process.stdout.write;+ let output = '';+ process.stdout.write = ((chunk: string | Uint8Array) => {+ output += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+ try { await runRecall(engine, [ENTITY, '--session', SESSION, '--limit', '1', '--source', 'default', '--json', ...args]); }+ finally { process.stdout.write = original; }+ return (JSON.parse(output).facts as Array<{ fact: string }>).map(f => f.fact);+ }++ test('remote op applies session, entity, visibility and active fences before LIMIT', async () => {+ expect(await op({})).toEqual([WANTED]);+ expect(await op({ since: '2019-01-01' })).toEqual([WANTED]);+ });+ test('local CLI preserves the intersection without changing entity ordering', async () => {+ expect(await cli([])).toEqual(['private newest fact']);+ expect(await cli(['--since', '2019-01-01'])).toEqual(['private newest fact']);+ // Local callers may see private facts; grep selects the public fixture.+ expect(await cli(['--grep', '50%_done'])).toEqual([WANTED]);+ expect(await cli(['--grep', '50%_done', '--since', '2019-01-01'])).toEqual([WANTED]);+ });+ test('an absent session returns empty, not entity or text-fallback facts', async () => {+ expect(await op({ session_id: 'missing-session' })).toEqual([]);+ expect(await cli(['--session', 'missing-session'])).toEqual([]);+ });+ test('literal grep and session selectors compose before LIMIT', async () => {+ expect(await op({ grep: '50%_done' })).toEqual([WANTED]);+ expect(await op({ grep: '50Xdone' })).toEqual([]);+ });+ test('entity-only and session-only arms retain their selectors', async () => {+ expect(await op({ session_id: undefined })).toEqual([OTHER]);+ expect(await op({ entity: undefined })).toEqual(['wanted session but another entity']);+ });+ test('engine intersection preserves pagination, history and source isolation', async () => {+ const opts = { sessionId: SESSION, visibility: ['world'] as const };+ // Read through both storage adapters, without the operation's policy fold.+ const rows = await engine.listFactsByEntity('default', ENTITY, { ...opts, visibility: ['world'], limit: 1 });+ expect(rows.map(r => r.fact)).toEqual([WANTED]);+ expect(await engine.listFactsByEntity('default', ENTITY, { ...opts, visibility: ['world'], offset: 1 })).toEqual([]);+ const history = await engine.listFactsByEntity('default', ENTITY, { ...opts, visibility: ['world'], activeOnly: false });+ expect(history.map(r => r.fact)).toEqual(['TTL-lapsed newest fact', 'expired newest fact', WANTED]);+ expect((await engine.listFactsByEntity('other-source', ENTITY, { sessionId: SESSION })).map(r => r.fact))+ .toEqual(['another source newest fact']);+ });+});