Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(projections): budgeted resident drain with an injected clock (#5401)
garrytand7c53cef8f85
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex d55c4f9453..497b425225 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -33,7 +33,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 6e91b02c4c..8d38f5d765 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.-- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.+- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply.Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 35baa868cd..bec7493e28 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -302,25 +302,69 @@ const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources s*/const statisticsDebt = new WeakMap<BrainEngine, { rebuilt: number; rows: number | null }>();+/**+ * #5401: a failed rebuild waits this long before the resident retries it. One+ * fragment over `page_projection_jobs j`, shared by the consumer's idle probe+ * and the resident's selector.+ */+export const PROJECTION_RETRY_READY_SQL = "(j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds')";++export interface ProjectionRebuildFailure { source_id: string; slug: string; reason: string }++export interface ProjectionRebuildOptions {+ /** Stop starting new pages once this many milliseconds have passed since the call began; the first page always starts. */+ deadlineMs?: number;+ /** Injectable clock in milliseconds, for the deadline. */+ now?: () => number;+ /**+ * Only rows last queued or failed at or before this database instant (text,+ * cast in SQL so microseconds survive). A caller that waits for the database+ * clock to pass it tries each row at most once per run.+ */+ notAfter?: string;+ /** Skip failed rows inside their retry window (PROJECTION_RETRY_READY_SQL). */+ retryCooldown?: boolean;+ /** Receives each failed page; without it a generic stderr line is printed. */+ onFailure?: (failure: ProjectionRebuildFailure) => void;+}++/** Live Markdown and code rows a rebuild can take, and how many of them last failed. */+export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ pending: number; failed: number; oldest_age_seconds: number | null }> {+ const [row] = await engine.executeRaw<{ pending: number; failed: number; oldest: number | null }>(`SELECT COUNT(*)::int AS pending,+ COUNT(*) FILTER (WHERE j.reason='rebuild_failed')::int AS failed,+ EXTRACT(EPOCH FROM now()-MIN(j.updated_at))::float8 AS oldest+ FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}`);+ const oldest = row?.oldest === null || row?.oldest === undefined ? null : Math.max(0, Math.floor(Number(row.oldest)));+ return { pending: Number(row?.pending ?? 0), failed: Number(row?.failed ?? 0), oldest_age_seconds: oldest };+}+/** Bounded and keyless. Unsupported media remains queued for its source importer. */-export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20): Promise<{ rebuilt: number; superseded: number }> {+export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20, opts: ProjectionRebuildOptions = {}): Promise<{ rebuilt: number; superseded: number }> {+ const now = opts.now ?? Date.now;+ const startedAt = now();+ const params: unknown[] = [Math.max(1, Math.min(limit, 100))];+ const filters: string[] = [];+ if (opts.retryCooldown) filters.push(PROJECTION_RETRY_READY_SQL);+ if (opts.notAfter !== undefined) { params.push(opts.notAfter); filters.push(`j.updated_at<=$${params.length}::text::timestamptz`); }const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind- FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs+ FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs j+ ${filters.length ? `WHERE ${filters.join(' AND ')}` : ''}ORDER BY updated_at,source_incarnation,slug OFFSET 0) j${PROJECTION_JOB_PROBES}- ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, Math.min(limit, 100))]);+ ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, params);let rebuilt = 0;let superseded = 0;- for (const job of jobs) {- const prepared = await engine.transaction(async tx => {- await tx.lockPageKeys([{ sourceId: job.source_id, slug: job.slug }]);- const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs- WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);- if (!pending.length) return null;- return readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });- });- if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }+ for (const [index, job] of jobs.entries()) {+ if (opts.deadlineMs !== undefined && index > 0 && now() - startedAt >= opts.deadlineMs) break;try {+ const prepared = await engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: job.source_id, slug: job.slug }]);+ const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs+ WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);+ if (!pending.length) return null;+ return readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });+ });+ if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }const projection = await preparePageProjection(prepared);await installPageProjection(engine, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });rebuilt++;@@ -328,7 +372,8 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =if (!(error instanceof PageRevisionConflictError)) {await engine.executeRaw(`UPDATE page_projection_jobs SET reason='rebuild_failed',updated_at=now()WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);- process.stderr.write('[gbrain] Projection rebuild failed; work remains queued. Inspect projection readiness and the recorded source path.\n');+ if (opts.onFailure) opts.onFailure({ source_id: job.source_id, slug: job.slug, reason: (error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300) });+ else process.stderr.write('[gbrain] Projection rebuild failed; work remains queued. Inspect projection readiness and the recorded source path.\n');continue;}superseded++;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 6a6de27bcd..e164f06283 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,16 +1,32 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimNextWrite, compactWriteReceipts, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';+import { CLAIMABLE_WRITE_SQL, claimNextWrite, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { isTerminal, type WriteRequest } from './model.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';-import { rebuildPendingPageProjections } from '../page-state/projections.ts';+import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';import { publicationConcurrency } from './pool-capacity.ts';import { runPersistenceEffects } from './effects.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';+/**+ * #5401: one resident projection invocation takes up to this many pages and+ * starts no new page once the budget has passed since it began. When a write is+ * claimable at its start it takes the small batch, so the drain never delays+ * queued writes by more than about two page rebuilds.+ */+export const RESIDENT_PROJECTION_PAGES = 100;+export const RESIDENT_PROJECTION_BUDGET_MS = 250;+export const WRITE_WAITING_PROJECTION_PAGES = 2;++export async function runResidentProjectionInvocation(engine: BrainEngine, hostId: string, excludeRoots: string[], now: () => number = Date.now) {+ const writesWaiting = publicationConcurrency(engine) > 0 && await hasClaimableWrite(engine, hostId, excludeRoots);+ return rebuildPendingPageProjections(engine, writesWaiting ? WRITE_WAITING_PROJECTION_PAGES : RESIDENT_PROJECTION_PAGES,+ { deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now, retryCooldown: true });+}+export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;export class PersistenceConsumer {private stopping = false;@@ -92,13 +108,7 @@ export class PersistenceConsumer {const retryingTopologies = [...this.topologyRetryAfter.keys()];const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(await this.acquireIdleLane(signal), `SELECT (EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id- WHERE r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))- AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))- AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)- AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)- AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier- WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))+ WHERE ${CLAIMABLE_WRITE_SQL}AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))OR EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_idWHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT (r.worktree_id::text=ANY($2::text[])))@@ -117,7 +127,7 @@ export class PersistenceConsumer {OR EXISTS (SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnationJOIN pages p ON p.source_id=s.id AND p.slug=j.slugWHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')- AND (j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds'))+ AND ${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[])))@@ -246,7 +256,8 @@ export class PersistenceConsumer {.then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}- if (!this.projectionWorker) this.projectionWorker = rebuildPendingPageProjections(this.engine, 2)+ if (!this.projectionWorker) this.projectionWorker = runResidentProjectionInvocation(this.engine, this.hostId,+ [...this.activeRoots, ...this.rootRetryAfter.keys()]).catch(error => this.report(error)).finally(() => { this.projectionWorker = undefined; });// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,// proves that a previous process can no longer be publishing this root.diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 54505171a6..3374674492 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -182,20 +182,34 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over} };}-/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */-export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {- return engine.transactionDirect(async tx => {- await declarePersistenceProtocol(tx);- const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r- LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id- WHERE r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))+/**+ * The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN+ * persistence_worktrees w`, with $1 = host id and $2 = excluded root keys. An+ * unresolved head blocks its entire root.+ */+export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests earlierWHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))+ AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))`;++/** #5401: whether `claimNextWrite` would find a row now. Read-only: no lock and no claim. */+export async function hasClaimableWrite(engine: SqlEngine, hostId: string, excludeRoots: string[] = []): Promise<boolean> {+ const [row] = await engine.executeRaw<{ claimable: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${CLAIMABLE_WRITE_SQL} LIMIT 1) AS claimable`, [hostId, excludeRoots]);+ return row?.claimable === true;+}++/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */+export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {+ return engine.transactionDirect(async tx => {+ await declarePersistenceProtocol(tx);+ const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id+ WHERE ${CLAIMABLE_WRITE_SQL}ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]);if (!row) return null;const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',