Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): bound each no-op settle pass and carry a per-process cursor
garrytan386d75ded68f
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 7c298464a8..626edc04df 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -16,7 +16,7 @@ import { publicationConcurrency } from './pool-capacity.ts';import { claimedHeadOrder } from './sync-window.ts';import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';import { runPersistenceEffects } from './effects.ts';-import { NOOP_SETTLE_BATCH, settleNoopEmbeddingEffects } from './embedding-noop-settle.ts';+import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';import { currentEmbeddingSignature } from '../embedding.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -175,6 +175,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private projectionWorker: Promise<unknown> | undefined;private effectsWorker: Promise<void> | undefined;private draining: { since: number; settled: number; ran: number; noticedAt: number } | undefined;+ private settleCursor: NoopSettleCursor | undefined;private topologyWorker: Promise<unknown> | undefined;private maintenanceWorker: Promise<unknown> | undefined;private nextMaintenance = 0;@@ -622,11 +623,13 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const signature = currentEmbeddingSignature();const drain = this.draining = { since: Date.now(), settled: 0, ran: 0, noticedAt: 0 };try {- for (let settled = signature ? NOOP_SETTLE_BATCH : 0; settled >= NOOP_SETTLE_BATCH && !this.stopping;) {- settled = await settleNoopEmbeddingEffects(this.engine, this.hostId, signature!);- drain.settled += settled;+ for (let done = !signature; !done && !this.stopping;) {+ const pass = await settleNoopEmbeddingEffects(this.engine, this.hostId, signature!, this.settleCursor);+ this.settleCursor = pass.cursor;+ done = pass.done;+ drain.settled += pass.settled;this.drainNotice(drain);- await yieldToEventLoop();+ if (!done) await yieldToEventLoop();}for (let ran = limit; ran >= limit && !this.stopping;) {ran = await runPersistenceEffects(this.engine, this.config, { hostId: this.hostId, limit, signal: this.abort.signal });diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 6114876c1a..5fc1b13599 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -23,6 +23,7 @@ import { AIConfigError, normalizeAIError } from '../ai/errors.ts';import { EMBEDDING_ZERO_NORM, isEmbeddingZeroNormError, type EmbeddingZeroNormError } from '../ai/embedding-guard.ts';import { isAIInvocationPolicyError, withAIInvocationPreflight } from '../ai/invocation-guard.ts';import { quoteIdentifier } from '../search/embedding-column.ts';+import type { ResolvedColumn } from '../types.ts';import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';import { sha256 } from './digest.ts';@@ -263,6 +264,15 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:else await finishPage(engine, effect, snapshot, result);}+/**+ * The chunk model an embedding effect counts as complete under: the explicit+ * model, else the legacy `embedding` column's signature without its trailing+ * `:dimensions`, else the write column's own model.+ */+export function embeddingCompletionModel(column: Pick<ResolvedColumn, 'name' | 'embeddingModel'>, signature: string, model?: string): string | null | undefined {+ return model ?? (column.name === 'embedding' ? signature.slice(0, signature.lastIndexOf(':')) : column.embeddingModel);+}+export async function readEmbeddingEffectProjection(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot,hostId: string, signature: string, model?: string) {return engine.transaction(async tx => {@@ -278,7 +288,7 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:p.embedding_signature=$2 AND cc.${quoteIdentifier(column.name)} IS NOT NULL AND cc.embedded_at IS NOT NULLAND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model IS NOT DISTINCT FROM $3 AS completeFROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1`,- [snapshot.page.id, signature, model ?? (column.name === 'embedding' ? signature.slice(0, signature.lastIndexOf(':')) : column.embeddingModel)]);+ [snapshot.page.id, signature, embeddingCompletionModel(column, signature, model)]);const complete = new Set(completion.filter(chunk => chunk.complete === true).map(chunk => chunk.id));const pending = prepared.chunks.filter(chunk => !complete.has(chunk.id));return { prepared, pending: pending.length && prepared.snapshot.page.contextual_retrieval_mode === 'per_chunk_synopsis' ? prepared.chunks : pending };diff --git a/src/core/persistence/embedding-noop-settle.ts b/src/core/persistence/embedding-noop-settle.tsindex 560ec86c8c..f137f9dfa3 100644--- a/src/core/persistence/embedding-noop-settle.ts+++ b/src/core/persistence/embedding-noop-settle.ts@@ -26,6 +26,7 @@ import { OperationError } from '../ops/contract.ts';import { embeddingWriteTarget } from '../page-state/projections.ts';import { quoteIdentifier } from '../search/embedding-column.ts';import { guardEffectSource } from './effect-recovery.ts';+import { embeddingCompletionModel } from './effects.ts';import type { PersistenceEffect } from './effect-model.ts';import { faultPoint } from './fault-points.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';@@ -39,24 +40,48 @@ const LEFT_FOR_RUNNER = new Set(['owner_unavailable', 'source_changed', 'recovertype Candidate = Pick<PersistenceEffect, 'id' | 'kind' | 'source_id' | 'source_incarnation' | 'worktree_id'>;-/** Settles up to `limit` no-op embedding effects claimable by `hostId`; resolves with how many it settled. */-export async function settleNoopEmbeddingEffects(engine: BrainEngine, hostId: string, signature: string, limit = NOOP_SETTLE_BATCH): Promise<number> {- // Most drains have no unattempted embedding effect at all: one indexed probe, no transaction.- const [due] = await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE kind='embedding' AND state='queued' AND attempts=0- AND next_attempt_at<=now() AND recovery IS NULL LIMIT 1`);- if (!due) return 0;+/**+ * How far a process's settle passes have looked, for one write column, model and signature. Effects at or below+ * `through` were each considered once; one that becomes a no-op later (vectors installed while it waited) takes the+ * runner path. Without it, a backlog that cannot settle (stale vectors, an unconfigured provider) would be walked in+ * full on every drain.+ */+export interface NoopSettleCursor { key: string; through: string }+export interface NoopSettlePass { settled: number; cursor: NoopSettleCursor; done: boolean }++/** One settle pass over effects past `after`, in id order; `done` once it reached the newest effect. */+export async function settleNoopEmbeddingEffects(engine: BrainEngine, hostId: string, signature: string,+ after?: NoopSettleCursor, limit = NOOP_SETTLE_BATCH): Promise<NoopSettlePass> {+ const { column } = await embeddingWriteTarget(engine);+ const expectedModel = embeddingCompletionModel(column, signature) ?? null;+ const key = `${column.name}\0${expectedModel ?? ''}\0${signature}`;+ const from = after?.key === key ? after.through : '0';+ // A drain with nothing new to consider costs one indexed read and opens no transaction.+ const [due] = await engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE id>$1::bigint AND kind='embedding' AND state='queued' AND attempts=0+ AND recovery IS NULL LIMIT 1`, [from]);+ if (!due) return { settled: 0, cursor: { key, through: from }, done: true };return engine.transaction(async tx => {await declarePersistenceProtocol(tx);- const { column, model } = await embeddingWriteTarget(tx);- const expectedModel = column.name === 'embedding' ? signature.slice(0, signature.lastIndexOf(':')) : column.embeddingModel ?? model;+ const [{ newest }] = await tx.executeRaw<{ newest: string }>('SELECT COALESCE(max(id),0)::text AS newest FROM persistence_effects');+ // The window is the next `limit` unattempted embedding effects by id, read from the primary key and locked;+ // the per-effect tests then run on that window only, so a pass costs at most `limit` effects whatever the+ // backlog holds and whatever the planner estimates for it.+ const rows = await tx.executeRaw<{ id: string; page_id: number | null }>(`SELECT e.id::text AS id, (e.data->>'page_id')::int AS page_id+ FROM persistence_effects e WHERE e.id>$1::bigint AND e.kind='embedding' AND e.state='queued' AND e.attempts=0 AND e.recovery IS NULL+ ORDER BY e.id LIMIT $2 FOR UPDATE SKIP LOCKED`, [from, limit]);+ const window = rows.map(row => row.id);+ // A short window reached the newest effect; a full one continues after its last effect.+ const done = window.length < limit;+ const cursor = { key, through: done ? newest : window[window.length - 1]! };+ if (!window.length) return { settled: 0, cursor, done };const vector = quoteIdentifier(column.name);- const candidates = await tx.executeRaw<Candidate>(`SELECT e.id, e.kind, e.source_id, e.source_incarnation, e.worktree_id+ const candidates = await tx.executeRaw<Candidate>(`SELECT e.id::text AS id, e.kind, e.source_id, e.source_incarnation, e.worktree_idFROM persistence_effects e- LEFT JOIN persistence_worktrees w ON w.id=e.worktree_idJOIN pages p ON p.id=(e.data->>'page_id')::int AND p.source_id=e.source_id- WHERE e.kind='embedding' AND e.state='queued' AND e.attempts=0 AND e.next_attempt_at<=now() AND e.recovery IS NULL+ WHERE e.id=ANY($4::text[]::bigint[]) AND p.id=ANY($5::int[]) AND e.next_attempt_at<=now()AND NOT (e.data ? 'targets') AND NOT (e.data ? 'source_scan') AND NOT (e.data ? 'retry_slugs') AND NOT (e.data ? 'parked')- AND (e.worktree_id IS NULL OR w.owner_host_id=$1::uuid) AND (e.worktree_id IS NULL OR ${refreshFenceClear('e')})+ AND (e.worktree_id IS NULL OR (EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=e.worktree_id AND w.owner_host_id=$1::uuid)+ AND ${refreshFenceClear('e')}))AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_effects mirror@@ -65,26 +90,26 @@ export async function settleNoopEmbeddingEffects(engine: BrainEngine, hostId: stAND p.embedding_signature=$2AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id=p.id AND NOT (cc.${vector} IS NOT NULLAND cc.embedded_at IS NOT NULL AND cc.embedded_text_hash IS NOT DISTINCT FROM md5(cc.chunk_text) AND cc.model IS NOT DISTINCT FROM $3))- ORDER BY e.next_attempt_at, e.id LIMIT $4- FOR UPDATE OF e SKIP LOCKED FOR SHARE OF p`, [hostId, signature, expectedModel, limit]);- if (!candidates.length) return 0;+ ORDER BY e.id+ FOR SHARE OF p`, [hostId, signature, expectedModel, window, rows.flatMap(row => row.page_id === null ? [] : [row.page_id])]);+ if (!candidates.length) return { settled: 0, cursor, done };const guarded = new Map<string, boolean>();const ids: string[] = [];for (const effect of candidates) {- const key = `${effect.source_id}\0${effect.source_incarnation}\0${effect.worktree_id ?? ''}`;- if (!guarded.has(key)) {- guarded.set(key, await guardEffectSource(tx, effect as PersistenceEffect, hostId).then(() => true, error => {+ const scope = `${effect.source_id}\0${effect.source_incarnation}\0${effect.worktree_id ?? ''}`;+ if (!guarded.has(scope)) {+ guarded.set(scope, await guardEffectSource(tx, effect as PersistenceEffect, hostId).then(() => true, error => {if (error instanceof OperationError && LEFT_FOR_RUNNER.has(error.code)) return false;throw error;}));}- if (guarded.get(key)) ids.push(String(effect.id));+ if (guarded.get(scope)) ids.push(String(effect.id));}- if (!ids.length) return 0;+ if (!ids.length) return { settled: 0, cursor, done };const settled = await tx.executeRaw(`UPDATE persistence_effects SET state='committed', error_code=NULL, attempts=attempts+1,data=data-'retry_slugs'-'target_failures'-'failing_target', execution_token=NULL, claim_expires_at=NULL, outcome='{}'::jsonb, updated_at=now()WHERE id=ANY($1::text[]::bigint[]) AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [ids]);await faultPoint('effect:embedding:settle', { effectId: ids[0] });- return settled.length;+ return { settled: settled.length, cursor, done };});}diff --git a/test/persistence-embedding-noop-settle.test.ts b/test/persistence-embedding-noop-settle.test.tsindex 157657c8ab..67a0356b5b 100644--- a/test/persistence-embedding-noop-settle.test.ts+++ b/test/persistence-embedding-noop-settle.test.ts@@ -17,7 +17,7 @@ import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';-import { runPersistenceEffects, type EffectWorkerOptions } from '../src/core/persistence/effects.ts';+import { embeddingCompletionModel, runPersistenceEffects, type EffectWorkerOptions } from '../src/core/persistence/effects.ts';import { settleNoopEmbeddingEffects } from '../src/core/persistence/embedding-noop-settle.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';@@ -108,7 +108,7 @@ for (const kind of testBackends()) {[[...noop, pending, ...Object.values(stale)].map(p => p.effectId)]);const gitBefore = await engine.executeRaw<{ id: string; state: string; attempts: number }>("SELECT id::text AS id,state,attempts FROM persistence_effects WHERE kind='git' ORDER BY id");- expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature)).toBe(2);+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(2);for (const p of noop) expect(await row(p.effectId)).toMatchObject({ state: 'committed', attempts: 1, outcome: {} });for (const p of [pending, ...Object.values(stale)]) expect((await row(p.effectId)).state).toBe('queued');// The settle never touches another kind.@@ -130,7 +130,7 @@ for (const kind of testBackends()) {const slow = await page('rows/slow', true);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now()+interval \'1 hour\' WHERE id=$1', [slow.effectId]);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [bulk.effectId]);- expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature)).toBe(1);+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(1);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [slow.effectId]);let calls = 0;await drainAll(async texts => { calls++; return texts.map(() => vector()); });@@ -153,7 +153,7 @@ for (const kind of testBackends()) {expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE request_id=ANY($1::uuid[]) AND state<>'committed' ORDER BY kind", [ids])).toEqual([{ kind: 'embedding' }, { kind: 'embedding' }]);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [bulk.effectId]);- expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature)).toBe(1);+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(1);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [slow.effectId]);let calls = 0;await drainAll(async texts => { calls++; return texts.map(() => vector()); });@@ -178,6 +178,71 @@ for (const kind of testBackends()) {.toEqual([{ compacted: true }, { compacted: true }]);});+ check('a backlog that cannot settle is considered once per process, and a new no-op past it still settles', async () => {+ await reset();+ const stale = [await page('cursor/stale-a', false), await page('cursor/stale-b', false)];+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [stale.map(p => p.effectId)]);+ const second = await settleNoopEmbeddingEffects(engine, localHostId(), signature);+ expect(second).toMatchObject({ settled: 0, done: true });+ const [{ newest }] = await engine.executeRaw<{ newest: string }>('SELECT max(id)::text AS newest FROM persistence_effects');+ expect(second.cursor.through).toBe(newest);+ // The next drain finds nothing past the cursor and opens no transaction.+ const transaction = engine.transaction.bind(engine);+ let opened = 0;+ engine.transaction = ((fn: never) => { opened++; return transaction(fn); }) as typeof engine.transaction;+ try { expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature, second.cursor)).toEqual({ settled: 0, cursor: second.cursor, done: true }); }+ finally { delete (engine as { transaction?: unknown }).transaction; }+ expect(opened).toBe(0);+ // A stale effect that becomes a no-op behind the cursor is the runner's; a new no-op past it settles here.+ const sealed = (await readProjectionSnapshot(engine, stale[0]!.slug, stale[0]!.sourceId))!;+ expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${stale[0]!.slug}`, embedding: vector(), model }], signature)).toBe(true);+ const fresh = await page('cursor/fresh', true);+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [[stale[0]!.effectId, fresh.effectId]]);+ expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature, second.cursor)).toMatchObject({ settled: 1, done: true });+ expect((await row(fresh.effectId)).state).toBe('committed');+ expect((await row(stale[0]!.effectId)).state).toBe('queued');+ // A different signature or write column starts over from the oldest effect.+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature, { ...second.cursor, key: 'other' })).settled).toBe(1);+ expect((await row(stale[0]!.effectId)).state).toBe('committed');+ });++ check('a full pass moves the cursor to its last candidate and the next pass continues past it', async () => {+ await reset();+ // Sweep the earlier cases' effects (none due) so the cursor starts at the newest effect.+ let start = await settleNoopEmbeddingEffects(engine, localHostId(), signature);+ while (!start.done) start = await settleNoopEmbeddingEffects(engine, localHostId(), signature, start.cursor);+ expect(start.settled).toBe(0);+ const noops = [await page('paged/a', true), await page('paged/b', true), await page('paged/c', true)];+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [noops.map(p => p.effectId)]);+ const first = await settleNoopEmbeddingEffects(engine, localHostId(), signature, start.cursor, 2);+ expect(first).toMatchObject({ settled: 2, done: false, cursor: { through: noops[1]!.effectId } });+ const next = await settleNoopEmbeddingEffects(engine, localHostId(), signature, first.cursor, 2);+ expect(next).toMatchObject({ settled: 1, done: true });+ for (const p of noops) expect((await row(p.effectId)).state).toBe('committed');+ });++ check('a sweep one effect at a time visits every unattempted embedding effect in numeric id order', async () => {+ await reset();+ // The next effect ids cross a power of ten, so a text ordering of ids would visit them out of order.+ await engine.executeRaw(`SELECT setval(pg_get_serial_sequence('persistence_effects','id'),+ (10::numeric ^ ceil(log(10, COALESCE(max(id),0)+20)))::bigint - 10) FROM persistence_effects`);+ for (let i = 0; i < 12; i++) await page(`sweep/n${i}`, false);+ const expected = (await engine.executeRaw<{ id: string }>(+ "SELECT e.id::text AS id FROM persistence_effects e WHERE e.kind='embedding' AND e.state='queued' AND e.attempts=0 AND e.recovery IS NULL ORDER BY e.id")).map(r => r.id);+ // Ids of different lengths: a text ordering would skip some of them.+ expect(new Set(expected.map(id => id.length)).size).toBeGreaterThan(1);+ const seen: string[] = [];+ let pass = await settleNoopEmbeddingEffects(engine, localHostId(), signature, undefined, 1);+ while (!pass.done) { seen.push(pass.cursor.through); pass = await settleNoopEmbeddingEffects(engine, localHostId(), signature, pass.cursor, 1); }+ expect(seen).toEqual(expected);+ });++ check('the completion model matches the runner for the legacy column and a named column, model names with colons included', async () => {+ expect(embeddingCompletionModel({ name: 'embedding', embeddingModel: undefined } as never, 'acme:embed:v2:1536')).toBe('acme:embed:v2');+ expect(embeddingCompletionModel({ name: 'embedding_voyage', embeddingModel: 'voyage:voyage-3' } as never, 'acme:embed:v2:1536')).toBe('voyage:voyage-3');+ expect(embeddingCompletionModel({ name: 'embedding', embeddingModel: undefined } as never, 'acme:embed:v2:1536', 'explicit:model')).toBe('explicit:model');+ });+check('a crash inside the settle leaves every row queued and unattempted', async () => {await reset();const a = await page('crash/a', true);@@ -187,7 +252,7 @@ for (const kind of testBackends()) {await expect(settleNoopEmbeddingEffects(engine, localHostId(), signature)).rejects.toThrow('crash inside the settle');installFaultHook(undefined);for (const p of [a, b]) expect(await row(p.effectId)).toMatchObject({ state: 'queued', attempts: 0, outcome: null, execution_token: null });- expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature)).toBe(2);+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(2);});check('an archived or replaced source and a deleted page are left for the runner', async () => {@@ -197,7 +262,7 @@ for (const kind of testBackends()) {await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [archived.sourceId]);await engine.executeRaw('UPDATE pages SET deleted_at=now() WHERE id=$1', [deleted.pageId]);await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [[archived.effectId, deleted.effectId]]);- expect(await settleNoopEmbeddingEffects(engine, localHostId(), signature)).toBe(0);+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(0);for (const p of [archived, deleted]) expect((await row(p.effectId)).state).toBe('queued');});});