Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): project a segmented page once at a time (#6143)

garrytand882c1269ec0
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index a1f1c115e4..ead30de1fa 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -56,10 +56,33 @@ async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'
}
}
+/** The projections of each engine's pages running in this process, by source and slug: the newest call of each page. */
+const projecting = new WeakMap<BrainEngine, Map<string, Promise<unknown>>>();
+
+/**
+ * #6143: one projection of a page at a time in this process. A segmented
+ * create's publication projects the page after commit while the resident
+ * drain picks up the job its unsealed commit queued; run side by side, both
+ * chunk the whole body and pin a pooled connection each, one waiting on the
+ * other's page guard, for every batch. A call for a page another call is
+ * projecting waits for it, and a page that call sealed has nothing left to project.
+ */
export async function buildSegmentedProjection(engine: BrainEngine, ref: { sourceId: string; slug: string },
opts: { expectedRevision?: string } = {}): Promise<SegmentedProjectionResult> {
+ let pages = projecting.get(engine);
+ if (!pages) projecting.set(engine, pages = new Map());
+ const key = JSON.stringify([ref.sourceId, ref.slug]);
+ const run = (pages.get(key) ?? Promise.resolve()).catch(() => undefined).then(() => projectSegmentedPage(engine, ref, opts));
+ pages.set(key, run);
+ try { return await run; }
+ finally { if (pages.get(key) === run) pages.delete(key); }
+}
+
+async function projectSegmentedPage(engine: BrainEngine, ref: { sourceId: string; slug: string },
+ opts: { expectedRevision?: string }): Promise<SegmentedProjectionResult> {
const page = await readProjectionPage(engine, ref);
if (!page || (opts.expectedRevision !== undefined && page.knowledge_revision !== opts.expectedRevision)) return { chunks: 0, retired: 0, sealed: false };
+ if (page.text_projection_revision === page.knowledge_revision) return { chunks: 0, retired: 0, sealed: true };
const generation = Number(page.body_generation);
const pageId = Number(page.id);
const liveRows = await engine.readManifest(pageId);
@@ -69,7 +92,7 @@ export async function buildSegmentedProjection(engine: BrainEngine, ref: { sourc
const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);
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 });
- await faultPoint('segmented:projection_staged', { sourceId: ref.sourceId });
+ 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);
diff --git a/test/large-pages/segmented-derived-work.test.ts b/test/large-pages/segmented-derived-work.test.ts
index f2ca2c288e..3ec4e3ba49 100644
--- a/test/large-pages/segmented-derived-work.test.ts
+++ b/test/large-pages/segmented-derived-work.test.ts
@@ -14,6 +14,9 @@
* trusted put_page (auto_link on) publishes a segmented page with its derived
* links and temporal evidence, edit_page edits one, and a put_page that
* shrinks one to inline versions the segmented body before demoting it;
+ * a segmented create is projected once at a time (#6143: the resident
+ * drain waits for the publication's own projection instead of chunking
+ * the same page beside it);
* re-linking one later (autoLinkWrittenPage, `extract --slugs`) reads its
* materialized body; the managed stale-links pass after a managed import
* links a segmented page within the ceiling and skips one over it as
@@ -52,6 +55,7 @@ import { extractManagedStaleLinks } from '../../src/core/persistence/links-maint
import { autoLinkWrittenPage } from '../../src/core/ops/pages.ts';
import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
const config = { engine: 'pglite' as const, embedding_disabled: true };
const CLIENT = 'client-segmented-derived';
@@ -285,6 +289,31 @@ describe('trusted coordinated writes of segmented pages', () => {
}
}, 300_000);
+ test('a segmented create is projected once at a time: the resident drain waits for the publication\'s own projection (#6143)', async () => {
+ const slug = 'meetings/segmented-single-flight';
+ const concurrent: Record<string, number> = {}, pages: Record<string, unknown> = {};
+ for (const engine of engines) {
+ await linkTargets(engine);
+ let inside = 0, most = 0, arrivals = 0;
+ // The first projection of the page to stage its chunks holds its seal open for a while: a second projection of the
+ // same page running beside it (the resident drain picking up the queued job) reaches the same point meanwhile.
+ installFaultHook(async (point, detail) => {
+ if (point !== 'segmented:projection_staged' || detail.slug !== slug) return;
+ inside++; arrivals++; most = Math.max(most, inside);
+ if (arrivals === 1) for (const until = Date.now() + 1500; inside < 2 && Date.now() < until;) await new Promise(resolve => setTimeout(resolve, 20));
+ inside--;
+ });
+ try {
+ expect((await localCall(engine, 'put_page', { slug, content: linkedMeeting('Single flight') })).isError).toBe(false);
+ } finally { installFaultHook(undefined); }
+ concurrent[engine.kind] = most;
+ pages[engine.kind] = await engine.executeRaw(`SELECT body_storage, text_projection_revision=knowledge_revision AS sealed FROM pages
+ WHERE source_id='default' AND slug=$1`, [slug]);
+ }
+ expect(concurrent).toEqual(Object.fromEntries(engines.map(engine => [engine.kind, 1])));
+ expect(pages).toEqual(Object.fromEntries(engines.map(engine => [engine.kind, [{ body_storage: 'segmented', sealed: true }]])));
+ }, 300_000);
+
test('re-linking a segmented page later (autoLinkWrittenPage, extract --slugs) reads its materialized body', async () => {
for (const engine of engines) {
await linkTargets(engine);