Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): serve drain yields and settles no-op embedding effects in bulk
garrytanfb1f84505c5a
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 630491242f..7c298464a8 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -16,6 +16,8 @@ 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 { currentEmbeddingSignature } from '../embedding.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';@@ -42,6 +44,10 @@ export interface AbandonedPreparation { request_id: string; operation: string; sexport const ABANDONED_STOP_GRACE_MS = 5_000;/** #6278: abandoned preparations past the ceiling this process tolerates before it stops claiming and reports `restart_required`. */export const DEFAULT_ZOMBIE_CAP = 1;+/** An effects drain running this long names itself on stderr (serve), then again at this cadence. */+const DRAIN_NOTICE_AFTER_MS = 5_000;+const DRAIN_NOTICE_EVERY_MS = 10_000;+const yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));/** When this process started; on PGLite no claim written earlier can belong to a live owner. */const PROCESS_STARTED_AT = new Date(performance.timeOrigin);/** #5801: the phase a connection checkout belongs to, carried through its async chain. */@@ -168,6 +174,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private rootRetryAfter = new Map<string, number>();private projectionWorker: Promise<unknown> | undefined;private effectsWorker: Promise<void> | undefined;+ private draining: { since: number; settled: number; ran: number; noticedAt: number } | undefined;private topologyWorker: Promise<unknown> | undefined;private maintenanceWorker: Promise<unknown> | undefined;private nextMaintenance = 0;@@ -207,7 +214,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** #6278 test seam: pins budgets, ceiling, attempt limit or the switch over the brain's config. */preparationBudgets?: Partial<EffectivePreparationPolicy>;/** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */- zombieCap?: number } = {}) {+ zombieCap?: number;+ /** Write the long-drain progress line on stderr (serve; never a CLI command that may print --json). */+ drainNotice?: boolean } = {}) {this.hostId = opts.hostId ?? localHostId();this.statements = consumerStatementEngine(engine);}@@ -603,11 +612,40 @@ export class PersistenceConsumer implements PersistenceConsumerLike {});this.active.add(task);}- /** Effects keep pace with publication: full batches continue without waiting for the next tick. */+ /**+ * Effects keep pace with publication: full batches continue without waiting for the next tick. No-op embedding+ * effects settle in bulk first. Each batch yields to the event loop, so a long drain never holds requests back+ * (PGLite queries resolve as one microtask chain that would otherwise starve stdin).+ */private async drainEffects(): Promise<void> {const limit = 20;- while (!this.stopping && await runPersistenceEffects(this.engine, this.config,- { hostId: this.hostId, limit, signal: this.abort.signal }) >= limit);+ 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;+ this.drainNotice(drain);+ 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 });+ drain.ran += ran;+ this.drainNotice(drain);+ if (ran >= limit) await yieldToEventLoop();+ }+ } finally {+ this.draining = undefined;+ if (drain.noticedAt) this.drainNotice(drain, true);+ }+ }+ /** A drain past DRAIN_NOTICE_AFTER_MS names itself on stderr every DRAIN_NOTICE_EVERY_MS, and once when it ends (serve only). */+ private drainNotice(drain: NonNullable<PersistenceConsumer['draining']>, done = false): void {+ const now = Date.now();+ if (!this.opts.drainNotice || (!done && (now - drain.since < DRAIN_NOTICE_AFTER_MS || now - drain.noticedAt < DRAIN_NOTICE_EVERY_MS))) return;+ drain.noticedAt = now;+ process.stderr.write(`[persistence] phase=effects_drain state=${done ? 'done' : 'running'} settled_noop_embeddings=${drain.settled} ran=${drain.ran}`+ + ` elapsed_s=${Math.round((now - drain.since) / 1000)}; requests are served while it drains; status: gbrain sources writer status --json\n`);}foregroundCompletions(worktreeId: string): number { return this.foregroundCounts.get(worktreeId) ?? 0; }/** CEO-A7: this process holds the claim, so its outcome reaches waiters through `onSettled` without a read. */@@ -622,6 +660,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** #6278: abandoned preparations past the ceiling have reached this process's cap; it claims nothing more until it restarts. */restartRequired(): boolean { return this.zombies.size >= (this.opts.zombieCap ?? DEFAULT_ZOMBIE_CAP); }status() {+ const drain = this.draining;const { deadlines, syncMs, maintenanceMs, ceilingMs, maxAttempts } = this.policy;return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,sampled_at: new Date().toISOString(), observation_scope: 'current_process_reset_on_restart',@@ -633,6 +672,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {abandoned_preparations: this.abandoned.size,outlived_ceiling: [...this.zombies.values()].map(value => ({ ...value })),restart_required: this.restartRequired(),+ // The effects drain in progress: since when, no-op embedding effects settled in bulk, effects run.+ ...(drain ? { draining: { since: new Date(drain.since).toISOString(), settled_noop_embeddings: drain.settled, ran: drain.ran } } : {}),// #6317: which connection this consumer's statements take, and whether the ordinary pool is a transaction-mode pooler.connection: consumerConnectionRoute(this.engine),...(this.lastError ? { last_error: { ...this.lastError } } : {}) };diff --git a/src/core/persistence/embedding-noop-settle.ts b/src/core/persistence/embedding-noop-settle.tsnew file mode 100644index 0000000000..560ec86c8c--- /dev/null+++ b/src/core/persistence/embedding-noop-settle.ts@@ -0,0 +1,90 @@+/**+ * Settles queued embedding effects that have nothing left to do, in bulk.+ *+ * A classic import followed by `gbrain embed --stale` (or a restored or moved+ * brain) can leave tens of thousands of queued page embedding effects whose+ * chunks already carry current vectors. Each one would otherwise take a claim,+ * a guard transaction, a projection read and a completion update before+ * reaching the outcome the effect runner records when nothing is pending.+ *+ * An effect is settled here only when the runner would find nothing to embed:+ * a plain page effect (no targets, scan, retry slugs or parked targets) never+ * attempted, ready and claimable by this host as `claimPersistenceEffect`+ * would claim it, whose source passes `guardEffectSource`, whose page is live+ * at the effect's revision with its text projection sealed there, and whose+ * every chunk passes `readEmbeddingEffectProjection`'s completion test for the+ * current signature, write column and model. The row ends exactly as the+ * runner's own claim and completion leave it (state, outcome, attempts,+ * cleared claim). Every other effect is left for the runner.+ *+ * No effect kind is ordered after a page embedding effect: the claim order is+ * `next_attempt_at, id` across kinds, only Git groups and withdrawal mirrors+ * gate other effects, and an embedding effect gates nothing.+ */+import type { BrainEngine } from '../engine.ts';+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 type { PersistenceEffect } from './effect-model.ts';+import { faultPoint } from './fault-points.ts';+import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';+import { refreshFenceClear } from './worktree-refresh-schema.ts';++/** At most this many effects settle in one statement. */+export const NOOP_SETTLE_BATCH = 200;++/** Guard failures that leave an effect for the runner, which records them as it does today. */+const LEFT_FOR_RUNNER = new Set(['owner_unavailable', 'source_changed', 'recovery_required']);++type 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;+ 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 vector = quoteIdentifier(column.name);+ const candidates = await tx.executeRaw<Candidate>(`SELECT e.id, e.kind, e.source_id, e.source_incarnation, e.worktree_id+ FROM persistence_effects e+ LEFT JOIN persistence_worktrees w ON w.id=e.worktree_id+ JOIN 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+ 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 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+ WHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state<>'committed')+ AND p.deleted_at IS NULL AND p.knowledge_revision=e.revision AND p.text_projection_revision=p.knowledge_revision+ AND p.embedding_signature=$2+ AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id=p.id AND NOT (cc.${vector} IS NOT NULL+ AND 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;+ 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 => {+ if (error instanceof OperationError && LEFT_FOR_RUNNER.has(error.code)) return false;+ throw error;+ }));+ }+ if (guarded.get(key)) ids.push(String(effect.id));+ }+ if (!ids.length) return 0;+ 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;+ });+}diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex f63a266ecc..ffcb8fa5a6 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -13,7 +13,7 @@ import type { PublicationHooks } from './coordinator.ts';import type { WriteRequest } from './model.ts';export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];-export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`+export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'| 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'| 'consumer:preparing' | 'lane:applied';/**diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 2ddc8f1220..251e489319 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -120,7 +120,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfreturn prior.consumer;}const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,- { onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });+ { drainNotice: claimOwnerKind() === 'serve', onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });const kind = claimOwnerKind();const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }diff --git a/src/core/pglite-engine/checkpoint-guard.ts b/src/core/pglite-engine/checkpoint-guard.tsindex 88106e775b..531e23ff30 100644--- a/src/core/pglite-engine/checkpoint-guard.ts+++ b/src/core/pglite-engine/checkpoint-guard.ts@@ -37,9 +37,25 @@ export function checkpointGuardThreshold(maxWalBytes: number, segmentBytes: numbreturn Math.min(CHECKPOINT_GUARD_MAX_BYTES, Math.max(segmentBytes, (segments - 1) * segmentBytes) / 2);}+/**+ * A probe is reused for this long, so a run of small writes reads+ * pg_control_checkpoint() about once per window instead of once per statement+ * (an effects drain issued four probes per effect).+ */+export const CHECKPOINT_PROBE_REUSE_MS = 50;+/**+ * The WAL rate the reuse window assumes PGLite never exceeds: about 5x the+ * peak measured for bulk chunk and vector inserts (205 MB/s; one 2,000-row+ * vector insert writes 15.7 MB). A probe is reused only while its reading plus+ * a full window at this rate stays under the threshold, so no write can cross+ * the threshold unprobed.+ */+export const PGLITE_WAL_BYTES_PER_SECOND_BOUND = 1024 ** 3;+export class PgliteCheckpointGuard {private threshold: number | undefined;private warned = false;+ private lastProbe: { at: number; walSinceRedo: number } | undefined;private tail: Promise<void> = Promise.resolve();private outermost = 0;@@ -74,21 +90,22 @@ export class PgliteCheckpointGuard {*/async runStatement<T>(query: Query, statement: () => Promise<T>): Promise<T> {const result = statement();- if (this.outermost > 0) return result;+ if (this.outermost > 0 || this.probeFresh()) return result;const probe = this.issueProbe(this.override ?? query);let value: T;try { value = await result; } catch (error) { void probe.catch(() => undefined); throw error; }if (await this.overThreshold(probe)) {// The write committed; a failed CHECKPOINT here warns instead of failing it, and the next probe retries.- try { await (this.override ?? query)('CHECKPOINT'); } catch (error) { this.warnOnce(error); }+ try { await (this.override ?? query)('CHECKPOINT'); this.lastProbe = undefined; } catch (error) { this.warnOnce(error); }}return value;}private async beforeOutermostTransaction(query: Query): Promise<void> {- if (!await this.overThreshold(this.issueProbe(query))) return;+ if (this.probeFresh() || !await this.overThreshold(this.issueProbe(query))) return;try {await query('CHECKPOINT');+ this.lastProbe = undefined;} catch (error) {throw new GBrainError('PGLite checkpoint failed',`a top-level CHECKPOINT before the next write transaction failed (${error instanceof Error ? error.message : String(error)}); the transaction was not started`,@@ -114,6 +131,7 @@ export class PgliteCheckpointGuard {}const walSinceRedo = Number(since!.since_redo);if (!Number.isFinite(walSinceRedo)) throw new Error('WAL position is unavailable');+ this.lastProbe = { at: Date.now(), walSinceRedo };return walSinceRedo >= this.threshold;} catch (error) {this.warnOnce(error);@@ -121,6 +139,13 @@ export class PgliteCheckpointGuard {}}+ /** The last probe is recent and leaves a full window of WAL at the bound under the threshold, so this write needs no new probe. */+ private probeFresh(): boolean {+ const last = this.lastProbe;+ return last !== undefined && this.threshold !== undefined && Date.now() - last.at < CHECKPOINT_PROBE_REUSE_MS+ && last.walSinceRedo + PGLITE_WAL_BYTES_PER_SECOND_BOUND * CHECKPOINT_PROBE_REUSE_MS / 1000 < this.threshold;+ }+private warnOnce(error: unknown): void {if (this.warned) return;this.warned = true;diff --git a/test/persistence-drain-latency.serial.test.ts b/test/persistence-drain-latency.serial.test.tsnew file mode 100644index 0000000000..feb5d93c44--- /dev/null+++ b/test/persistence-drain-latency.serial.test.ts@@ -0,0 +1,129 @@+/**+ * Forced probe: a request answers while a large effects backlog drains.+ *+ * Protects: a freshly imported PGLite brain carried ~47k queued embedding+ * effects whose chunks `embed --stale` had already embedded. The serve+ * consumer drained them one claim at a time, and PGLite resolves its queries+ * as one microtask chain, so stdin was not read until the drain ended: the+ * first tool call took 230-290 s. Now no-op embedding effects settle in bulk+ * and the drain yields to the event loop between batches, so a tool call+ * issued at any point of the drain answers within DRAIN_ANSWER_BOUND_MS.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';+import { installPageEmbeddings, installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withEnv } from './helpers/with-env.ts';++/** Queued no-op embedding effects in the backlog (the 55k brain carried 46,685). */+const BACKLOG = 8_000;+/** Every tool call during the drain answers within this. Before the fix one waited for the whole drain. */+const DRAIN_ANSWER_BOUND_MS = 2_000;+const MODEL = 'openai:text-embedding-3-small';++describe('effects drain latency (PGLite)', () => {+ let engine: PGLiteEngine;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-drain-latency-'));+ configureGateway({ embedding_model: MODEL, embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-not-used' } });+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(scratch, 'brain') }); await engine.initSchema();+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine?.disconnect();+ resetGateway();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });++ /** One embedded page whose embedding effect is a no-op, cloned into BACKLOG queued requests and effects. */+ async function backlog(): Promise<string> {+ await registerLocalWriter(engine, 'cli');+ const sourceId = 'default';+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const slug = 'notes/backlog';+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, source.incarnation, slug);+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: source.incarnation, slug, requestId: randomUUID(), callerIntent: { body: 'b' }, intent: { body: 'b' } });+ const row = (await claimNextWrite(engine, localHostId()))!;+ await publishMutation(engine, row, { observedRevision: null, apply: async tx => {+ await tx.putPage(slug, { type: 'note', title: 'Backlog', compiled_truth: 'Widget Co renewal notes.', timeline: '', frontmatter: {} }, { sourceId }); return {};+ } }, localHostId());+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Widget Co renewal notes.' }], { seal: true });+ const sealed = (await readProjectionSnapshot(engine, slug, sourceId))!;+ expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Widget Co renewal notes.',+ embedding: new Float32Array(1536).fill(0.1), model: MODEL }], `${MODEL}:1536`)).toBe(true);+ await engine.executeRaw("UPDATE persistence_effects SET state='committed', outcome='{}'::jsonb WHERE kind<>'embedding'");+ // Clone the committed request and its queued no-op effect: every clone is its own request, as an import leaves them.+ const columns = async (table: string, skip: string[]) => (await engine.executeRaw<{ c: string }>(+ `SELECT column_name AS c FROM information_schema.columns WHERE table_name=$1 AND table_schema='public' ORDER BY ordinal_position`, [table]))+ .map(r => r.c).filter(c => !skip.includes(c));+ const requestCols = await columns('persistence_requests', ['id', 'request_id', 'sequence']);+ const effectCols = await columns('persistence_effects', ['id', 'request_id']);+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ await tx.executeRaw(`CREATE TEMP TABLE clone_ids ON COMMIT DROP AS SELECT gen_random_uuid() AS id, gen_random_uuid() AS request_id FROM generate_series(1,${BACKLOG})`);+ await tx.executeRaw(`INSERT INTO persistence_requests (id, request_id, ${requestCols.join(',')})+ SELECT c.id, c.request_id, ${requestCols.map(col => `r.${col}`).join(',')} FROM clone_ids c CROSS JOIN persistence_requests r WHERE r.id=$1::uuid`, [row.id]);+ await tx.executeRaw(`INSERT INTO persistence_effects (request_id, ${effectCols.join(',')})+ SELECT c.id, ${effectCols.map(col => `e.${col}`).join(',')} FROM clone_ids c CROSS JOIN persistence_effects e WHERE e.request_id=$1::uuid AND e.kind='embedding'`, [row.id]);+ });+ const [{ n }] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE kind='embedding' AND state='queued'");+ expect(n).toBe(BACKLOG + 1);+ return slug;+ }++ test(`a tool call answers within ${DRAIN_ANSWER_BOUND_MS} ms while ${BACKLOG} no-op embedding effects drain`, () => withEnv({ GBRAIN_HOME: scratch }, async () => {+ const slug = await backlog();+ // A CLI process (which may print --json on stdout) never writes the drain notice; only serve does.+ const stderrWrite = process.stderr.write.bind(process.stderr);+ const notices: string[] = [];+ process.stderr.write = ((chunk: string | Uint8Array, ...rest: never[]) => {+ if (String(chunk).includes('phase=effects_drain')) notices.push(String(chunk));+ return stderrWrite(chunk, ...rest);+ }) as typeof process.stderr.write;+ const consumer = startPersistenceConsumer(engine, { engine: 'pglite' });+ consumer.wake();+ // A client calls a tool every 50 ms while the backlog drains: no call may wait past the bound, and neither may+ // the event loop (the gap between one call's answer and the next call starting).+ const queued = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE kind='embedding' AND state<>'committed'"))[0]!.n;+ let worstAnswerMs = 0, worstGapMs = 0, calls = 0, callsDuringDrain = 0;+ const deadline = Date.now() + 120_000;+ try {+ for (let pending = await queued(); pending > 0 && Date.now() < deadline; pending = await queued()) {+ const started = performance.now();+ const answer = await dispatchToolCall(engine, 'get_page', { slug }, { remote: false, sourceId: 'default', config: { engine: 'pglite' } } as never);+ expect(answer.isError).toBeFalsy();+ worstAnswerMs = Math.max(worstAnswerMs, performance.now() - started);+ calls++;+ if (pending < BACKLOG + 1) callsDuringDrain++;+ const slept = performance.now();+ await Bun.sleep(50);+ worstGapMs = Math.max(worstGapMs, performance.now() - slept - 50);+ }+ } finally { process.stderr.write = stderrWrite; }+ console.log(JSON.stringify({ backlog: BACKLOG, calls, calls_during_drain: callsDuringDrain, worst_answer_ms: Math.round(worstAnswerMs), worst_loop_gap_ms: Math.round(worstGapMs) }));+ expect(await queued()).toBe(0);+ expect(callsDuringDrain).toBeGreaterThan(0);+ expect(notices).toEqual([]);+ expect({ worstAnswerMs: Math.round(worstAnswerMs), within: worstAnswerMs < DRAIN_ANSWER_BOUND_MS }).toMatchObject({ within: true });+ expect({ worstGapMs: Math.round(worstGapMs), within: worstGapMs < DRAIN_ANSWER_BOUND_MS }).toMatchObject({ within: true });+ // Every effect settled exactly once.+ const [{ attempts }] = await engine.executeRaw<{ attempts: number }>("SELECT max(attempts)::int AS attempts FROM persistence_effects WHERE kind='embedding'");+ expect(attempts).toBe(1);+ }), 180_000);+});diff --git a/test/persistence-embedding-noop-settle.test.ts b/test/persistence-embedding-noop-settle.test.tsnew file mode 100644index 0000000000..157657c8ab--- /dev/null+++ b/test/persistence-embedding-noop-settle.test.ts@@ -0,0 +1,204 @@+/**+ * Bulk settle of no-op embedding effects (embedding-noop-settle.ts).+ *+ * Protects: an import followed by `embed --stale` left ~47k queued page+ * embedding effects whose chunks were already embedded; the serve drain ran+ * each through a claim, a guard, a projection read and a completion, and the+ * first tool call waited for all of them. The bulk settle commits only true+ * no-ops and leaves the row exactly as the runner's own no-op completion+ * does; every effect with anything left to embed (or any doubt) still runs,+ * and a crash inside the settle leaves every row queued.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+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 { 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';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite, compactWriteReceipts, getWriteRequestProgress } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { installPageEmbeddings, installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+const signature = 'test:model:1536';+const model = 'test:model';+const vector = () => new Float32Array(1536).fill(0.1);++for (const kind of testBackends()) {+ describe(`no-op embedding settle ${kind}`, () => {+ let engine: BrainEngine;+ let scratch: string;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-noop-settle-'));+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(scratch, 'brain') }); await engine.initSchema();+ }+ }, 120_000);+ afterAll(async () => {+ await engine?.disconnect();+ if (close) await close();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ afterEach(() => installFaultHook(undefined));+ const check = (name: string, fn: () => Promise<void>) => test(name, () => withEnv({ GBRAIN_HOME: scratch }, fn), 120_000);++ /** One published page with its sealed projection; `embedded` installs current vectors. Returns its embedding effect. */+ async function page(slug: string, embedded: boolean) {+ await registerLocalWriter(engine, 'cli');+ const sourceId = `noop-${randomUUID()}`;+ const [source] = await engine.executeRaw<{ incarnation: string }>('INSERT INTO sources(id,name) VALUES($1,$1) RETURNING incarnation', [sourceId]);+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, source.incarnation, slug);+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: source.incarnation, slug, requestId: randomUUID(), callerIntent: { body: slug }, intent: { body: slug } });+ const row = (await claimNextWrite(engine, localHostId()))!;+ await publishMutation(engine, row, { observedRevision: null, apply: async tx => {+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Body of ${slug}`, timeline: '', frontmatter: {} }, { sourceId }); return {};+ } }, localHostId());+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${slug}` }], { seal: true });+ if (embedded) {+ const sealed = (await readProjectionSnapshot(engine, slug, sourceId))!;+ expect(await installPageEmbeddings(engine, sealed, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Body of ${slug}`, embedding: vector(), model }], signature)).toBe(true);+ }+ // Only embedding effects are due; Git and other effects of these writes wait.+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'embedding'");+ const [effect] = await engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [row.id]);+ const [{ id: pageId }] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ return { sourceId, slug, effectId: effect.id, pageId, requestId: row.id };+ }+ const row = async (effectId: string) => (await engine.executeRaw<Record<string, unknown>>(+ `SELECT state, attempts, error_code, outcome, data, execution_token, claim_expires_at, recovery FROM persistence_effects WHERE id=$1`, [effectId]))[0]!;+ async function drainAll(embed: NonNullable<EffectWorkerOptions['embedding']>['embed']) {+ while (await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 20, embedding: { signature, model, embed } }) >= 20);+ }+ /** Settle every due no-op, then park whatever is left so the next case starts clean. */+ async function reset() {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE state='queued'");+ }++ check('settles only true no-ops in a mixed queue; the rest still embed', async () => {+ await reset();+ const noop = [await page('mixed/noop-a', true), await page('mixed/noop-b', true)];+ const pending = await page('mixed/pending', false);+ const stale: Record<string, Awaited<ReturnType<typeof page>>> = {};+ for (const kind of ['null-vector', 'text-hash', 'model', 'signature', 'unsealed', 'attempted'] as const) {+ const p = stale[kind] = await page(`mixed/stale-${kind}`, true);+ if (kind === 'null-vector') await engine.executeRaw('UPDATE content_chunks SET embedding=NULL WHERE page_id=$1', [p.pageId]);+ else if (kind === 'text-hash') await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash='stale' WHERE page_id=$1", [p.pageId]);+ else if (kind === 'model') await engine.executeRaw("UPDATE content_chunks SET model='old:model' WHERE page_id=$1", [p.pageId]);+ else if (kind === 'signature') await engine.executeRaw("UPDATE pages SET embedding_signature='old' WHERE id=$1", [p.pageId]);+ else if (kind === 'unsealed') await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [p.pageId]);+ else await engine.executeRaw('UPDATE persistence_effects SET attempts=1 WHERE id=$1', [p.effectId]);+ }+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='embedding' AND state='queued' AND source_id LIKE 'noop-%' AND id=ANY($1::text[]::bigint[])",+ [[...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);+ 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.+ expect(await engine.executeRaw("SELECT id::text AS id,state,attempts FROM persistence_effects WHERE kind='git' ORDER BY id")).toEqual(gitBefore);++ // Everything left runs as before: the page without vectors and every stale one embed; the attempted no-op+ // completes through the runner without provider work; the unsealed one waits for its projection.+ const embedded: string[] = [];+ await drainAll(async texts => { embedded.push(...texts); return texts.map(() => vector()); });+ const reembedded = ['mixed/pending', 'mixed/stale-null-vector', 'mixed/stale-text-hash', 'mixed/stale-model', 'mixed/stale-signature'];+ expect(reembedded.filter(slug => !embedded.some(text => text.includes(`Body of ${slug}`)))).toEqual([]);+ expect(embedded.filter(text => /Body of mixed\/(noop-|stale-attempted)/.test(text))).toEqual([]);+ for (const p of [pending, ...Object.values(stale).filter(p => p.slug !== 'mixed/stale-unsealed')]) expect((await row(p.effectId)).state).toBe('committed');+ });++ check('a settled no-op ends with the same row the runner leaves for one', async () => {+ await reset();+ const bulk = await page('rows/bulk', true);+ 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);+ 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()); });+ expect(calls).toBe(0);+ const strip = (r: Record<string, unknown>) => ({ ...r, data: { ...(r.data as Record<string, unknown>), page_id: undefined, slug: undefined } });+ expect(strip(await row(bulk.effectId))).toEqual(strip(await row(slow.effectId)));+ const requests = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT state, outcome IS NOT NULL AS has_outcome, recovery FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY slug', [[bulk.requestId, slow.requestId]]);+ expect(requests[0]).toEqual(requests[1]);+ });++ check('a request whose only open effect is a no-op embedding finishes the same through either path', async () => {+ await reset();+ const bulk = await page('request/bulk', true);+ const slow = await page('request/slow', true);+ const ids = [bulk.requestId, slow.requestId];+ // Every other effect of both requests runs first, so the embedding effect is each request's only open one.+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=CASE WHEN kind='embedding' THEN now()+interval '1 hour' ELSE now() END WHERE request_id=ANY($1::uuid[])", [ids]);+ await drainAll(async texts => texts.map(() => vector()));+ 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);+ 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()); });+ expect(calls).toBe(0);++ const identity = ['id', 'request_id', 'idempotency_key', 'digest', 'slug', 'source_id', 'source_incarnation', 'sequence', 'principal', 'authority',+ 'intent', 'caller_intent'];+ // Times and generated tokens differ between any two requests; every other value must match.+ const opaque = (v: unknown): unknown => v instanceof Date || (typeof v === 'string' && /^\d{4}-\d\d-\d\dT|^[0-9a-f]{8}-[0-9a-f]{4}-/.test(v)) ? '<opaque>'+ : Array.isArray(v) ? v.map(opaque) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, opaque(x)])) : v;+ const strip = (r: Record<string, unknown>) => opaque(Object.fromEntries(Object.entries(r).filter(([key]) => !identity.includes(key)))) as Record<string, unknown>;+ const request = async (id: string) => strip((await engine.executeRaw<Record<string, unknown>>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id]))[0]!);+ const effects = async (id: string) => (await engine.executeRaw<Record<string, unknown>>(+ "SELECT * FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind", [id])).map(e => ({ ...strip(e), data: { ...(e.data as object), page_id: undefined, slug: undefined, relative_path: undefined, expected_hash: undefined } }));+ expect(await request(bulk.requestId)).toEqual(await request(slow.requestId));+ expect(await effects(bulk.requestId)).toEqual(await effects(slow.requestId));+ const progress = async (id: string) => { const p = await getWriteRequestProgress(engine, id); return p && strip(p as unknown as Record<string, unknown>); };+ expect(await progress(bulk.requestId)).toEqual(await progress(slow.requestId));+ // Receipt compaction waits for every effect of a request to commit; both receipts are now eligible.+ await compactWriteReceipts(engine, 0);+ expect(await engine.executeRaw<{ compacted: boolean }>('SELECT compacted FROM persistence_requests WHERE id=ANY($1::uuid[])', [ids]))+ .toEqual([{ compacted: true }, { compacted: true }]);+ });++ check('a crash inside the settle leaves every row queued and unattempted', async () => {+ await reset();+ const a = await page('crash/a', true);+ const b = await page('crash/b', true);+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=ANY($1::text[]::bigint[])', [[a.effectId, b.effectId]]);+ installFaultHook(point => { if (point === 'effect:embedding:settle') throw new Error('crash inside the settle'); });+ 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);+ });++ check('an archived or replaced source and a deleted page are left for the runner', async () => {+ await reset();+ const archived = await page('guard/archived', true);+ const deleted = await page('guard/deleted', true);+ 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);+ for (const p of [archived, deleted]) expect((await row(p.effectId)).state).toBe('queued');+ });+ });+}diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.tsindex 6e55d5ed42..2c0bb2a801 100644--- a/test/persistence-git-coalescing-5530.slow.test.ts+++ b/test/persistence-git-coalescing-5530.slow.test.ts@@ -37,6 +37,7 @@ import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';const HOOK = '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n';@@ -410,6 +411,51 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kindexpect(row).toEqual({ state: 'queued', blocked_reason: 'writer_busy', claim_phase: null });} finally { await held.release(); await disposePersistenceConsumer(engine); }}), 300_000);+ // The no-op embedding settle (embedding-noop-settle.ts) under the same backlog: the drain also settles queued embedding+ // effects whose chunks already carry current vectors, yielding between batches; the write still publishes within its+ // wait, the settle never touches a Git row, and every effect still commits once.+ test('a write admitted behind a Git backlog and a no-op embedding backlog publishes within the write wait', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), BACKLOG));+ // Every seeded page is already embedded at the current signature, as `embed --stale` leaves an import.+ const [{ type }] = await engine.executeRaw<{ type: string }>("SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attname='embedding'");+ const dims = Number(/vector\((\d+)\)/.exec(type)![1]);+ const model = 'openai:text-embedding-3-small';+ configureGateway({ embedding_model: model, embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test-not-used' } });+ try {+ await engine.executeRaw(`UPDATE content_chunks SET embedding=$1::vector, embedded_at=now(), embedded_text_hash=md5(chunk_text), model=$2`,+ [`[${new Array(dims).fill(0.1).join(',')}]`, model]);+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dims}`]);+ const noops = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects e JOIN pages p ON p.id=(e.data->>'page_id')::int+ WHERE e.kind='embedding' AND e.state='queued' AND p.text_projection_revision=p.knowledge_revision AND p.knowledge_revision=e.revision`);+ expect(Number(noops[0]!.n)).toBeGreaterThanOrEqual(BACKLOG);+ await effectSql(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='embedding' AND state='queued'");+ const real = Bun.which('git')!;+ const committing = join(home, 'committing');+ const stub = stubGit(home, `case " $* " in *" commit "*) touch '${committing}'; sleep ${COMMIT_SLEEP_S};; esac\nexec '${real}' "$@"`);+ await withEnv({ PATH: `${stub}:${process.env.PATH}` }, async () => {+ await release(engine);+ startPersistenceConsumer(engine, { engine: engine.kind, embedding_disabled: true } as never);+ for (let i = 0; i < 200 && !existsSync(committing); i++) await Bun.sleep(25);+ expect(existsSync(committing)).toBe(true);+ const started = performance.now();+ const result = await submitPageMutation(ctx('default'), { operation: 'put_page', waitMs: 5000,+ params: { slug: 'notes/behind-both-backlogs', request_id: randomUUID(), content: pageContent(9998) } });+ expect(result.status).not.toBe('pending');+ expect(performance.now() - started).toBeLessThan(5000);+ await disposePersistenceConsumer(engine);+ });+ await release(engine);+ while ((await gitStates(engine)).queued) { await release(engine); await pass(engine); }+ expect(await gitStates(engine)).toEqual({ committed: BACKLOG + 1 });+ const embedding = await engine.executeRaw<{ state: string; attempts: number; n: number }>(+ "SELECT state, attempts, count(*)::int AS n FROM persistence_effects WHERE kind='embedding' AND data->>'slug' LIKE 'notes/page-%' GROUP BY 1,2");+ expect(embedding.map(r => ({ state: r.state, attempts: Number(r.attempts), n: Number(r.n) }))).toEqual([{ state: 'committed', attempts: 1, n: BACKLOG }]);+ } finally { resetGateway(); }+ }), 300_000);// Wave 7: the coalesced claim hoists its worktree-wide conditions into one InitPlan. This is the claim's// predicate before that change, row by row; every state below must claim exactly the rows it selects.test('the coalesced claim takes exactly the rows of the per-row reference predicate', () => withBrain(kind, async ({ engine, home, ctx }) => {diff --git a/test/pglite-checkpoint-guard.test.ts b/test/pglite-checkpoint-guard.test.tsindex 4a6dc12d26..b7597715bd 100644--- a/test/pglite-checkpoint-guard.test.ts+++ b/test/pglite-checkpoint-guard.test.ts@@ -8,7 +8,7 @@ import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { CHECKPOINT_GUARD_MAX_BYTES, PgliteCheckpointGuard, checkpointGuardThreshold, writesWal } from '../src/core/pglite-engine/checkpoint-guard.ts';+import { CHECKPOINT_GUARD_MAX_BYTES, CHECKPOINT_PROBE_REUSE_MS, PGLITE_WAL_BYTES_PER_SECOND_BOUND, PgliteCheckpointGuard, checkpointGuardThreshold, writesWal } from '../src/core/pglite-engine/checkpoint-guard.ts';import { GBrainError } from '../src/core/types.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';@@ -26,7 +26,7 @@ function install(engine: PGLiteEngine, opts: { threshold?: number; fail?: RegExp}, message => opts.warnings?.push(message));if (opts.threshold !== undefined) (guard as unknown as { threshold: number }).threshold = opts.threshold;inner._checkpointGuard = guard;- return { checkpoints: () => calls.filter(sql => sql === 'CHECKPOINT').length, calls };+ return { checkpoints: () => calls.filter(sql => sql === 'CHECKPOINT').length, calls, guard };}describe('checkpoint guard threshold', () => {@@ -111,6 +111,48 @@ describe('PGLite outermost transaction guard', () => {});});+describe('probe reuse window', () => {+ let engine: PGLiteEngine;+ const probes = (calls: string[]) => calls.filter(sql => sql.includes('pg_control_checkpoint')).length;+ const reuseBudget = PGLITE_WAL_BYTES_PER_SECOND_BOUND * CHECKPOINT_PROBE_REUSE_MS / 1000;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.executeRaw('CREATE TABLE guard_reuse (id int PRIMARY KEY, v text)');+ });+ afterAll(async () => { await engine.disconnect(); });++ test('a run of small writes inside the window reads the WAL position once', async () => {+ await engine.executeRaw('CHECKPOINT');+ const spy = install(engine, { threshold: CHECKPOINT_GUARD_MAX_BYTES });+ const start = Date.now();+ for (let i = 0; i < 5; i++) await engine.transaction(async tx => { await tx.executeRaw('INSERT INTO guard_reuse VALUES ($1, $2)', [i, 'x']); });+ if (Date.now() - start < CHECKPOINT_PROBE_REUSE_MS) expect(probes(spy.calls)).toBe(1);+ expect(spy.checkpoints()).toBe(0);+ });++ test('a reading within one window of the threshold is never reused', async () => {+ await engine.executeRaw('CHECKPOINT');+ // Any reading is within a full window's budget of this threshold, so every write probes.+ const spy = install(engine, { threshold: reuseBudget });+ for (let i = 10; i < 13; i++) await engine.transaction(async tx => { await tx.executeRaw('INSERT INTO guard_reuse VALUES ($1, $2)', [i, 'x']); });+ expect(probes(spy.calls)).toBe(3);+ });++ test('WAL that crosses the threshold inside a reused window checkpoints on the first probe after it', async () => {+ await engine.executeRaw('CHECKPOINT');+ const spy = install(engine, { threshold: CHECKPOINT_GUARD_MAX_BYTES });+ await engine.transaction(async tx => { await tx.executeRaw("INSERT INTO guard_reuse VALUES (20, 'first')"); });+ expect(probes(spy.calls)).toBe(1);+ // Forced: the WAL now sits past the threshold (as if a window's writes crossed it); the reused probe still says it is far.+ (spy.guard as unknown as { threshold: number }).threshold = 1;+ await Bun.sleep(CHECKPOINT_PROBE_REUSE_MS + 10);+ await engine.transaction(async tx => { await tx.executeRaw("INSERT INTO guard_reuse VALUES (21, 'after the window')"); });+ expect(probes(spy.calls)).toBe(2);+ expect(spy.checkpoints()).toBe(1);+ });+});+describe('guard checkpoint durability', () => {let dir: string;let reopened: PGLiteEngine;