Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
resident: bounded projection window and cached class status (#6803)
garrytan55d76b015ebd
diff --git a/src/core/page-state/projection-status.ts b/src/core/page-state/projection-status.tsnew file mode 100644index 0000000000..a0d6557a5d--- /dev/null+++ b/src/core/page-state/projection-status.ts@@ -0,0 +1,48 @@+/**+ * #6803 part 2: the resident's `projection_status` answer, kept off the tick+ * path. Counting every class of a 93K-row queue takes hundreds of+ * milliseconds, more than a doctor read should wait on and nothing a consumer+ * tick should pay for, so the resident refreshes the counts on a timer: at+ * most every 60 s when the queue's row count or `max(updated_at)` or a source's+ * archive flag changed, and at least every 10 minutes otherwise. The IPC reply+ * reads the cache (host-local, within the 2 s budget); before the first count+ * finishes it waits for that count.+ */+import type { BrainEngine } from '../engine.ts';+import { projectionBacklog, type ProjectionBacklog } from './projections.ts';++export const PROJECTION_STATUS_CHECK_MS = 60_000;+export const PROJECTION_STATUS_MAX_AGE_MS = 10 * 60_000;++export interface ProjectionStatusCache {+ /** The latest class counts (the first call waits for the first count). */+ read(): Promise<Required<ProjectionBacklog>>;+ /** Recount when the queue or a source's lifecycle changed, or the count is older than 10 minutes. */+ refresh(): Promise<void>;+ stop(): void;+}++export function startProjectionStatusCache(engine: Pick<BrainEngine, 'executeRaw'>, opts: { now?: () => number; checkMs?: number } = {}): ProjectionStatusCache {+ const now = opts.now ?? Date.now;+ let counted: { at: number; signal: string; value: Required<ProjectionBacklog> } | null = null;+ let inflight: Promise<void> | null = null;+ const refresh = (): Promise<void> => inflight ??= (async () => {+ const [row] = await engine.executeRaw<{ signal: string }>(`SELECT (SELECT count(*) FROM page_projection_jobs)::text || '/'+ || COALESCE((SELECT max(updated_at) FROM page_projection_jobs)::text,'') || '/'+ || md5(COALESCE((SELECT string_agg(id || ':' || archived::text, ',' ORDER BY id) FROM sources),'')) AS signal`);+ const signal = String(row?.signal ?? '');+ if (counted && counted.signal === signal && now() - counted.at < PROJECTION_STATUS_MAX_AGE_MS) return;+ counted = { at: now(), signal, value: await projectionBacklog(engine) };+ })().finally(() => { inflight = null; });+ const timer = setInterval(() => { refresh().catch(() => undefined); }, opts.checkMs ?? PROJECTION_STATUS_CHECK_MS);+ timer.unref?.();+ refresh().catch(() => undefined);+ return {+ async read() {+ if (!counted) await refresh();+ return counted!.value;+ },+ refresh,+ stop: () => clearInterval(timer),+ };+}diff --git a/src/core/page-state/projection-window.ts b/src/core/page-state/projection-window.tsnew file mode 100644index 0000000000..bac41a20d0--- /dev/null+++ b/src/core/page-state/projection-window.ts@@ -0,0 +1,93 @@+/**+ * #6803 part 2: bounded resident projection selection. On master the+ * resident's selector walked the whole `page_projection_jobs` table in+ * `updated_at` order and probed each row's page, so every tick of every+ * resident probed all 93K undrainable image rows v153 queued. Each tick now+ * looks at most at `RESIDENT_PROBE_BUDGET` rows:+ *+ * 1. a recency lane: rows updated after `high water - 10 minutes` (newest+ * first, at most `RESIDENT_RECENT_ROWS`), so a fresh edit behind a large+ * queue, or a row whose writer transaction started before the previous+ * tick, is reached within two ticks. The mark starts at `max(updated_at)`;+ * the lane scans the queue table only, never `pages`.+ * 2. a primary-key window over the rest of the budget, from a per-process+ * cursor that starts at a random key and wraps around, so every row+ * (a `rebuild_failed` retry after its cooldown, a restored source's rows)+ * is reached within one lap. The consumer's idle `hasWork` probe walks+ * the same window and advances the same cursor.+ *+ * A bounded negative cache skips (source incarnation, slug, revision) of a page+ * whose kind the resident never builds (images: their seal is the importer's+ * or the explicit `gbrain projections drain`'s). Archive, missing-source and+ * cooldown states are never cached. The window and the recency lane bound the+ * inline selector only; the segmented route keeps its own probe and lease, and+ * the explicit drain keeps oldest-first.+ */+import { randomUUID } from 'node:crypto';++export const RESIDENT_PROBE_BUDGET = 500;+export const RESIDENT_RECENT_ROWS = 100;+const WINDOW_ROWS = RESIDENT_PROBE_BUDGET - RESIDENT_RECENT_ROWS;+const NEGATIVE_CACHE_MAX = 100_000;++export interface ProjectionScanCursor {+ /** The last primary key the window covered; the next window starts after it. */+ after: { source_incarnation: string; slug: string };+ /** `max(updated_at)` the previous selection saw (text), or null before the first. */+ highWater: string | null;+ /** Keys (incarnation, slug, revision) of pages whose kind the resident never builds. */+ ineligible: Set<string>;+}++export function newProjectionScanCursor(): ProjectionScanCursor {+ return { after: { source_incarnation: randomUUID(), slug: '' }, highWater: null, ineligible: new Set() };+}++const cursors = new WeakMap<object, ProjectionScanCursor>();++/** The per-process cursor of one engine, shared by its resident invocations and its consumer's idle probe. */+export function residentProjectionCursor(engine: object): ProjectionScanCursor {+ let cursor = cursors.get(engine);+ if (!cursor) cursors.set(engine, cursor = newProjectionScanCursor());+ return cursor;+}++export function ineligibleKey(row: { source_incarnation: string; slug: string; revision: string }): string {+ return `${row.source_incarnation}\u0000${row.slug}\u0000${row.revision}`;+}++export function rememberIneligible(cursor: ProjectionScanCursor, row: { source_incarnation: string; slug: string; revision: string }): void {+ if (cursor.ineligible.size >= NEGATIVE_CACHE_MAX) cursor.ineligible.clear();+ cursor.ineligible.add(ineligibleKey(row));+}++/**+ * The CTEs `recent` and `win` over `page_projection_jobs` for one cursor: each+ * row carries `lane` ('recent' or 'window') and `ord` (window order). `filter`+ * is an extra predicate over `j` (internal SQL); parameters are appended to+ * `params`. `high_water` (the queue's current `max(updated_at)`) rides along so+ * the caller can move the mark.+ */+export function residentWindowCtes(cursor: ProjectionScanCursor, params: unknown[], filter = 'TRUE'): string {+ const inc = params.push(cursor.after.source_incarnation);+ const slug = params.push(cursor.after.slug);+ const mark = params.push(cursor.highWater);+ const cols = 'j.source_incarnation,j.slug,j.revision,j.updated_at,j.reason';+ return `mark AS (SELECT COALESCE($${mark}::text::timestamptz,(SELECT max(updated_at) FROM page_projection_jobs)) AS at),+ recent AS (SELECT ${cols},'recent'::text AS lane,0 AS ord FROM page_projection_jobs j, mark+ WHERE j.updated_at > mark.at - interval '10 minutes' AND ${filter} ORDER BY j.updated_at DESC LIMIT ${RESIDENT_RECENT_ROWS}),+ fwd AS (SELECT ${cols} FROM page_projection_jobs j WHERE (j.source_incarnation,j.slug) > ($${inc}::uuid,$${slug}) AND ${filter}+ ORDER BY j.source_incarnation,j.slug LIMIT ${WINDOW_ROWS}),+ wrap AS (SELECT ${cols} FROM page_projection_jobs j WHERE (j.source_incarnation,j.slug) <= ($${inc}::uuid,$${slug}) AND ${filter}+ ORDER BY j.source_incarnation,j.slug LIMIT ${WINDOW_ROWS}),+ win AS (SELECT *,'window'::text AS lane,row_number() OVER (ORDER BY part,source_incarnation,slug) AS ord FROM (+ (SELECT *,0 AS part FROM fwd ORDER BY source_incarnation,slug) UNION ALL (SELECT *,1 AS part FROM wrap ORDER BY source_incarnation,slug)+ ORDER BY part,source_incarnation,slug LIMIT ${WINDOW_ROWS}) w),+ high_water AS (SELECT max(updated_at)::text AS at FROM page_projection_jobs)`;+}++/** Move the cursor past the window's last row a caller has finished with (none: the window was empty). */+export function advanceProjectionCursor(cursor: ProjectionScanCursor, last: { source_incarnation: string; slug: string } | null | undefined, highWater: string | null | undefined): void {+ if (last) cursor.after = { source_incarnation: String(last.source_incarnation), slug: String(last.slug) };+ if (highWater) cursor.highWater = highWater;+}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 80ae4d37e7..598eb37222 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -12,6 +12,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { ownerExceptionLogText } from './publication-failure.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';+import { advanceProjectionCursor, residentProjectionCursor, residentWindowCtes } from '../page-state/projection-window.ts';import { rebuildPendingSegmentedProjections } from '../page-body/projection.ts';import { publicationConcurrency } from './pool-capacity.ts';import { claimedHeadOrder } from './sync-window.ts';@@ -111,7 +112,8 @@ export async function runResidentProjectionInvocation(engine: BrainEngine, hostI// Wave B: queued segmented pages are rebuilt first, through their own route (one segment batch at a time).const startedAt = now();await rebuildPendingSegmentedProjections(engine, pages, { deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now });- return rebuildPendingPageProjections(engine, pages, { deadlineMs: Math.max(0, RESIDENT_PROJECTION_BUDGET_MS - (now() - startedAt)), now, retryCooldown: true });+ return rebuildPendingPageProjections(engine, pages, { deadlineMs: Math.max(0, RESIDENT_PROJECTION_BUDGET_MS - (now() - startedAt)), now, retryCooldown: true,+ window: residentProjectionCursor(engine) });}const PARKED_WORKER: Promise<void> = Promise.resolve();@@ -315,7 +317,19 @@ export class PersistenceConsumer implements PersistenceConsumerLike {const retryingTopologies = [...this.topologyRetryAfter.keys()];// On the direct route the probe needs no reserved pool lane: the direct pool is small and keeps its connections.const direct = consumerConnectionRoute(this.engine).lane === 'direct';- const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse || direct ? undefined : await this.acquireIdleLane(signal), `SELECT (+ // #6803: inline projection rows are probed through the resident's bounded window (projection-window.ts), which this+ // probe advances; segmented rows keep their own probe over the whole queue, as their selector reads it.+ const cursor = residentProjectionCursor(this.engine);+ const params: unknown[] = [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies, [...this.laneTasks.keys()]];+ const windowCtes = residentWindowCtes(cursor, params, PROJECTION_RETRY_READY_SQL);+ const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean; projection_work: boolean; projection_last: { source_incarnation: string; slug: string } | null; high_water: string | null }>(this.laneInUse || direct ? undefined : await this.acquireIdleLane(signal), `WITH ${windowCtes},+ pwork AS (SELECT EXISTS (SELECT 1 FROM (SELECT source_incarnation,slug FROM recent UNION ALL SELECT source_incarnation,slug FROM win) j+ CROSS JOIN LATERAL (SELECT s.id FROM sources s WHERE s.incarnation=j.source_incarnation AND NOT s.archived OFFSET 0) s+ CROSS JOIN LATERAL (SELECT 1 FROM (SELECT p.id FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug OFFSET 0) k+ JOIN pages p ON p.id=k.id WHERE p.deleted_at IS NULL AND p.page_kind IN ('markdown','code')) p) AS found)+ SELECT (SELECT found FROM pwork) AS projection_work,+ (SELECT json_build_object('source_incarnation',source_incarnation,'slug',slug) FROM win ORDER BY ord DESC LIMIT 1) AS projection_last,+ (SELECT at FROM high_water) AS high_water, (EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_idWHERE ${claimableWriteSql(foregroundPrioritySql(), '$5::text[]')}AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))@@ -333,14 +347,16 @@ export class PersistenceConsumer implements PersistenceConsumerLike {WHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state<>'committed')))OR EXISTS (SELECT 1 FROM persistence_effects e JOIN persistence_worktrees w ON w.id=e.worktree_idWHERE e.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND e.next_attempt_at<=now())- OR EXISTS (SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation- JOIN pages p ON p.source_id=s.id AND p.slug=j.slug- WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')- AND ${PROJECTION_RETRY_READY_SQL})+ OR (SELECT found FROM pwork)+ OR EXISTS (SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation AND NOT s.archived+ JOIN pages p ON p.source_id=s.id AND p.slug=j.slug AND p.deleted_at IS NULL AND p.body_storage='segmented'+ WHERE ${PROJECTION_RETRY_READY_SQL})OR EXISTS (SELECT 1 FROM persistence_topology_changes cJOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuidWHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))- ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies, [...this.laneTasks.keys()]], signal));+ ) AS work`, params, signal));+ // A window holding work stays put, so the tick it wakes reads the same rows.+ advanceProjectionCursor(cursor, row?.projection_work ? null : row?.projection_last, row?.high_water);return row?.work === true;}/**diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex d1aeb2c8ab..ef2a01405d 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -5,6 +5,7 @@ import { isAbsolute } from 'node:path';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';+import type { ProjectionBacklog } from '../page-state/projections.ts';import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt } from './types.ts';import { isPersistenceAdminExtension, isPersistenceAdminOperation, PERSISTENCE_ADMIN_EXTENSIONS, PERSISTENCE_ADMIN_OPERATIONS, type PersistenceAdminExtension, type PersistenceAdminOperation } from './admin-contract.ts';@@ -82,12 +83,15 @@ export interface PersistenceIpcAdminRequest {registration: PersistenceIpcRegistration;}-/** #5401: the resident's queued text-projection backlog. Counts only, never identifiers. */-export interface PersistenceProjectionStatus {- pending: number;- failed: number;- oldest_age_seconds: number | null;-}+/**+ * #5401: the resident's queued text-projection backlog. Counts only, never+ * identifiers. #6803: `pending` and `failed` keep their meaning (rows the+ * resident drains); the class counts are optional, so an older doctor reading+ * a new reply sees an unchanged `pending` and a new doctor reading an old one+ * knows the resident predates them.+ */+export type PersistenceProjectionStatus = ProjectionBacklog;+const PROJECTION_CLASS_KEYS = ['sealable', 'sealable_with_visual', 'reimport', 'ocr_required', 'protected', 'archived'] as const;export interface PersistenceIpcProvider {brainId: string;@@ -414,7 +418,9 @@ export async function requestPersistenceProjectionStatus(socketPath: string, timconst value = await exchange(socketPath, { version: 1, kind: 'projection_status' }, timeoutMs);if (!record(value) || !count(value.pending) || !count(value.failed)|| !(value.oldest_age_seconds === null || count(value.oldest_age_seconds))) throw new PersistenceIpcTransportError(false);- return { pending: value.pending, failed: value.failed, oldest_age_seconds: value.oldest_age_seconds };+ const classes = Object.fromEntries(PROJECTION_CLASS_KEYS.flatMap(key => count(value[key]) ? [[key, value[key]]] : []));+ return { pending: value.pending, failed: value.failed, oldest_age_seconds: value.oldest_age_seconds, ...classes,+ ...(typeof value.as_of === 'string' ? { as_of: value.as_of } : {}) };}export async function requestPersistenceOperation(socketPath: string, request: PersistenceIpcRequest, timeoutMs = 30_000): Promise<unknown> {diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex 422744c9d1..728076cb2a 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -12,7 +12,7 @@ import { LOCAL_CLI_OWNER_OPERATIONS, type PersistenceIpcProvider } from './ipc.timport { runPersistenceAdministration } from './administration.ts';import { boundedWriteWaitMs } from './write-wait.ts';export { residentPersistenceConfig } from './local-client.ts';-import { projectionBacklog } from '../page-state/projections.ts';+import { startProjectionStatusCache } from '../page-state/projection-status.ts';import { trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';@@ -37,7 +37,8 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:}const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');startPersistenceConsumer(engine, config);- return { brainId: brain.brain_id, projectionStatus: () => projectionBacklog(engine), dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {+ const projectionStatus = startProjectionStatusCache(engine);+ return { brainId: brain.brain_id, projectionStatus: () => projectionStatus.read(), dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {assertPersistenceAccepting(engine);if (request.brain_id !== brain.brain_id) {throw opError('permission_denied', 'This registration belongs to a different brain.',diff --git a/test/projection-resident-doctor.test.ts b/test/projection-resident-doctor.test.tsindex 30a251d090..1d8470b1fa 100644--- a/test/projection-resident-doctor.test.ts+++ b/test/projection-resident-doctor.test.ts@@ -53,7 +53,8 @@ test('the resident answers projection_status with counts only; an owner withouttry {const status = await requestPersistenceProjectionStatus(socket);expect(status).toMatchObject({ pending: 3, failed: 0 });- expect(Object.keys(status).sort()).toEqual(['failed', 'oldest_age_seconds', 'pending']);+ expect(Object.keys(status).sort()).toEqual(['archived', 'as_of', 'failed', 'ocr_required', 'oldest_age_seconds', 'pending', 'protected',+ 'reimport', 'sealable', 'sealable_with_visual']);expect(status.oldest_age_seconds).toBeGreaterThanOrEqual(0);} finally { server.close(); }const old = (await startPersistenceIpcServer(socket, provider()))!;diff --git a/test/projection-resident-window.test.ts b/test/projection-resident-window.test.tsnew file mode 100644index 0000000000..2ea39cb50e--- /dev/null+++ b/test/projection-resident-window.test.ts@@ -0,0 +1,133 @@+/**+ * #6803 part 2: the resident's projection selector and the consumer's idle+ * probe read a bounded window of the queue (page-state/projection-window.ts)+ * instead of walking every row v153 queued. Protects: a fresh edit behind a+ * large image queue is reached through the recency lane; the primary-key+ * window wraps so an old row behind the cursor is reached; image rows the+ * resident never builds are remembered and not probed again; the idle probe+ * advances the shared cursor; a rebuild_failed row is retried only after its+ * cooldown. PGLite (the resident's engine).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PAGE_PROJECTION_ACTIVATION_SQL } from '../src/core/page-state/projection-schema.ts';+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';+import { newProjectionScanCursor, residentProjectionCursor, RESIDENT_PROBE_BUDGET } from '../src/core/page-state/projection-window.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';++let engine: PGLiteEngine;+const IMAGES = 1000;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); });++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM page_projection_jobs');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,page_kind,title,compiled_truth,timeline,chunker_version)+ SELECT 'default','images/img-'||lpad(i::text,4,'0')||'.png','image','image','img','','',0 FROM generate_series(1,$1::int) i`, [IMAGES]);+ for (const statement of PAGE_PROJECTION_ACTIVATION_SQL.split(';').map(part => part.trim()).filter(Boolean)) await engine.executeRaw(statement);+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at = now() - interval '1 hour'");+});++async function queueNote(slug: string, opts: { old?: boolean; failed?: boolean } = {}) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example note ${slug}.` });+ await engine.executeRaw(`UPDATE pages SET text_projection_revision = NULL WHERE slug = $1`, [slug]);+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)+ SELECT s.incarnation,p.slug,p.knowledge_revision,'pages_trigger' FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.slug = $1+ ON CONFLICT DO NOTHING`, [slug]);+ if (opts.failed) await engine.executeRaw(`UPDATE page_projection_jobs SET reason = 'rebuild_failed', updated_at = now() WHERE slug = $1`, [slug]);+ if (opts.old) await engine.executeRaw(`UPDATE page_projection_jobs SET updated_at = now() - interval '1 hour' WHERE slug = $1`, [slug]);+}++const queued = async (slug: string) => (await engine.executeRaw('SELECT 1 FROM page_projection_jobs WHERE slug = $1', [slug])).length > 0;+/** A high-water mark of now: the recency lane then skips every row queued an hour ago, so only the window can reach them. */+const highWater = async () => (await engine.executeRaw<{ at: string }>('SELECT now()::text AS at'))[0]!.at;++describe('bounded resident projection window', () => {+ test('a fresh edit behind a large image queue is rebuilt through the recency lane', async () => {+ const cursor = newProjectionScanCursor();+ cursor.after = { source_incarnation: '00000000-0000-0000-0000-000000000000', slug: '' };+ expect(await rebuildPendingPageProjections(engine, 100, { window: cursor, retryCooldown: true })).toMatchObject({ rebuilt: 0 });+ await queueNote('zz/fresh-edit');+ expect(await rebuildPendingPageProjections(engine, 100, { window: cursor, retryCooldown: true })).toMatchObject({ rebuilt: 1 });+ expect(await queued('zz/fresh-edit')).toBe(false);+ }, 60_000);++ test('the window wraps to an old row behind its cursor, and remembered image rows are not probed again', async () => {+ await queueNote('aa/old-note', { old: true });+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id = 'default'");+ const cursor = newProjectionScanCursor();+ cursor.after = { source_incarnation: incarnation, slug: 'images/img-0700.png' };+ cursor.highWater = await highWater();+ const probes: number[] = [];+ const spy = new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {+ if (sql.includes('jsonb_to_recordset($1::text::jsonb) AS k(i int')) probes.push(JSON.parse(String(params![0])).length);+ return target.executeRaw(sql, params);+ };+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as PGLiteEngine;+ const laps: number[] = [];+ for (let tick = 0; tick < 3 && await queued('aa/old-note'); tick++) laps.push((await rebuildPendingPageProjections(spy, 100, { window: cursor, retryCooldown: true })).rebuilt);+ expect(laps[0]).toBe(1);+ expect(await queued('aa/old-note')).toBe(false);+ expect(Math.max(...probes)).toBeLessThanOrEqual(RESIDENT_PROBE_BUDGET);+ const remembered = cursor.ineligible.size;+ expect(remembered).toBeGreaterThan(0);+ probes.length = 0;+ for (let tick = 0; tick < Math.ceil(IMAGES / 400) + 1; tick++) await rebuildPendingPageProjections(spy, 100, { window: cursor, retryCooldown: true });+ expect(cursor.ineligible.size).toBe(IMAGES);+ probes.length = 0;+ await rebuildPendingPageProjections(spy, 100, { window: cursor, retryCooldown: true });+ expect(probes).toEqual([]);+ }, 120_000);++ test('the idle probe walks the shared window and advances its cursor', async () => {+ const consumer = new PersistenceConsumer(engine, {} as never, async () => { throw new Error('no preparation in this probe'); });+ const probe = consumer as unknown as { hasWork(): Promise<boolean> };+ const cursor = residentProjectionCursor(engine);+ cursor.after = { source_incarnation: '00000000-0000-0000-0000-000000000000', slug: '' };+ cursor.highWater = await highWater();+ expect(await probe.hasWork()).toBe(false);+ const first = cursor.after.slug;+ expect(first).toBe('images/img-0400.png');+ expect(await probe.hasWork()).toBe(false);+ expect(cursor.after.slug).toBe('images/img-0800.png');+ await queueNote('aa/old-note', { old: true });+ cursor.after = { source_incarnation: '00000000-0000-0000-0000-000000000000', slug: '' };+ expect(await probe.hasWork()).toBe(true);+ expect(cursor.after.slug).toBe('');+ }, 60_000);++ test('a segmented row outside the window still wakes the idle probe (its route reads the whole queue)', async () => {+ await queueNote('zz/segmented', { old: true });+ await engine.executeRaw("UPDATE pages SET body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_bytes = 1 WHERE slug = 'zz/segmented'");+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at = now() - interval '1 hour' WHERE slug = 'zz/segmented'");+ const consumer = new PersistenceConsumer(engine, {} as never, async () => { throw new Error('no preparation in this probe'); });+ const cursor = residentProjectionCursor(engine);+ cursor.after = { source_incarnation: '00000000-0000-0000-0000-000000000000', slug: '' };+ cursor.highWater = await highWater();+ expect(await (consumer as unknown as { hasWork(): Promise<boolean> }).hasWork()).toBe(true);+ }, 60_000);++ test('a rebuild_failed row is retried only after its cooldown', async () => {+ await queueNote('notes/failed', { failed: true });+ const cursor = newProjectionScanCursor();+ expect(await rebuildPendingPageProjections(engine, 100, { window: cursor, retryCooldown: true })).toMatchObject({ rebuilt: 0 });+ expect(await queued('notes/failed')).toBe(true);+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at = now() - interval '1 minute' WHERE slug = 'notes/failed'");+ let rebuilt = 0;+ for (let tick = 0; tick < Math.ceil(IMAGES / 400) + 1 && await queued('notes/failed'); tick++) {+ rebuilt += (await rebuildPendingPageProjections(engine, 100, { window: cursor, retryCooldown: true })).rebuilt;+ }+ expect(rebuilt).toBe(1);+ expect(await queued('notes/failed')).toBe(false);+ }, 60_000);+});