Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(postgres): sync watermark partial index; retrieval telemetry moves to page_retrievals

time-attackaf7ba329a102
diff --git a/src/core/context/volunteer.ts b/src/core/context/volunteer.ts
index d5c934eaaf..4f84df571a 100644
--- a/src/core/context/volunteer.ts
+++ b/src/core/context/volunteer.ts
@@ -356,10 +356,11 @@ export async function volunteerUsageStats(
rows = await engine.executeRaw(
`SELECT e.match_arm, e.channel,
count(*)::text AS volunteered,
- count(*) FILTER (WHERE p.last_retrieved_at > e.volunteered_at)::text AS used
+ count(*) FILTER (WHERE GREATEST(p.last_retrieved_at, r.last_retrieved_at) > e.volunteered_at)::text AS used
FROM context_volunteer_events e
LEFT JOIN pages p
ON p.source_id = e.source_id AND p.slug = e.slug AND p.deleted_at IS NULL
+ LEFT JOIN page_retrievals r ON r.page_id = p.id
WHERE e.source_id = ANY($1::text[])
AND e.volunteered_at > now() - ($2 || ' days')::interval
GROUP BY e.match_arm, e.channel
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 5e0c72bfaf..0e482d202f 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -508,10 +508,11 @@ export async function listPrefixSampledPages(scoped: ScopedReadRunner, opts: Dom
p.source_id,
p.title,
p.compiled_truth,
- p.last_retrieved_at,
+ GREATEST(p.last_retrieved_at, r.last_retrieved_at) AS last_retrieved_at,
substring(p.slug from '^[^/]+/[^/]+') AS prefix,
COUNT(pl.id) AS connection_count
FROM pages p
+ LEFT JOIN page_retrievals r ON r.page_id = p.id
LEFT JOIN page_links pl ON pl.to_page_id = p.id
WHERE p.deleted_at IS NULL
AND substring(p.slug from '^[^/]+/[^/]+') = ANY(${opts.prefixes}::text[])
@@ -521,7 +522,7 @@ export async function listPrefixSampledPages(scoped: ScopedReadRunner, opts: Dom
OR (${sourceIds}::text[] IS NULL AND ${sourceId}::text IS NOT NULL AND p.source_id = ${sourceId})
OR (${sourceIds}::text[] IS NULL AND ${sourceId}::text IS NULL)
)
- GROUP BY p.id, p.slug, p.source_id, p.title, p.compiled_truth, p.last_retrieved_at
+ GROUP BY p.id, p.slug, p.source_id, p.title, p.compiled_truth, p.last_retrieved_at, r.last_retrieved_at
),
ranked AS (
SELECT
@@ -594,10 +595,11 @@ export async function listCorpusSample(scoped: ScopedReadRunner, opts: CorpusSam
p.source_id,
p.title,
p.compiled_truth,
- p.last_retrieved_at,
+ GREATEST(p.last_retrieved_at, r.last_retrieved_at) AS last_retrieved_at,
substring(p.slug from '^[^/]+/[^/]+') AS prefix,
(SELECT COUNT(*) FROM page_links pl WHERE pl.to_page_id = p.id) AS connection_count
FROM pages p
+ LEFT JOIN page_retrievals r ON r.page_id = p.id
WHERE p.deleted_at IS NULL
AND (cardinality(${exclude}::text[]) = 0 OR NOT (p.slug = ANY(${exclude}::text[])))
AND (
diff --git a/src/core/last-retrieved.ts b/src/core/last-retrieved.ts
index 1b2a8688fc..b4472b9f13 100644
--- a/src/core/last-retrieved.ts
+++ b/src/core/last-retrieved.ts
@@ -10,11 +10,23 @@
* dream cycle, doctor probes, etc. Pure signal: "a user-facing surface
* just surfaced this page."
*
- * - 5-min throttle (D2). The UPDATE includes a `WHERE last_retrieved_at IS
- * NULL OR last_retrieved_at < NOW() - INTERVAL '5 minutes'` clause so
- * hot pages surfaced by many concurrent searches don't pile up MVCC
- * row versions. ~90% of writes skipped in steady state on a heavily-
- * searched brain. Mirrors `embedded_at` reset gating in `upsertChunks`.
+ * - 5-min throttle (D2). The upsert only moves a timestamp older than
+ * 5 minutes, so hot pages surfaced by many concurrent searches don't pile
+ * up MVCC row versions. ~90% of writes skipped in steady state on a
+ * heavily-searched brain. Mirrors `embedded_at` reset gating in
+ * `upsertChunks`.
+ *
+ * - Narrow side table (migration v224). The timestamp lives in
+ * `page_retrievals(page_id, last_retrieved_at)`, not on `pages`: an UPDATE
+ * of `pages` fired seven triggers per statement, wrote a new wide heap
+ * tuple plus an entry in every pages index, and advanced
+ * `page_generation_clock_seq` even when the throttle matched no row, which
+ * expired the query-cache bookmark, the get_health memo and the projection
+ * readiness memo on every read. The upsert is a HOT update of a 40-byte
+ * row with no triggers. Readers take
+ * `GREATEST(pages.last_retrieved_at, page_retrievals.last_retrieved_at)`:
+ * the migration copied the column, and a mixed-version writer still
+ * updating `pages.last_retrieved_at` stays visible.
*
* - Default-on with `search.track_retrieval` config escape hatch (D13).
* Operators worried about per-search write amplification can opt out:
@@ -34,7 +46,7 @@
*/
import type { BrainEngine } from './engine.ts';
-import { isUndefinedColumnError } from './utils.ts';
+import { isUndefinedTableError } from './utils.ts';
import { registerBackgroundWorkDrainer } from './background-work.ts';
let _trackRetrievalCache: { ts: number; enabled: boolean } | null = null;
@@ -162,6 +174,12 @@ export function _resetTrackRetrievalCacheForTests(): void {
_trackRetrievalCache = null;
}
+/** $1 page ids. Ids of pages that do not exist are skipped, as the UPDATE of `pages` skipped them. */
+export const BUMP_LAST_RETRIEVED_SQL = `INSERT INTO page_retrievals (page_id, last_retrieved_at)
+ SELECT p.id, NOW() FROM pages p WHERE p.id = ANY($1::int[])
+ ON CONFLICT (page_id) DO UPDATE SET last_retrieved_at = EXCLUDED.last_retrieved_at
+ WHERE page_retrievals.last_retrieved_at < NOW() - INTERVAL '5 minutes'`;
+
/**
* Bump `last_retrieved_at` on the given page_ids. Fire-and-forget — caller
* MUST NOT await this for the op response. Empty ids list is a no-op.
@@ -180,21 +198,14 @@ export function bumpLastRetrievedAt(engine: BrainEngine, pageIds: number[]): voi
try {
const enabled = await isTrackingEnabled(engine);
if (!enabled) return;
- // 5-minute throttle (D2) + best-effort. The UPDATE is idempotent:
+ // 5-minute throttle (D2) + best-effort. The upsert is idempotent:
// setting last_retrieved_at = NOW() multiple times in a row is the
// same as setting it once (TIMESTAMPTZ comparison is monotonic).
- await engine.executeRaw(
- `UPDATE pages
- SET last_retrieved_at = NOW()
- WHERE id = ANY($1::int[])
- AND (last_retrieved_at IS NULL
- OR last_retrieved_at < NOW() - INTERVAL '5 minutes')`,
- [pageIds]
- );
+ await engine.executeRaw(BUMP_LAST_RETRIEVED_SQL, [pageIds]);
} catch (err) {
- // Pre-v77 brain (column missing) falls through silently — the search
+ // Pre-v224 brain (table missing) falls through silently — the search
// op already returned, the LSD signal just stays NULL until upgrade.
- if (isUndefinedColumnError(err, 'last_retrieved_at')) return;
+ if (isUndefinedTableError(err)) return;
// Other errors: stderr-warn but don't break the op response.
const msg = err instanceof Error ? err.message : String(err);
console.warn(`[last-retrieved] write-back failed (best-effort): ${msg}`);
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 30434f329f..ade7f1b44d 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -104,6 +104,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),
carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),
carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),
+ carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),
carry('page_versions', 'user_data', 'Page revision history with attribution.'),
carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),
carry('pages', 'user_data', 'Pages with ids, knowledge_revision, revision attribution and timestamps.'),
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 5eeb60a078..67a9c04cef 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -23,10 +23,26 @@ export const PERSISTENCE_SYNC_RUN_INDEXES = [
* that `writer movement`, `data_moving` and doctor `managed_sync_not_moving`
* read; the baseline indexes cover pending, recovery and principal reads
* only. Postgres builds it CONCURRENTLY in migration v222; PGLite inline.
+ * Superseded by the sync watermark below: v223 drops it, and fresh installs
+ * build only the new one.
*/
export const PERSISTENCE_COMMITTED_WATERMARK_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_committed_watermark
ON persistence_requests(worktree_id,completed_at DESC) WHERE state='committed'`;
export const PERSISTENCE_COMMITTED_WATERMARK_INDEX = { name: 'persistence_requests_committed_watermark', table: 'persistence_requests', sql: PERSISTENCE_COMMITTED_WATERMARK_INDEX_SQL } as const;
+/**
+ * The movement watermark read (sync-movement.ts): the newest committed managed
+ * sync receipt of one worktree and incarnation. v222's index above holds every
+ * committed receipt, so on a brain whose newest receipts are imports or
+ * maintenance writes the read walked all of them and detoasted each intent to
+ * test its kind (about 1 s at 50k receipts). Receipts are permanent (compaction
+ * after `persistence.receipt_retention_days` only drops the intent), so that
+ * walk grew with every write. This index holds only the receipts the read can
+ * return, and compaction removes a receipt from it. Postgres builds it
+ * CONCURRENTLY in migration v223, which drops v222's index; PGLite inline.
+ */
+export const PERSISTENCE_SYNC_WATERMARK_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_requests_sync_watermark
+ ON persistence_requests(worktree_id,source_incarnation,completed_at DESC) WHERE state='committed' AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%'`;
+export const PERSISTENCE_SYNC_WATERMARK_INDEX = { name: 'persistence_requests_sync_watermark', table: 'persistence_requests', sql: PERSISTENCE_SYNC_WATERMARK_INDEX_SQL } as const;
/**
* #6317: one row per process that runs a full persistence consumer on a host
* (consumer-heartbeat.ts). The primary key carries the process nonce, so a
@@ -57,7 +73,7 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persi
)`;
/** Indexes the Postgres blob omits because a migration builds them CONCURRENTLY. */
export const POSTGRES_CONCURRENT_PERSISTENCE_INDEXES: ReadonlySet<string> = new Set([
- PERSISTENCE_DATABASE_PENDING_INDEX_SQL, PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL, PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL, PERSISTENCE_COMMITTED_WATERMARK_INDEX_SQL,
+ PERSISTENCE_DATABASE_PENDING_INDEX_SQL, PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL, PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL, PERSISTENCE_SYNC_WATERMARK_INDEX_SQL,
]);
/** Durable infrastructure: never reconstruct or discard these rows during page reindexing. */
export const PERSISTENCE_SCHEMA_STATEMENTS = [
@@ -148,7 +164,7 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
PERSISTENCE_DATABASE_PENDING_INDEX_SQL,
PERSISTENCE_SYNC_RUN_OPEN_INDEX_SQL,
PERSISTENCE_SYNC_RUN_COMMITTED_INDEX_SQL,
- PERSISTENCE_COMMITTED_WATERMARK_INDEX_SQL,
+ PERSISTENCE_SYNC_WATERMARK_INDEX_SQL,
`CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC)`,
`CREATE TABLE IF NOT EXISTS persistence_effects (
id bigserial PRIMARY KEY,
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index 9dfe61eba2..c0dd6233fb 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -9,8 +9,9 @@
* (`readManagedSyncBacklog`: index, total, held, the drain's last advance),
* the movement watermark (the newest `completed_at` of a committed
* `managed_sync_*` receipt in the current source incarnation, read through
- * the partial index on `(worktree_id, completed_at DESC) WHERE
- * state='committed'`; never a count, since compaction nulls `intent`), the
+ * the partial index `persistence_requests_sync_watermark`, whose predicate
+ * repeats the read's kind test; never a count, since compaction nulls
+ * `intent`), the
* head request's claim stamp (`step_since` moving is progress too: a
* multi-wave group commits nothing until its last wave), the newest hold, and
* who could move it: a live drain (the per-source sync lock) or a live
@@ -83,6 +84,12 @@ const newest = (...values: Array<string | null | undefined>): string | null => v
export function writerStatusCommand(sourceId: string): string { return `gbrain sources writer status --source ${sourceId} --json`; }
+/** $1 worktree, $2 source incarnation. The kind test matches the `persistence_requests_sync_watermark` predicate text, so the planner can prove the partial index applies. */
+export const MOVEMENT_WATERMARK_SQL = `SELECT
+ (SELECT r.completed_at FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state='committed' AND r.source_incarnation=$2::uuid
+ AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' ORDER BY r.completed_at DESC LIMIT 1) AS last_commit_at,
+ (SELECT count(*) FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running') AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS admitted`;
+
interface BindingRow { source_id: string; worktree_id: string; source_incarnation: string; owner_host_id: string | null }
interface WatermarkRow { last_commit_at: unknown; admitted: number | string }
interface HeadRow { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean | null }
@@ -106,11 +113,7 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
const liveHeartbeat = () => heartbeat ??= listHostConsumers(engine, host).then(rows => rows.some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live'), () => false);
const out: SourceMovement[] = [];
for (const binding of bindings) {
- const [mark] = await engine.executeRaw<WatermarkRow>(`SELECT
- (SELECT r.completed_at FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state='committed' AND r.source_incarnation=$2::uuid
- AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' ORDER BY r.completed_at DESC LIMIT 1) AS last_commit_at,
- (SELECT count(*) FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running') AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS admitted`,
- [binding.worktree_id, binding.source_incarnation]);
+ const [mark] = await engine.executeRaw<WatermarkRow>(MOVEMENT_WATERMARK_SQL, [binding.worktree_id, binding.source_incarnation]);
const [headRow] = await engine.executeRaw<HeadRow>(`SELECT request_id::text AS request_id, state, claim_phase, execution_token::text AS execution_token,
(claim_expires_at IS NOT NULL AND claim_expires_at < now()) AS claim_lapsed, publication_started
FROM persistence_requests WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') ORDER BY (state <> 'running'), sequence LIMIT 1`, [binding.worktree_id]);
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 452e5e49d2..65c68d88d9 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -133,8 +133,20 @@ CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_
CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id);
CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idx
ON pages (deleted_at) WHERE deleted_at IS NOT NULL;
-CREATE INDEX IF NOT EXISTS pages_last_retrieved_at_idx
- ON pages (last_retrieved_at);
+CREATE TABLE IF NOT EXISTS page_retrievals (
+ page_id INTEGER PRIMARY KEY,
+ last_retrieved_at TIMESTAMPTZ NOT NULL
+);
+CREATE OR REPLACE FUNCTION gbrain_forget_page_retrievals() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+BEGIN
+ DELETE FROM page_retrievals r USING gbrain_deleted_pages d WHERE r.page_id = d.id;
+ RETURN NULL;
+END \$\$;
+DROP TRIGGER IF EXISTS pages_forget_retrievals ON pages;
+CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON pages
+ REFERENCING OLD TABLE AS gbrain_deleted_pages
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals();
CREATE INDEX IF NOT EXISTS pages_links_extracted_at_idx
ON pages (source_id, links_extracted_at);
CREATE INDEX IF NOT EXISTS pages_coalesce_date_idx
@@ -1307,8 +1319,8 @@ CREATE INDEX IF NOT EXISTS persistence_requests_sync_run_open
ON persistence_requests(worktree_id,(intent->>'runId')) WHERE state<>'committed' AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete');
CREATE INDEX IF NOT EXISTS persistence_requests_sync_run_committed
ON persistence_requests(source_id,(intent->>'runId'),(intent->>'index')) WHERE state='committed' AND intent ? 'runId';
-CREATE INDEX IF NOT EXISTS persistence_requests_committed_watermark
- ON persistence_requests(worktree_id,completed_at DESC) WHERE state='committed';
+CREATE INDEX IF NOT EXISTS persistence_requests_sync_watermark
+ ON persistence_requests(worktree_id,source_incarnation,completed_at DESC) WHERE state='committed' AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%';
CREATE INDEX IF NOT EXISTS persistence_requests_principal ON persistence_requests(principal_kind,principal_id,sequence DESC);
CREATE TABLE IF NOT EXISTS persistence_effects (
id bigserial PRIMARY KEY,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 2400f2fa7e..b99d30bb71 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -281,13 +281,30 @@ CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id);
-- stays low. Don't add a regular \`(deleted_at)\` index without measuring.
CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idx
ON pages (deleted_at) WHERE deleted_at IS NOT NULL;
--- v0.37.0: full B-tree index on last_retrieved_at supports LSD's stale-page
--- query \`WHERE last_retrieved_at IS NULL OR last_retrieved_at < NOW() -
--- INTERVAL '90 days'\`. Postgres handles NULL in B-tree indexes (sorted to
--- one end) so one index covers both branches. A partial WHERE NOT NULL
--- would miss the NULL branch that LSD prioritizes (codex round 2 #6).
-CREATE INDEX IF NOT EXISTS pages_last_retrieved_at_idx
- ON pages (last_retrieved_at);
+-- Retrieval telemetry (src/core/last-retrieved.ts, migration v224): when a
+-- user-facing read last surfaced a page, written at most once per page per 5
+-- minutes. Kept off \`pages\` so the per-read upsert is a HOT update of a narrow
+-- row: an UPDATE of pages fires its triggers, rewrites a wide tuple with an
+-- entry in every pages index and advances page_generation_clock_seq, which
+-- expires the query-cache bookmark. Readers take GREATEST of this and the
+-- legacy pages.last_retrieved_at column (copied here by v224; v224 also drops
+-- its unused index). No foreign key: its KEY SHARE lock would dirty the pages
+-- row on every bump; the statement trigger below removes rows of hard-deleted
+-- pages instead.
+CREATE TABLE IF NOT EXISTS page_retrievals (
+ page_id INTEGER PRIMARY KEY,
+ last_retrieved_at TIMESTAMPTZ NOT NULL
+);
+CREATE OR REPLACE FUNCTION gbrain_forget_page_retrievals() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$
+BEGIN
+ DELETE FROM page_retrievals r USING gbrain_deleted_pages d WHERE r.page_id = d.id;
+ RETURN NULL;
+END \$\$;
+DROP TRIGGER IF EXISTS pages_forget_retrievals ON pages;
+CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON pages
+ REFERENCING OLD TABLE AS gbrain_deleted_pages
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals();
-- v0.42.7 (migration v112): composite B-tree backing \`extract --stale\` and the
-- \`links_extraction_lag\` doctor check. source_id leads so source-scoped staleness
-- scans (\`extract --stale --source X\`, \`gbrain doctor --source X\`) are indexed;
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index cbe69fa2f9..4f44c97ebc 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 222;
+export const LATEST_SCHEMA_VERSION = 224;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index dda130b5a7..c12d660871 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -223,6 +223,8 @@ import { v219 } from './v219-pages-reconcile-name-indexes.ts';
import { v220 } from './v220-persistence-request-preparation-attempts.ts';
import { v221 } from './v221-chunk-embedding-pending-since.ts';
import { v222 } from './v222-persistence-consumers.ts';
+import { v223 } from './v223-persistence-sync-watermark-index.ts';
+import { v224 } from './v224-page-retrievals.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -444,4 +446,6 @@ export const MIGRATIONS: Migration[] = [
v220,
v221,
v222,
+ v223,
+ v224,
];
diff --git a/src/core/schema-migrations/v223-persistence-sync-watermark-index.ts b/src/core/schema-migrations/v223-persistence-sync-watermark-index.ts
new file mode 100644
index 0000000000..f18cb8a052
--- /dev/null
+++ b/src/core/schema-migrations/v223-persistence-sync-watermark-index.ts
@@ -0,0 +1,28 @@
+import type { Migration } from './types.ts';
+import { PERSISTENCE_SYNC_WATERMARK_INDEX } from '../persistence/schema.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// The movement watermark read (persistence/sync-movement.ts, every minute per
+// managed source in `gbrain serve`) filtered v222's
+// `persistence_requests_committed_watermark` by incarnation and intent kind,
+// so a worktree whose committed receipts are not managed sync receipts was a
+// full walk that detoasted every intent: 115 ms at 5k receipts, 1.1 s at 50k.
+// `persistence_requests_sync_watermark` keys on (worktree_id,
+// source_incarnation, completed_at DESC) and holds only committed receipts of
+// a `managed_sync_*` kind, so the read is one index probe. Postgres builds it
+// CONCURRENTLY and then drops v222's index CONCURRENTLY (nothing else reads
+// it); PGLite builds and drops inline. Fresh installs replay v222 on an empty
+// table, so the build and drop there cost nothing.
+export const v223: Migration = {
+ version: 223,
+ name: 'persistence_sync_watermark_index',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 223, PERSISTENCE_SYNC_WATERMARK_INDEX, { notice: migrationNotice });
+ await engine.runMigration(223, `DROP INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}IF EXISTS persistence_requests_committed_watermark;`);
+ },
+};
diff --git a/src/core/schema-migrations/v224-page-retrievals.ts b/src/core/schema-migrations/v224-page-retrievals.ts
new file mode 100644
index 0000000000..dbb38ab15e
--- /dev/null
+++ b/src/core/schema-migrations/v224-page-retrievals.ts
@@ -0,0 +1,47 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Retrieval telemetry moves off `pages` (src/core/last-retrieved.ts). The
+// per-read `UPDATE pages SET last_retrieved_at` fired seven triggers, wrote a
+// new wide heap tuple (never HOT: the column was indexed) with an entry in
+// every pages index, and its statement trigger advanced
+// page_generation_clock_seq even when the 5-minute throttle matched no row,
+// expiring the query-cache bookmark and the get_health and projection
+// readiness memos on every read. `page_retrievals` is a narrow side table
+// with no foreign key (its KEY SHARE lock would dirty the pages row on every
+// bump); a statement trigger removes the rows of hard-deleted pages.
+//
+// BACKFILL: existing timestamps are copied in one INSERT ... SELECT (a scan of
+// pages under ACCESS SHARE; writers are not blocked). The column stays:
+// readers take GREATEST of both, so values written by an older binary on the
+// same database stay visible. Its index is dropped (no query filters or sorts
+// on the column) by the handler: CONCURRENTLY on Postgres, inline on PGLite.
+export const v224: Migration = {
+ version: 224,
+ name: 'page_retrievals',
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS page_retrievals (
+ page_id INTEGER PRIMARY KEY,
+ last_retrieved_at TIMESTAMPTZ NOT NULL
+ );
+ CREATE OR REPLACE FUNCTION gbrain_forget_page_retrievals() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+ BEGIN
+ DELETE FROM page_retrievals r USING gbrain_deleted_pages d WHERE r.page_id = d.id;
+ RETURN NULL;
+ END $$;
+ DROP TRIGGER IF EXISTS pages_forget_retrievals ON pages;
+ CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON pages
+ REFERENCING OLD TABLE AS gbrain_deleted_pages
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals();
+ INSERT INTO page_retrievals (page_id, last_retrieved_at)
+ SELECT id, last_retrieved_at FROM pages WHERE last_retrieved_at IS NOT NULL
+ ON CONFLICT (page_id) DO UPDATE SET last_retrieved_at = GREATEST(page_retrievals.last_retrieved_at, EXCLUDED.last_retrieved_at);
+ `,
+ handler: async engine => {
+ await engine.runMigration(224, `DROP INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}IF EXISTS pages_last_retrieved_at_idx;`);
+ },
+};
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index c0e4af5d4e..3b92a923b0 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -201,7 +201,8 @@ export async function buildEntityCard(
let rows: CardPageRow[] = [];
try {
rows = await engine.executeRaw<CardPageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth, updated_at, last_retrieved_at
+ `SELECT slug, source_id, title, type, frontmatter, compiled_truth, updated_at,
+ GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_at
FROM pages
WHERE deleted_at IS NULL
AND source_id = $1
@@ -225,7 +226,8 @@ export async function buildEntityCard(
if (missing.length) {
try {
const extra = await engine.executeRaw<CardPageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth, updated_at, last_retrieved_at
+ `SELECT slug, source_id, title, type, frontmatter, compiled_truth, updated_at,
+ GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_at
FROM pages
WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])${privatePredicate}`,
[sourceId, missing],
diff --git a/src/schema.sql b/src/schema.sql
index 37cafb0c15..391c01777a 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -277,13 +277,30 @@ CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id);
-- stays low. Don't add a regular `(deleted_at)` index without measuring.
CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idx
ON pages (deleted_at) WHERE deleted_at IS NOT NULL;
--- v0.37.0: full B-tree index on last_retrieved_at supports LSD's stale-page
--- query `WHERE last_retrieved_at IS NULL OR last_retrieved_at < NOW() -
--- INTERVAL '90 days'`. Postgres handles NULL in B-tree indexes (sorted to
--- one end) so one index covers both branches. A partial WHERE NOT NULL
--- would miss the NULL branch that LSD prioritizes (codex round 2 #6).
-CREATE INDEX IF NOT EXISTS pages_last_retrieved_at_idx
- ON pages (last_retrieved_at);
+-- Retrieval telemetry (src/core/last-retrieved.ts, migration v224): when a
+-- user-facing read last surfaced a page, written at most once per page per 5
+-- minutes. Kept off `pages` so the per-read upsert is a HOT update of a narrow
+-- row: an UPDATE of pages fires its triggers, rewrites a wide tuple with an
+-- entry in every pages index and advances page_generation_clock_seq, which
+-- expires the query-cache bookmark. Readers take GREATEST of this and the
+-- legacy pages.last_retrieved_at column (copied here by v224; v224 also drops
+-- its unused index). No foreign key: its KEY SHARE lock would dirty the pages
+-- row on every bump; the statement trigger below removes rows of hard-deleted
+-- pages instead.
+CREATE TABLE IF NOT EXISTS page_retrievals (
+ page_id INTEGER PRIMARY KEY,
+ last_retrieved_at TIMESTAMPTZ NOT NULL
+);
+CREATE OR REPLACE FUNCTION gbrain_forget_page_retrievals() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
+BEGIN
+ DELETE FROM page_retrievals r USING gbrain_deleted_pages d WHERE r.page_id = d.id;
+ RETURN NULL;
+END $$;
+DROP TRIGGER IF EXISTS pages_forget_retrievals ON pages;
+CREATE TRIGGER pages_forget_retrievals AFTER DELETE ON pages
+ REFERENCING OLD TABLE AS gbrain_deleted_pages
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_forget_page_retrievals();
-- v0.42.7 (migration v112): composite B-tree backing `extract --stale` and the
-- `links_extraction_lag` doctor check. source_id leads so source-scoped staleness
-- scans (`extract --stale --source X`, `gbrain doctor --source X`) are indexed;
diff --git a/test/e2e/persistence-consumers-postgres.test.ts b/test/e2e/persistence-consumers-postgres.test.ts
index 82a2d6fce1..a4bfa3c978 100644
--- a/test/e2e/persistence-consumers-postgres.test.ts
+++ b/test/e2e/persistence-consumers-postgres.test.ts
@@ -33,6 +33,7 @@ import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { admitWrite } from '../../src/core/persistence/journal.ts';
import { claimPhaseStamp, startClaimPhase } from '../../src/core/persistence/claim-phase.ts';
import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';
+import { MOVEMENT_WATERMARK_SQL } from '../../src/core/persistence/sync-movement.ts';
import { consumersWithoutHeartbeatCheck, hostIdentityMismatchCheck, twoConsumersOnHostCheck } from '../../src/commands/doctor/checks/persistence-consumers.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { hasDatabase } from './helpers.ts';
@@ -277,7 +278,7 @@ describe('persistence_consumers on PGLite (#6317)', () => {
await pglite.initSchema();
try {
const [table] = await pglite.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_consumers') IS NOT NULL AS present");
- const [index] = await pglite.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_committed_watermark') IS NOT NULL AS present");
+ const [index] = await pglite.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_sync_watermark') IS NOT NULL AND to_regclass('persistence_requests_committed_watermark') IS NULL AS present");
expect(table?.present).toBe(true);
expect(index?.present).toBe(true);
const heartbeat = startConsumerHeartbeat(pglite, randomUUID(), { kind: 'serve', mode: 'full', report: () => ({ restart_required: false, root_barrier_age_ms: null }) });
@@ -287,10 +288,15 @@ describe('persistence_consumers on PGLite (#6317)', () => {
expect(await listHostConsumers(pglite, randomUUID())).toEqual([]);
await heartbeat.stop();
if (hasDatabase()) {
- const [pg] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_committed_watermark') IS NOT NULL AS present");
+ const [pg] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_requests_sync_watermark') IS NOT NULL AND to_regclass('persistence_requests_committed_watermark') IS NULL AS present");
expect(pg?.present).toBe(true);
- const [def] = await engine.executeRaw<{ def: string }>("SELECT indexdef AS def FROM pg_indexes WHERE indexname='persistence_requests_committed_watermark'");
- expect(def?.def).toContain("(worktree_id, completed_at DESC) WHERE (state = 'committed'::text)");
+ const [def] = await engine.executeRaw<{ def: string }>("SELECT indexdef AS def FROM pg_indexes WHERE indexname='persistence_requests_sync_watermark'");
+ expect(def?.def).toContain("(worktree_id, source_incarnation, completed_at DESC) WHERE ((state = 'committed'::text) AND (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text))");
+ const plan = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL enable_seqscan = off');
+ return tx.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${MOVEMENT_WATERMARK_SQL.replaceAll('$1::uuid', `'${randomUUID()}'::uuid`).replaceAll('$2::uuid', `'${randomUUID()}'::uuid`)}`);
+ });
+ expect(plan.map(row => row['QUERY PLAN']).join('\n')).toContain('persistence_requests_sync_watermark');
}
} finally { await pglite.disconnect(); }
}, 120_000);
diff --git a/test/e2e/serve-loop-migrations-postgres.test.ts b/test/e2e/serve-loop-migrations-postgres.test.ts
new file mode 100644
index 0000000000..fe883e9072
--- /dev/null
+++ b/test/e2e/serve-loop-migrations-postgres.test.ts
@@ -0,0 +1,30 @@
+/**
+ * v223 + v224 on Postgres: the sync watermark index (built CONCURRENTLY, v222's
+ * index dropped CONCURRENTLY) and page_retrievals (timestamps copied, the
+ * column's index dropped CONCURRENTLY) on a fresh install and on an upgraded
+ * brain. PGLite twin: test/serve-loop-migrations.test.ts.
+ */
+import { afterAll, beforeAll, describe, test } from 'bun:test';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { assertFreshServeLoopSchema, assertUpgradedServeLoopSchema } from '../helpers/serve-loop-migrations.ts';
+
+let engine: PostgresEngine;
+let close: () => Promise<void>;
+
+describe.skipIf(!hasDatabase())('sync watermark index and page_retrievals (Postgres)', () => {
+ beforeAll(async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine; close = pg.close;
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('a fresh install has the sync watermark index and page_retrievals, without the superseded indexes', async () => {
+ await assertFreshServeLoopSchema(engine);
+ }, 30_000);
+
+ test('an upgraded brain gets both migrations, keeps every timestamp, and a re-run changes nothing', async () => {
+ await assertUpgradedServeLoopSchema(engine);
+ }, 60_000);
+});
diff --git a/test/helpers/serve-loop-migrations.ts b/test/helpers/serve-loop-migrations.ts
new file mode 100644
index 0000000000..92c60af585
--- /dev/null
+++ b/test/helpers/serve-loop-migrations.ts
@@ -0,0 +1,59 @@
+/**
+ * Shared body of the v223 (sync watermark index) and v224 (page_retrievals)
+ * migration tests: PGLite in `test/serve-loop-migrations.test.ts`, Postgres in
+ * `test/e2e/serve-loop-migrations-postgres.test.ts`.
+ */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { LATEST_VERSION, runMigrations } from '../../src/core/migrate.ts';
+import { MIGRATIONS } from '../../src/core/schema-migrations/registry.generated.ts';
+
+const INDEXES_SQL = `SELECT indexname AS name FROM pg_indexes WHERE indexname IN
+ ('persistence_requests_committed_watermark','persistence_requests_sync_watermark','pages_last_retrieved_at_idx') ORDER BY indexname`;
+
+/** A fresh install at head has the sync watermark index and page_retrievals, and neither superseded index. */
+export async function assertFreshServeLoopSchema(engine: BrainEngine): Promise<void> {
+ expect((await engine.executeRaw<{ name: string }>(INDEXES_SQL)).map(r => r.name)).toEqual(['persistence_requests_sync_watermark']);
+ const [table] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('page_retrievals') IS NOT NULL AS present");
+ expect(table?.present).toBe(true);
+ const triggers = await engine.executeRaw<{ name: string }>("SELECT tgname AS name FROM pg_trigger WHERE tgrelid='pages'::regclass AND tgname='pages_forget_retrievals'");
+ expect(triggers).toHaveLength(1);
+}
+
+/**
+ * An upgraded brain: v222's watermark index and the indexed pages column with
+ * timestamps, no page_retrievals. The runner swaps the watermark index, copies
+ * every timestamp into page_retrievals, drops the column's index and leaves the
+ * column's values alone; a second run changes nothing.
+ */
+export async function assertUpgradedServeLoopSchema(engine: BrainEngine): Promise<void> {
+ const v223 = MIGRATIONS.find(m => m.name === 'persistence_sync_watermark_index')!;
+ expect(MIGRATIONS.find(m => m.name === 'page_retrievals')!.version).toBe(v223.version + 1);
+ await engine.executeRaw('DELETE FROM pages');
+ const ids = (await engine.executeRaw<{ id: number }>(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, last_retrieved_at)
+ SELECT 'people/upgrade-' || g, 'default', 'person', 'Upgrade ' || g, 'body', '', CASE WHEN g % 3 = 0 THEN NULL ELSE now() - g * interval '1 hour' END
+ FROM generate_series(1, 9) g RETURNING id`)).map(r => Number(r.id));
+ await engine.executeRaw('DROP TRIGGER IF EXISTS pages_forget_retrievals ON pages');
+ await engine.executeRaw('DROP FUNCTION IF EXISTS gbrain_forget_page_retrievals()');
+ await engine.executeRaw('DROP TABLE IF EXISTS page_retrievals');
+ await engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_watermark');
+ await engine.executeRaw(`CREATE INDEX persistence_requests_committed_watermark ON persistence_requests(worktree_id,completed_at DESC) WHERE state='committed'`);
+ await engine.executeRaw('CREATE INDEX pages_last_retrieved_at_idx ON pages (last_retrieved_at)');
+ expect((await engine.executeRaw<{ name: string }>(INDEXES_SQL)).map(r => r.name)).toEqual(['pages_last_retrieved_at_idx', 'persistence_requests_committed_watermark']);
+ const column = async () => (await engine.executeRaw<{ id: number; at: string | null }>(
+ 'SELECT id, last_retrieved_at::text AS at FROM pages WHERE id = ANY($1::int[]) ORDER BY id', [ids])).map(r => [Number(r.id), r.at]);
+ const before = await column();
+
+ for (const run of [1, 2]) {
+ await engine.setConfig('version', String(v223.version - 1));
+ const result = await runMigrations(engine);
+ expect(result.current).toBe(LATEST_VERSION);
+ await assertFreshServeLoopSchema(engine);
+ const copied = (await engine.executeRaw<{ page_id: number; at: string }>('SELECT page_id, last_retrieved_at::text AS at FROM page_retrievals ORDER BY page_id'))
+ .map(r => [Number(r.page_id), r.at]);
+ expect(copied).toEqual(before.filter(([, at]) => at !== null));
+ expect(copied).toHaveLength(6);
+ expect(await column()).toEqual(before);
+ if (run === 1) await engine.executeRaw(`UPDATE page_retrievals SET last_retrieved_at = last_retrieved_at - interval '1 day'`);
+ }
+}
diff --git a/test/page-retrievals.test.ts b/test/page-retrievals.test.ts
new file mode 100644
index 0000000000..7f2cf31f65
--- /dev/null
+++ b/test/page-retrievals.test.ts
@@ -0,0 +1,138 @@
+/**
+ * Retrieval telemetry lives in `page_retrievals` (migration v224), not on
+ * `pages`. These cases pin the move: the side-table upsert bumps exactly the
+ * pages the legacy `UPDATE pages SET last_retrieved_at` bumped and leaves the
+ * same effective timestamps under the 5-minute throttle; it never advances
+ * page_generation_clock_seq; hard deletes clean up; and every reader sees
+ * GREATEST(legacy column, side table).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ BUMP_LAST_RETRIEVED_SQL,
+ bumpLastRetrievedAt,
+ awaitPendingLastRetrievedWrites,
+ _resetTrackRetrievalCacheForTests,
+} from '../src/core/last-retrieved.ts';
+import { volunteerUsageStats } from '../src/core/context/volunteer.ts';
+import { insertVolunteerEvents } from '../src/core/context/volunteer-events.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+
+const LEGACY_BUMP_SQL = `UPDATE pages SET last_retrieved_at = NOW()
+ WHERE id = ANY($1::int[]) AND (last_retrieved_at IS NULL OR last_retrieved_at < NOW() - INTERVAL '5 minutes')`;
+
+let engine: PGLiteEngine;
+
+async function seed(slug: string, title = slug): Promise<number> {
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ($1, 'default', 'person', $2, 'body', '') RETURNING id`, [slug, title]);
+ return row!.id;
+}
+const clock = async () => Number((await engine.executeRaw<{ v: string }>('SELECT last_value::text AS v FROM page_generation_clock_seq'))[0]!.v);
+const ageMinutes = async (sql: string, params: unknown[]) =>
+ (await engine.executeRaw<{ id: number; age: number | null }>(sql, params)).map(r => ({ id: Number(r.id), age: r.age === null ? null : Math.round(Number(r.age)) }));
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM context_volunteer_events').catch(() => {});
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw('DELETE FROM page_retrievals');
+ _resetTrackRetrievalCacheForTests();
+});
+
+describe('page_retrievals bump', () => {
+ test('bumps the same pages as the legacy UPDATE and leaves the same effective timestamps', async () => {
+ const never = await seed('people/never');
+ const stale = await seed('people/stale');
+ const fresh = await seed('people/fresh');
+ const softDeleted = await seed('people/soft-deleted');
+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE id = $1`, [softDeleted]);
+ const ids = [never, stale, fresh, softDeleted, 999_999];
+ const ages: Array<[number, string | null]> = [[stale, '10 minutes'], [fresh, '1 minute']];
+
+ for (const [id, age] of ages) await engine.executeRaw(`UPDATE pages SET last_retrieved_at = now() - $2::interval WHERE id = $1`, [id, age]);
+ const legacyBumped = (await engine.executeRaw<{ id: number }>(`${LEGACY_BUMP_SQL} RETURNING id`, [ids])).map(r => Number(r.id)).sort();
+ const legacy = await ageMinutes(`SELECT id, EXTRACT(EPOCH FROM now() - last_retrieved_at) / 60 AS age FROM pages ORDER BY id`, []);
+
+ await engine.executeRaw('UPDATE pages SET last_retrieved_at = NULL');
+ for (const [id, age] of ages) await engine.executeRaw(`INSERT INTO page_retrievals VALUES ($1, now() - $2::interval)`, [id, age]);
+ const sideBumped = (await engine.executeRaw<{ page_id: number }>(`${BUMP_LAST_RETRIEVED_SQL} RETURNING page_id`, [ids])).map(r => Number(r.page_id)).sort();
+ const side = await ageMinutes(`SELECT p.id, EXTRACT(EPOCH FROM now() - GREATEST(p.last_retrieved_at, r.last_retrieved_at)) / 60 AS age
+ FROM pages p LEFT JOIN page_retrievals r ON r.page_id = p.id ORDER BY p.id`, []);
+
+ expect(sideBumped).toEqual(legacyBumped);
+ expect(sideBumped).toEqual([never, stale, softDeleted].sort());
+ expect(side).toEqual(legacy);
+ expect(side.find(r => r.id === fresh)!.age).toBe(1);
+ expect(await engine.executeRaw('SELECT 1 FROM page_retrievals WHERE page_id = 999999')).toEqual([]);
+ });
+
+ test('a repeat bump inside the window writes nothing, one past it moves the timestamp', async () => {
+ const id = await seed('people/repeat');
+ expect((await engine.executeRaw(`${BUMP_LAST_RETRIEVED_SQL} RETURNING page_id`, [[id]])).length).toBe(1);
+ expect((await engine.executeRaw(`${BUMP_LAST_RETRIEVED_SQL} RETURNING page_id`, [[id, id]])).length).toBe(0);
+ await engine.executeRaw(`UPDATE page_retrievals SET last_retrieved_at = now() - interval '6 minutes'`);
+ expect((await engine.executeRaw(`${BUMP_LAST_RETRIEVED_SQL} RETURNING page_id`, [[id]])).length).toBe(1);
+ });
+
+ test('never advances the page generation clock; the legacy UPDATE did even when it matched no row', async () => {
+ const id = await seed('people/clock');
+ const before = await clock();
+ bumpLastRetrievedAt(engine, [id]);
+ bumpLastRetrievedAt(engine, [id]);
+ await awaitPendingLastRetrievedWrites();
+ expect(await clock()).toBe(before);
+ expect((await engine.executeRaw('SELECT 1 FROM page_retrievals WHERE page_id = $1', [id])).length).toBe(1);
+ await engine.executeRaw(LEGACY_BUMP_SQL, [[-1]]);
+ expect(await clock()).toBeGreaterThan(before);
+ });
+
+ test('a hard-deleted page loses its row; a soft delete keeps it', async () => {
+ const keep = await seed('people/keep');
+ const gone = await seed('people/gone');
+ await engine.executeRaw(BUMP_LAST_RETRIEVED_SQL, [[keep, gone]]);
+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [keep]);
+ await engine.executeRaw('DELETE FROM pages WHERE id = $1', [gone]);
+ const rows = (await engine.executeRaw<{ page_id: number }>('SELECT page_id FROM page_retrievals ORDER BY page_id')).map(r => Number(r.page_id));
+ expect(rows).toEqual([keep]);
+ });
+});
+
+describe('page_retrievals readers take GREATEST(legacy column, side table)', () => {
+ test('volunteer usage stats count a retrieval recorded in either place', async () => {
+ const viaSide = await seed('people/alice-example', 'Alice Example');
+ await seed('people/bob-example', 'Bob Example');
+ const unused = await seed('people/carol-example', 'Carol Example');
+ await insertVolunteerEvents(engine, ['alice-example', 'bob-example', 'carol-example'].map(name => ({
+ source_id: 'default', slug: `people/${name}`, confidence: 0.9, match_arm: 'exact', rationale: '', channel: 'op',
+ })) as never);
+ await engine.executeRaw(`INSERT INTO page_retrievals VALUES ($1, now() + interval '1 minute')`, [viaSide]);
+ await engine.executeRaw(`UPDATE pages SET last_retrieved_at = now() + interval '1 minute' WHERE slug = 'people/bob-example'`);
+ await engine.executeRaw(`INSERT INTO page_retrievals VALUES ($1, now() - interval '1 day')`, [unused]);
+ const stats = await volunteerUsageStats(engine, ['default']);
+ expect(stats.total_volunteered).toBe(3);
+ expect(stats.total_used).toBe(2);
+ });
+
+ test('domain-bank samplers and the entity card return the newer of the two timestamps', async () => {
+ const side = await seed('wiki/a/side', 'Side Example');
+ const legacy = await seed('wiki/b/legacy', 'Legacy Example');
+ await seed('wiki/c/never', 'Never Example');
+ await engine.executeRaw(`UPDATE pages SET last_retrieved_at = now() - interval '200 days' WHERE id = ANY($1::int[])`, [[side, legacy]]);
+ await engine.executeRaw(`INSERT INTO page_retrievals VALUES ($1, now() - interval '1 day'), ($2, now() - interval '300 days')`, [side, legacy]);
+ const days = (v: Date | string | null) => v === null ? null : Math.round((Date.now() - new Date(v).getTime()) / 86_400_000);
+ const sampled = await engine.listPrefixSampledPages({ prefixes: ['wiki/a', 'wiki/b', 'wiki/c'], staleBias: true });
+ expect(sampled.map(r => [r.slug, days(r.last_retrieved_at)])).toEqual([['wiki/a/side', 1], ['wiki/b/legacy', 200], ['wiki/c/never', null]]);
+ const corpus = await engine.listCorpusSample({ n: 10, seed: 0.5 });
+ expect(Object.fromEntries(corpus.map(r => [r.slug, days(r.last_retrieved_at)]))).toEqual({ 'wiki/a/side': 1, 'wiki/b/legacy': 200, 'wiki/c/never': null });
+ const card = await buildEntityCard(engine, 'default', 'Side Example', { remote: false });
+ expect(card.found).toBe(true);
+ expect(days((card as { card: { last_touched: { last_retrieved_at: string | null } } }).card.last_touched.last_retrieved_at)).toBe(1);
+ });
+});
diff --git a/test/serve-loop-migrations.test.ts b/test/serve-loop-migrations.test.ts
new file mode 100644
index 0000000000..5783404319
--- /dev/null
+++ b/test/serve-loop-migrations.test.ts
@@ -0,0 +1,26 @@
+/**
+ * v223 + v224 on PGLite: a fresh install has the sync watermark index and
+ * page_retrievals; an upgraded brain swaps v222's watermark index, copies
+ * every pages.last_retrieved_at into page_retrievals (a re-run keeps the newer
+ * value), drops the column's unused index and keeps the column. The Postgres
+ * twin is test/e2e/serve-loop-migrations-postgres.test.ts.
+ */
+import { afterAll, beforeAll, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { assertFreshServeLoopSchema, assertUpgradedServeLoopSchema } from './helpers/serve-loop-migrations.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+test('a fresh PGLite install has the sync watermark index and page_retrievals, without the superseded indexes', async () => {
+ await assertFreshServeLoopSchema(engine);
+}, 30_000);
+
+test('an upgraded PGLite brain gets both migrations, keeps every timestamp, and a re-run changes nothing', async () => {
+ await assertUpgradedServeLoopSchema(engine);
+}, 60_000);
diff --git a/test/sync-movement.test.ts b/test/sync-movement.test.ts
index 742b3309bd..2492006f03 100644
--- a/test/sync-movement.test.ts
+++ b/test/sync-movement.test.ts
@@ -32,7 +32,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { syncLockId, tryAcquireDbLock, type DbLockHandle } from '../src/core/db-lock.ts';
import { withEnv } from './helpers/with-env.ts';
-import { judgeMovement, readSourceMovement, startMovementWatch, formatSourceMovement } from '../src/core/persistence/sync-movement.ts';
+import { judgeMovement, readSourceMovement, startMovementWatch, formatSourceMovement, MOVEMENT_WATERMARK_SQL } from '../src/core/persistence/sync-movement.ts';
import { movementReport, movementWindowMs, parseMovementArgs, runMovementCheck, MOVEMENT_SUPERVISOR_STEP } from '../src/commands/sources-writer-movement.ts';
import { managedSyncMovementEntry } from '../src/commands/doctor/checks/managed-sync-movement.ts';
import { deriveNext, cliRenderContext } from '../src/core/agent-output.ts';
@@ -131,6 +131,43 @@ describe('readSourceMovement (B4)', () => {
}), 60_000);
});
+describe('movement watermark index', () => {
+ test('the watermark read returns the newest committed sync receipt of the incarnation, with and without persistence_requests_sync_watermark', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const indexes = await engine.executeRaw<{ name: string }>(`SELECT indexname AS name FROM pg_indexes WHERE indexname IN ('persistence_requests_sync_watermark','persistence_requests_committed_watermark')`);
+ expect(indexes.map(r => r.name)).toEqual(['persistence_requests_sync_watermark']);
+ const f = await managedSource();
+ const read = async () => {
+ const [row] = await engine.executeRaw<{ last_commit_at: unknown; admitted: number | string }>(MOVEMENT_WATERMARK_SQL, [f.worktreeId, f.incarnation]);
+ return { last_commit_at: row!.last_commit_at === null ? null : new Date(row!.last_commit_at as string).toISOString(), admitted: Number(row!.admitted) };
+ };
+ const unindexed = () => engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL enable_indexscan = off');
+ await tx.executeRaw('SET LOCAL enable_indexonlyscan = off');
+ await tx.executeRaw('SET LOCAL enable_bitmapscan = off');
+ const [row] = await tx.executeRaw<{ last_commit_at: unknown; admitted: number | string }>(MOVEMENT_WATERMARK_SQL, [f.worktreeId, f.incarnation]);
+ return { last_commit_at: row!.last_commit_at === null ? null : new Date(row!.last_commit_at as string).toISOString(), admitted: Number(row!.admitted) };
+ });
+ expect(await read()).toEqual({ last_commit_at: null, admitted: 0 });
+ for (let i = 0; i < 30; i++) await request(f, 'committed', { completedAt: ago(1_000 + i * 1_000), kind: 'managed_file_import' });
+ expect(await read()).toEqual(await unindexed());
+ expect((await read()).last_commit_at).toBeNull();
+ await request(f, 'committed', { completedAt: ago(90_000) });
+ const newest = await request(f, 'committed', { completedAt: ago(60_000), kind: 'managed_sync_delete' });
+ await request(f, 'committed', { completedAt: ago(30_000), kind: 'managed_sync_import' });
+ await request(f, 'queued', { kind: 'managed_sync_import' });
+ await request(f, 'queued', { kind: 'managed_file_import' });
+ await engine.executeRaw(`UPDATE persistence_requests SET source_incarnation=gen_random_uuid() WHERE worktree_id=$1::uuid AND completed_at > now()-interval '45 seconds' AND intent->>'kind'='managed_sync_import'`, [f.worktreeId]);
+ const expected = await unindexed();
+ expect(await read()).toEqual(expected);
+ expect(expected.admitted).toBe(1);
+ const [stamp] = await engine.executeRaw<{ at: string }>('SELECT completed_at AS at FROM persistence_requests WHERE request_id=$1::uuid', [newest]);
+ expect(expected.last_commit_at).toBe(new Date(stamp!.at).toISOString());
+ await engine.executeRaw(`UPDATE persistence_requests SET intent=NULL, compacted=true WHERE request_id=$1::uuid`, [newest]);
+ expect(await read()).toEqual(await unindexed());
+ expect(Date.parse((await read()).last_commit_at!)).toBeLessThan(Date.parse(stamp!.at));
+ }), 60_000);
+});
+
describe('gbrain sources writer movement (I2, T4)', () => {
const fast = { pollMs: 100 };