Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): a projection build checks it still owns its claim before it stages or seals

garrytan8bdbd5d2d8db
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 6e6d07c1ea..df229a20f6 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -375,8 +375,9 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
guarded?: boolean;
/** A create's preparation: the chunks are collected here (its page row does not exist yet) and inserted by the publication. */
hold?: SegmentChunkInput[];
- /** Guarded: runs in each batch's transaction (the projection renews its claim on the page's queue row). */
- renew?: (tx: BrainEngine) => Promise<unknown> }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
+ /** Guarded: runs in each batch's transaction before its insert (the projection renews its claim on the page's queue row);
+ * false when the caller lost its claim: that batch inserts nothing and the staging stops. */
+ renew?: (tx: BrainEngine) => Promise<boolean> }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
const fenceBudget = newFenceChunkBudget();
@@ -414,20 +415,20 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
segmentChunkWork.chunks += chunks.length;
if (input.hold) input.hold.push(...chunks);
else if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));
- let moved = false;
+ let moved = false, lost = false;
if (chunks.length && input.guarded) await faultPoint('segmented:projection_batch', { sourceId: input.sourceId, slug: input.slug });
if (chunks.length && input.guarded) rows -= chunks.length - await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);
const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [input.pageId]);
if (Number(page?.body_generation) !== input.generation) { moved = true; return 0; }
+ if (input.renew && !await input.renew(tx)) { lost = true; return 0; }
const open = new Set((await occurrencesWithoutChunks(tx, input.pageId, input.generation, batch)).map(row => row.occurrenceId));
const still = chunks.filter(chunk => open.has(chunk.occurrence_id));
- await input.renew?.(tx);
if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);
return still.length;
});
rows += chunks.length;
- if (moved) break;
+ if (moved || lost) break;
done += batch.length;
collectBatchGarbage();
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 3bdf632831..b660b949d2 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -14,8 +14,13 @@
* chunk the whole body; a claim left by a dead process lapses after
* SEGMENTED_PROJECTION_LEASE_SECONDS, and a build that throws releases it
* at once (the resident's queue route then marks its own failures
- * `rebuild_failed`). Within a process, calls for one page also run one after
- * another, and a page an earlier call sealed returns at once (#6143).
+ * `rebuild_failed`). The claim is this build's while the row's `updated_at`
+ * is the stamp it last wrote: each renewal, the seal and the release match
+ * that stamp, so a build that outlived its claim and lost it to another
+ * process stops at its next batch (`claimLost`) without staging, sealing or
+ * releasing over the new owner's claim. Within a process, calls for one page
+ * also run one after another, and a page an earlier call sealed returns at
+ * once (#6143).
*
* Retirement runs in bounded statements and deletes, as the flip does: rows of
* occurrences outside the live generation, inline rows a promotion deferred,
@@ -34,7 +39,8 @@ import { DEFAULT_FLIP_RETIRE_MAX_ROWS } from './limits.ts';
import type { JsonObject } from './types.ts';
import { assertGenerationTiles } from './body-tiling.ts';
-export interface SegmentedProjectionResult { chunks: number; retired: number; sealed: boolean }
+/** `claimLost`: another process took the page's claim over (or a write re-queued the page) during the build, which stopped unsealed. */
+export interface SegmentedProjectionResult { chunks: number; retired: number; sealed: boolean; claimLost?: true }
interface ProjectionPage {
id: number; body_generation: number | string; knowledge_revision: string; text_projection_revision: string | null;
@@ -106,13 +112,36 @@ async function retireStaleChunks(engine: BrainEngine, ref: { sourceId: string; s
const JOB_OF_PAGE = 'source_incarnation=(SELECT incarnation FROM sources WHERE id=$1) AND slug=$2';
-/** Claim the page's queue row; false when another process holds it. A page with no queued row is built unclaimed. */
-async function claimProjection(engine: Pick<BrainEngine, 'executeRaw'>, ref: { sourceId: string; slug: string }): Promise<boolean> {
- const [job] = await engine.executeRaw<{ claimed: boolean }>(`WITH claimed AS (UPDATE page_projection_jobs SET reason='${SEGMENTED_PROJECTION_CLAIM}', updated_at=now()
- WHERE ${JOB_OF_PAGE} AND NOT (reason='${SEGMENTED_PROJECTION_CLAIM}' AND updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds') RETURNING 1)
- SELECT EXISTS (SELECT 1 FROM claimed) AS claimed WHERE EXISTS (SELECT 1 FROM claimed) OR EXISTS (SELECT 1 FROM page_projection_jobs WHERE ${JOB_OF_PAGE})`,
+/** This build's claim: the `updated_at` it last wrote on the page's queue row. Null for a page built unclaimed. */
+type ProjectionClaim = { stamp: string } | null;
+
+/** The page's queue row while it carries this build's claim ($3: its stamp). A function: projections.ts imports this module, so its constants are not initialized while this module loads. */
+const claimedByBuild = () => `${JOB_OF_PAGE} AND reason='${SEGMENTED_PROJECTION_CLAIM}' AND updated_at=$3::text::timestamptz`;
+
+/** Claim the page's queue row; false when another process holds it. A page with no queued row is built unclaimed (null). */
+async function claimProjection(engine: Pick<BrainEngine, 'executeRaw'>, ref: { sourceId: string; slug: string }): Promise<ProjectionClaim | false> {
+ const [job] = await engine.executeRaw<{ stamp: string | null }>(`WITH claimed AS (UPDATE page_projection_jobs SET reason='${SEGMENTED_PROJECTION_CLAIM}', updated_at=now()
+ WHERE ${JOB_OF_PAGE} AND NOT (reason='${SEGMENTED_PROJECTION_CLAIM}' AND updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds')
+ RETURNING updated_at::text AS stamp)
+ SELECT (SELECT stamp FROM claimed) AS stamp WHERE EXISTS (SELECT 1 FROM claimed) OR EXISTS (SELECT 1 FROM page_projection_jobs WHERE ${JOB_OF_PAGE})`,
[ref.sourceId, ref.slug]);
- return !job || job.claimed;
+ if (!job) return null;
+ return job.stamp === null ? false : { stamp: job.stamp };
+}
+
+/**
+ * Renew this build's claim in `tx`, holding the row until `tx` ends so no other process claims it meanwhile; false when
+ * the row no longer carries the claim (another process took it over, or a write re-queued the page), changing nothing.
+ * A renewal whose transaction rolls back leaves the stamp ahead of the row, so that build's release misses and its claim
+ * lapses after the lease: it never matches another build's claim.
+ */
+async function renewClaim(tx: Pick<BrainEngine, 'executeRaw'>, ref: { sourceId: string; slug: string }, claim: ProjectionClaim): Promise<boolean> {
+ if (!claim) return true;
+ const [row] = await tx.executeRaw<{ stamp: string }>(`UPDATE page_projection_jobs SET updated_at=now() WHERE ${claimedByBuild()} RETURNING updated_at::text AS stamp`,
+ [ref.sourceId, ref.slug, claim.stamp]);
+ if (!row) return false;
+ claim.stamp = row.stamp;
+ return true;
}
/** The projections of each engine's pages running in this process, by source and slug: the newest call of each page. */
@@ -146,17 +175,19 @@ async function projectSegmentedPage(engine: BrainEngine, ref: { sourceId: string
&& !await hasStaleChunks(engine, Number(page.id), Number(page.body_generation), await liveOccurrenceIds(engine, Number(page.id), Number(page.body_generation)))) {
return { chunks: 0, retired: 0, sealed: true };
}
- if (!await claimProjection(engine, ref)) return { chunks: 0, retired: 0, sealed: false };
+ const claim = await claimProjection(engine, ref);
+ if (claim === false) return { chunks: 0, retired: 0, sealed: false };
try {
- return await buildClaimedProjection(engine, ref, page);
+ return await buildClaimedProjection(engine, ref, page, claim);
} catch (error) {
- await engine.executeRaw(`UPDATE page_projection_jobs SET reason='canonical_change', updated_at=now() WHERE ${JOB_OF_PAGE} AND reason='${SEGMENTED_PROJECTION_CLAIM}'`,
- [ref.sourceId, ref.slug]).catch(() => undefined);
+ if (claim) await engine.executeRaw(`UPDATE page_projection_jobs SET reason='canonical_change', updated_at=now() WHERE ${claimedByBuild()}`,
+ [ref.sourceId, ref.slug, claim.stamp]).catch(() => undefined);
throw error;
}
}
-async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: string; slug: string }, page: ProjectionPage): Promise<SegmentedProjectionResult> {
+async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: string; slug: string }, page: ProjectionPage,
+ claim: ProjectionClaim): Promise<SegmentedProjectionResult> {
const generation = Number(page.body_generation);
const pageId = Number(page.id);
const liveRows = await engine.readManifest(pageId);
@@ -166,18 +197,22 @@ async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: stri
const frontmatter = page.frontmatter ?? {};
const quarantined = isQuarantined(frontmatter);
const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);
+ let claimLost = false;
const staged = await stageOccurrenceChunks(engine, { pageId, sourceId: ref.sourceId, slug: ref.slug, generation, occurrences: unchunked, title: page.title,
frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guarded: true,
- renew: tx => tx.executeRaw(`UPDATE page_projection_jobs SET updated_at=now() WHERE ${JOB_OF_PAGE} AND reason='${SEGMENTED_PROJECTION_CLAIM}'`, [ref.sourceId, ref.slug]) });
+ renew: async tx => { claimLost = !await renewClaim(tx, ref, claim); return !claimLost; } });
+ if (claimLost) return { chunks: staged.rows, retired, sealed: false, claimLost: true };
await faultPoint('segmented:projection_staged', { sourceId: ref.sourceId, slug: ref.slug });
const sealed = await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: ref.sourceId, slug: ref.slug }]);
const current = await readProjectionPage(tx, ref);
if (!current || current.knowledge_revision !== page.knowledge_revision || Number(current.body_generation) !== generation) return false;
- if (current.text_projection_revision !== current.knowledge_revision) await sealSegmentedPage(tx, pageId, current.timeline_lead ?? '');
+ if (current.text_projection_revision === current.knowledge_revision) return true;
+ if (!await renewClaim(tx, ref, claim)) { claimLost = true; return false; }
+ await sealSegmentedPage(tx, pageId, current.timeline_lead ?? '');
return true;
});
- return { chunks: staged.rows, retired, sealed };
+ return claimLost ? { chunks: staged.rows, retired, sealed: false, claimLost: true } : { chunks: staged.rows, retired, sealed };
}
/**
@@ -215,8 +250,8 @@ export async function rebuildPendingSegmentedProjections(engine: BrainEngine, li
await engine.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [job.source_incarnation, job.slug, job.revision]);
} catch (error) {
failed++;
- 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]);
+ await engine.executeRaw(`UPDATE page_projection_jobs j SET reason='rebuild_failed', updated_at=now()
+ WHERE j.source_incarnation=$1::uuid AND j.slug=$2 AND j.revision=$3::uuid AND NOT ${SEGMENTED_PROJECTION_CLAIMED_SQL}`, [job.source_incarnation, job.slug, job.revision]);
opts.onFailure?.({ source_id: job.source_id, slug: job.slug, reason: (error instanceof Error ? error.message : String(error)).split('\n')[0]!.slice(0, 300) });
}
}
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index ed573520f0..e278a8073b 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -460,6 +460,8 @@ export async function noteProjectionRebuilds(engine: BrainEngine, rebuilt: numbe
/**
* The queue reason of a segmented page whose projection a process is building (buildSegmentedProjection): the claim
* holds while its `updated_at`, renewed with each chunk batch, is younger than SEGMENTED_PROJECTION_LEASE_SECONDS.
+ * That `updated_at` is also the building process's stamp: its renewals, seal and release match it, so any other write
+ * to a claimed row's `updated_at` hands the claim back; a deferral or failure mark skips a live claim.
*/
export const SEGMENTED_PROJECTION_CLAIM = 'segmented_projecting';
export const SEGMENTED_PROJECTION_LEASE_SECONDS = 60;
@@ -701,7 +703,8 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
const built = await buildSegmentedProjection(engine, { sourceId: job.source_id, slug: job.slug });
await engine.executeRaw(built.sealed
? 'DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid'
- : 'UPDATE page_projection_jobs SET updated_at=now() WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', observed);
+ : `UPDATE page_projection_jobs j SET updated_at=now() WHERE j.source_incarnation=$1::uuid AND j.slug=$2 AND j.revision=$3::uuid
+ AND NOT ${SEGMENTED_PROJECTION_CLAIMED_SQL}`, observed);
if (built.sealed) rebuilt++;
else superseded++;
continue;
@@ -711,8 +714,8 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
rebuilt++;
} catch (error) {
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`, observed);
+ await engine.executeRaw(`UPDATE page_projection_jobs j SET reason='rebuild_failed',updated_at=now()
+ WHERE j.source_incarnation=$1::uuid AND j.slug=$2 AND j.revision=$3::uuid AND NOT ${SEGMENTED_PROJECTION_CLAIMED_SQL}`, observed);
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;