Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): resolve contextual reindex by its expected source (#5291)

time-attack785d8e1e5b64
diff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
index c3b64cb4c7..ce7e068137 100644
--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts
+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
@@ -88,9 +88,11 @@ export function resolveContextualSynopsisLeaseSettings(
* `source_id` field in the payload that mismatches the loaded value
* triggers UnrecoverableError (stale/malicious payload defense).
*
- * `expected_source_id` is optional — when present, the handler verifies
- * it matches the loaded page's source_id. Lets the submitter (mode-switch
- * hook with known per-source plans) catch its own staleness.
+ * `expected_source_id` is optional — when present, the page is resolved in
+ * that source only; a same-slug page in another source is never selected,
+ * and a page missing from that source fails the job without re-embedding
+ * anything. Lets the submitter (mode-switch hook with known per-source
+ * plans) catch its own staleness.
*/
export interface ContextualReindexJobData {
page_slug: string;
@@ -131,24 +133,20 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerO
const data = parseJobData(ctx.data);
// Load page row to derive the authoritative source_id (D27 P2-1).
- // Without sourceId we can't do a lookup at all — fall back to
- // 'default' for the initial lookup, then if the page isn't found
- // there, surface as unrecoverable (the submitter should have
- // included expected_source_id).
- let foundPage = await tryLoadPageAcrossSources(engine, data.page_slug);
+ // With expected_source_id the lookup is scoped to that source and a
+ // miss is final (stale payload): falling back across sources would
+ // re-embed another source's same-slug page. Without it, try 'default'
+ // and then every live source.
+ const foundPage = data.expected_source_id
+ ? await engine.getPage(data.page_slug, { sourceId: data.expected_source_id })
+ : await tryLoadPageAcrossSources(engine, data.page_slug);
if (!foundPage) {
throw new UnrecoverableError(
- `Page not found for slug '${data.page_slug}'. ` +
- `Submitter should include expected_source_id or the page may have been deleted.`,
- );
- }
-
- // D27 P2-1: reject mismatched expected_source_id (stale payload).
- if (data.expected_source_id && data.expected_source_id !== foundPage.source_id) {
- throw new UnrecoverableError(
- `Source id mismatch for page '${data.page_slug}': expected ` +
- `'${data.expected_source_id}', page actually lives in ` +
- `'${foundPage.source_id}'. Stale payload?`,
+ data.expected_source_id
+ ? `Page not found for slug '${data.page_slug}' in its expected source. ` +
+ `The payload is stale or the page was deleted; nothing was re-embedded.`
+ : `Page not found for slug '${data.page_slug}'. ` +
+ `Submitter should include expected_source_id or the page may have been deleted.`,
);
}
diff --git a/test/contextual-reindex-lease-release.test.ts b/test/contextual-reindex-lease-release.test.ts
index 89119001f0..84a012cb27 100644
--- a/test/contextual-reindex-lease-release.test.ts
+++ b/test/contextual-reindex-lease-release.test.ts
@@ -5,10 +5,16 @@
* `typeof lease === 'number'` guard never released it and every slot idled
* to its TTL. PGLite parses safe-range int8 to Number, so only a fake engine
* reproduces the shape.
+ *
+ * #5276 — with expected_source_id the handler resolves the page in that
+ * source only. A same-slug page elsewhere must neither shadow it nor be
+ * re-embedded when the expected source lacks the page (PGLite fixture).
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { makeContextualReindexHandler } from '../src/core/minions/handlers/contextual-reindex-per-chunk.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import type { ReembedPageResult } from '../src/core/contextual-retrieval-service.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
type Call = { sql: string; params?: unknown[] };
const RELEASE_SQL = 'DELETE FROM subagent_rate_leases WHERE id = $1';
@@ -39,6 +45,36 @@ const SUCCESS: ReembedPageResult = {
const JOB = { id: 42, data: { page_slug: 'wiki/example' }, signal: new AbortController().signal } as never;
describe('contextual_reindex_per_chunk synopsis lease release', () => {
+ test('uses expected_source_id to resolve a duplicate slug in its intended source', async () => {
+ const getPageCalls: Array<{ slug: string; sourceId?: string }> = [];
+ const engine = {
+ async getPage(slug: string, opts?: { sourceId?: string }) {
+ getPageCalls.push({ slug, sourceId: opts?.sourceId });
+ if (opts?.sourceId === 'source-a') return { source_id: 'source-a' };
+ if (opts?.sourceId === 'source-b') return { source_id: 'source-b' };
+ return null;
+ },
+ async getConfig() { return null; },
+ };
+ let reembedSourceId: string | undefined;
+ const handler = makeContextualReindexHandler({
+ engine: engine as never,
+ reembedPage: async (args) => {
+ reembedSourceId = args.sourceId;
+ return SUCCESS;
+ },
+ });
+
+ await handler({
+ id: 43,
+ data: { page_slug: 'changelog', expected_source_id: 'source-a' },
+ signal: new AbortController().signal,
+ } as never);
+
+ expect(getPageCalls).toEqual([{ slug: 'changelog', sourceId: 'source-a' }]);
+ expect(reembedSourceId).toBe('source-a');
+ });
+
test('releases the lease acquired through a Postgres-shaped RETURNING id (native BigInt)', async () => {
const calls: Call[] = [];
const handler = makeContextualReindexHandler({
@@ -82,3 +118,103 @@ describe('contextual_reindex_per_chunk synopsis lease release', () => {
expect(calls.filter(c => c.sql === RELEASE_SQL)).toEqual([]);
});
});
+
+describe('contextual_reindex_per_chunk expected_source_id on a real engine (#5276)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('acme-example','acme-example') ON CONFLICT DO NOTHING");
+ });
+
+ const page = (marker: string) => ({ type: 'note' as const, title: 'Changelog', compiled_truth: `${marker} prose`, timeline: '', frontmatter: {} });
+
+ async function snapshot(sourceId: string) {
+ const rows = await engine.executeRaw<{ compiled_truth: string; updated_at: string }>(
+ 'SELECT compiled_truth, updated_at::text AS updated_at FROM pages WHERE slug = $1 AND source_id = $2',
+ ['notes/changelog', sourceId],
+ );
+ return rows[0];
+ }
+
+ test('a same-slug page in default does not shadow the expected source; the lease is taken and released', async () => {
+ await engine.putPage('notes/changelog', page('default-marker'), { sourceId: 'default' });
+ await engine.putPage('notes/changelog', page('acme-marker'), { sourceId: 'acme-example' });
+ const [job] = await engine.executeRaw<{ id: number }>(
+ "INSERT INTO minion_jobs (name, submission_authority) VALUES ('test-lease-owner', '{}'::jsonb) RETURNING id",
+ );
+ const reembedded: string[] = [];
+ const handler = makeContextualReindexHandler({
+ engine,
+ reembedPage: async (args) => {
+ reembedded.push(args.sourceId);
+ const lease = await args.acquireSynopsisLease!();
+ await args.releaseSynopsisLease!(lease);
+ return SUCCESS;
+ },
+ });
+
+ const result = await handler({
+ id: job!.id,
+ data: { page_slug: 'notes/changelog', expected_source_id: 'acme-example' },
+ signal: new AbortController().signal,
+ } as never);
+
+ expect(result).toEqual({ ok: true, mode_applied: 'per_chunk_synopsis', chunks_embedded: 1 });
+ expect(reembedded).toEqual(['acme-example']);
+ expect(await engine.executeRaw('SELECT id FROM subagent_rate_leases')).toEqual([]);
+ });
+
+ test('a page missing from the expected source fails the job and never touches the other source', async () => {
+ await engine.putPage('notes/changelog', page('default-marker'), { sourceId: 'default' });
+ const before = await snapshot('default');
+ let reembedCalls = 0;
+ const handler = makeContextualReindexHandler({
+ engine,
+ reembedPage: async () => { reembedCalls++; return SUCCESS; },
+ });
+
+ let message = '';
+ try {
+ await handler({
+ id: 44,
+ data: { page_slug: 'notes/changelog', expected_source_id: 'acme-example' },
+ signal: new AbortController().signal,
+ } as never);
+ } catch (err) {
+ expect((err as Error).name).toBe('UnrecoverableError');
+ message = (err as Error).message;
+ }
+
+ expect(message).toBe(
+ "Page not found for slug 'notes/changelog' in its expected source. " +
+ 'The payload is stale or the page was deleted; nothing was re-embedded.',
+ );
+ expect(reembedCalls).toBe(0);
+ expect(await snapshot('default')).toEqual(before);
+ expect(await engine.executeRaw('SELECT id FROM subagent_rate_leases')).toEqual([]);
+ });
+
+ test('control: without expected_source_id the legacy default-then-sources walk still resolves', async () => {
+ await engine.putPage('notes/changelog', page('acme-marker'), { sourceId: 'acme-example' });
+ const reembedded: string[] = [];
+ const handler = makeContextualReindexHandler({
+ engine,
+ reembedPage: async (args) => { reembedded.push(args.sourceId); return SUCCESS; },
+ });
+
+ await handler({ id: 45, data: { page_slug: 'notes/changelog' }, signal: new AbortController().signal } as never);
+
+ expect(reembedded).toEqual(['acme-example']);
+ });
+});