Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(#6007): batch admission reads once per batch; group waits settle together; fewer apply statements

garrytanee6140784f52
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index e1d00035bd..7c18d3ea15 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -41,7 +41,7 @@ src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline,
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 447 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/import-file.ts importFromContent 807 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts)
+src/core/import-file.ts importFromContent 808 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 377 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler 884 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 814 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index b15c1ac1be..6982324e93 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1,5 +1,6 @@
import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
+import type { PreparedImportApplied } from './persistence/prepared-import.ts';
import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';
@@ -822,7 +823,7 @@ export async function importFromContent(
const txOpts = { sourceId: sourceId ?? 'default' };
let persistedProjection: ProjectionSnapshot | null = null;
const timeZone = await loadBrainTimeZone(engine);
- const applyPrepared = async (tx: BrainEngine) => {
+ const applyPrepared = async (tx: BrainEngine): Promise<PreparedImportApplied> => {
await assertImportBase(tx, slug, txOpts.sourceId, existing);
await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);
if (existing) await tx.createVersion(slug, txOpts);
@@ -845,7 +846,7 @@ export async function importFromContent(
createdAt: fallbackCreatedAt({ existing, fileTimes: opts.fileTimes, now: nowDate }),
});
- await tx.putPage(slug, {
+ const written = await tx.putPage(slug, {
type: parsed.type,
title: parsed.title,
compiled_truth: parsed.compiled_truth,
@@ -973,6 +974,7 @@ export async function importFromContent(
// guard. Deferred provider results cannot replace newer text or chunks.
persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);
}
+ return { livePageId: written && written.deleted_at == null ? written.id : undefined, sealed: !opts.beforeCommit };
};
if (opts.prepare) return opts.prepare({
slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 8232785f6d..aede433ea2 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -249,7 +249,7 @@ function takeCollision(): OperationError {
* what this writer actually edited.
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
- prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine) => Promise<void>> {
+ prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine, livePageId?: number) => Promise<void>> {
const { factRows, takes } = compileCanonicalProjections(page, slug, sourceId);
const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
page, prior?.page ?? null, slug, writer);
@@ -265,9 +265,10 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num
WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) LIMIT 1`, [pageId, newTakes])).length > 0;
if (prior && await collides(engine, prior.page.id)) throw takeCollision();
- return async tx=>{
- const snapshot=await tx.readPageSnapshot(slug,{sourceId});
- if (!snapshot) return;
+ // #6007: `livePageId` is the id of the page the caller just wrote live in this transaction; it replaces the snapshot read.
+ return async (tx, livePageId?: number)=>{
+ const snapshot=livePageId === undefined ? await tx.readPageSnapshot(slug,{sourceId}) : null;
+ if (livePageId === undefined && !snapshot) return;
// Fact IDs in permanent receipts remain meaningful when a canonical row is
// removed/replaced. Expire and detach its row position instead of deleting it.
// Conversation-extractor rows share the page coordinate without a fence
@@ -290,9 +291,10 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
fact.valid_until?.toISOString()??null,fact.expired_at?.toISOString()??null,fact.source,fact.confidence,
fact.claim_metric??null,fact.claim_value??null,fact.claim_unit??null,fact.claim_period??null]);
}
- const pageId=snapshot.page.id;
- if (await collides(tx,pageId)) throw takeCollision();
- await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])',[pageId,takeRowsGone]);
+ const pageId=livePageId ?? snapshot!.page.id;
+ // Statements whose input set is empty change nothing and are skipped.
+ if (newTakes !== '[]' && await collides(tx,pageId)) throw takeCollision();
+ if (takeRowsGone.length) await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])',[pageId,takeRowsGone]);
if (takes.length) await tx.addTakesBatch(takes.map(t=>takesPreparation.toCanonicalBatchInput(pageId,t)));
// Full canonical versions include resolution fields; a revert restores those
// fields from Markdown too, without the ordinary immutable-resolution API.
@@ -302,12 +304,12 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
take.resolvedQuality==='correct'?true:take.resolvedQuality==='incorrect'?false:null,
take.resolvedEvidence??null,take.resolvedValue??null,take.resolvedUnit??null,take.resolvedBy??null]);
// Event-page references have a different canonical origin and remain intact.
- await tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)
+ if (deletions !== '[]') await tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source
AND t.summary=d.summary AND t.detail=d.detail`,[pageId,deletions]);
// New rows carry their Markdown detail on insert; pinned rows refresh only from their preimage.
for (const entry of timeline.values()) await tx.addTimelineEntry(slug,entry,{sourceId});
- await tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
+ if (refreshes !== '[]') await tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`,[pageId,refreshes]);
};
}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 5a62d3a3ad..f6eac2e207 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -29,7 +29,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
const revision = snapshot?.revision;
const data = { slug: row.slug, page_id: snapshot?.page.id };
// #6007: the effects are inserted together, in queue order, by one statement at the end.
- const queued: { kind: EffectKind; data: Record<string, unknown> }[] = [];
+ const queued: { kind: EffectKind; data: Record<string, unknown>; gated?: boolean }[] = [];
const queue = (kind: EffectKind, extra: Record<string, unknown> = {}) => { queued.push({ kind, data: { ...data, ...extra } }); };
if (prepared?.file && row.worktree_id) {
const [binding] = await tx.executeRaw<{ local_path: string }>(`SELECT h.local_path FROM persistence_host_bindings h
@@ -46,22 +46,21 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };
else queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
- if (queuesMentionLinks(row)) {
- const queued = await tx.executeRaw(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
- SELECT $1::uuid,'links',$2::uuid,$3::text::jsonb,$4,$5::uuid,$6::uuid WHERE NOT EXISTS (SELECT 1 FROM config
- WHERE key IN ('auto_link',$7) AND lower(btrim(value,E' \\t\\r\\n')) IN ('false','0','no','off'))
- ON CONFLICT(request_id,kind) DO NOTHING RETURNING id`,
- [row.id, revision ?? null, JSON.stringify(data), row.source_id, row.source_incarnation, row.worktree_id, REMOTE_AUTO_LINKS_KEY]);
- if (queued.length) outcome.auto_links = { ...(outcome.auto_links as Record<string, unknown> | undefined), mention_links: 'queued' };
- if (!opts.deferBatchReconcile) await reconcileFinishedBatch(tx, row);
- }
+ // The links effect is inserted with the others, gated in SQL on auto_link and mcp.remote_auto_links.
+ if (queuesMentionLinks(row)) queued.push({ kind: 'links', data: { ...data }, gated: true });
// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
await recordChronicleDecision(tx, row, snapshot, outcome);
}
- if (queued.length) await tx.executeRaw(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
+ const inserted = queued.length ? await tx.executeRaw<{ kind: string }>(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)
SELECT $1::uuid,t.e->>'kind',$2::uuid,t.e->'data',$3,$4::uuid,$5::uuid FROM jsonb_array_elements($6::text::jsonb) WITH ORDINALITY AS t(e,n)
- ORDER BY t.n ON CONFLICT(request_id,kind) DO NOTHING`,
- [row.id, revision ?? null, row.source_id, row.source_incarnation, row.worktree_id, JSON.stringify(queued)]);
+ WHERE NOT (COALESCE((t.e->>'gated')::boolean,false) AND EXISTS (SELECT 1 FROM config
+ WHERE key IN ('auto_link',$7) AND lower(btrim(value,E' \\t\\r\\n')) IN ('false','0','no','off')))
+ ORDER BY t.n ON CONFLICT(request_id,kind) DO NOTHING RETURNING kind`,
+ [row.id, revision ?? null, row.source_id, row.source_incarnation, row.worktree_id, JSON.stringify(queued), REMOTE_AUTO_LINKS_KEY]) : [];
+ if (queued.some(effect => effect.kind === 'links')) {
+ if (inserted.some(effect => effect.kind === 'links')) outcome.auto_links = { ...(outcome.auto_links as Record<string, unknown> | undefined), mention_links: 'queued' };
+ if (!opts.deferBatchReconcile) await reconcileFinishedBatch(tx, row);
+ }
}
/** Whether a publication of this request queues a mention `links` effect: a remote page write without trusted auto-linking. */
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 15ec467b82..11d7d7efe6 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -22,7 +22,7 @@ import { pageBatchChildRequestId, pageBatchChildRequestIds } from './page-batch-
export { pageBatchChildRequestId };
import { isTerminal, type WriteRequest } from './model.ts';
import { estimatedRetryAfterMs, waitForWrites, writeResponse } from './service.ts';
-import { initializeLocalPersistence, pageMutationSource, preparePageAdmission, requestPrincipalForContext } from './page-mutations.ts';
+import { initializeLocalPersistence, pageMutationSource, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';
import type { PageTypeWarning } from './page-input.ts';
import { parseWriteRequestId } from './preconditions.ts';
import { parseWireWriteWaitMs } from './write-wait.ts';
@@ -157,9 +157,14 @@ async function admitBatch(ctx: OperationContext, batchId: string, admissions: Wr
}), BATCH_ADMISSION_BUDGET_MS);
}
-async function prepareAll(ctx: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {
+async function prepareAll(caller: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {
+ // #6007 (workstream A): one writer verification and one shared-read snapshot per batch (page-mutations.ts withBatchAdmission).
+ return withBatchAdmission(caller, (own, shared) => preparePages(own, shared, batchId, sourceId, pages));
+}
+async function preparePages(own: OperationContext, shared: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {
const prepared: (Awaited<ReturnType<typeof preparePageAdmission>> | OperationError)[] = new Array(pages.length);
const prepareOne = async (index: number) => {
+ const ctx = index === 0 ? own : shared;
const page = pages[index]!;
const params: Record<string, unknown> = { slug: page.slug, content: page.content, source_id: sourceId };
if (page.expected_revision !== undefined) params.expected_revision = page.expected_revision;
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index ab766eb12f..140958c213 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -13,7 +13,8 @@ import { assertPersistenceAccepting, estimatedRetryAfterMs, waitForWrite, writeR
import { parseWireWriteWaitMs } from './write-wait.ts';
import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
import { submissionAuthority, authorizeStoredRequest } from './authority.ts';
-import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
+import type { BrainEngine } from '../engine.ts';
import { claimWorktree, getWorktreeBinding } from './ownership.ts';
import { parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
@@ -38,6 +39,50 @@ export async function requestPrincipalForContext(ctx: OperationContext): Promise
export async function initializeLocalPersistence(ctx: OperationContext): Promise<void> {
if (!ctx.auth && !currentVerifiedLocalWriter()) await registerLocalWriter(ctx.engine, ctx.remote === false ? 'cli' : 'stdio');
}
+const flatSql = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+/**
+ * Pre-admission reads every page of one batch makes with the same arguments:
+ * the source row, the worktree binding, the writer registration, the shared
+ * skillpack roots, the persistence identity and config values. All of them
+ * are rechecked under lock by the admission transaction.
+ */
+const BATCH_SHARED_READS = new Set([
+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1",
+ 'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1',
+ 'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid',
+ 'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',
+ 'SELECT brain_id FROM persistence_brain WHERE singleton=1',
+ 'SELECT value FROM config WHERE key=$1',
+]);
+function batchSharedReads(engine: BrainEngine): BrainEngine {
+ const reads = new Map<string, Promise<unknown>>();
+ const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
+ let value = reads.get(id) as Promise<T> | undefined;
+ if (!value) { value = read(); reads.set(id, value); value.catch(() => reads.delete(id)); }
+ return value;
+ };
+ return new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>
+ BATCH_SHARED_READS.has(flatSql(sql)) ? once(JSON.stringify([flatSql(sql), params ?? null]), () => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);
+ if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+/**
+ * #6007: prepares one batch's page admissions under one writer verification
+ * and one read snapshot. `run` gets the caller's context (for a page that may
+ * claim the source's worktree) and a context whose engine answers the batch's
+ * shared pre-admission reads once; the local writer is verified once for the
+ * whole call instead of once per page.
+ */
+export async function withBatchAdmission<T>(ctx: OperationContext, run: (own: OperationContext, shared: OperationContext) => Promise<T>): Promise<T> {
+ const shared: OperationContext = { ...ctx, engine: batchSharedReads(ctx.engine) };
+ if (ctx.auth || currentVerifiedLocalWriter()) return run(ctx, shared);
+ await initializeLocalPersistence(ctx);
+ const registration = await readLocalWriter(ctx.engine, ctx.remote === false ? 'cli' : 'stdio');
+ return withVerifiedLocalRegistration(ctx.engine, registration, () => run(ctx, shared));
+}
/** Validate explicit routing before any admission, including dry-run adapters. */
export function pageMutationSource(ctx: OperationContext, params: Record<string, unknown>, operation: string): string {
const sourceId = parseSourceIdParam(params.source_id, operation) ?? ctx.sourceId ?? 'default';
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 3cdda8e792..6cc61f1d79 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -394,7 +394,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file), validate: ready.validate, apply: async tx => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
if (!noop) {
- await ready.apply(tx);
+ const applied = await ready.apply(tx);
// Mandatory metadata shares publication rollback; exact no-ops never heal it.
if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1
WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]);
@@ -412,11 +412,13 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
for (const tag of snapshot!.tags) if (!versionTags.includes(tag)) await tx.removeTag(row.slug, tag, source);
for (const tag of versionTags) await tx.addTag(row.slug, tag, source);
}
- await project?.(tx);
+ // #6007: the page the import just wrote live is the page the projections describe; no re-read.
+ await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.livePageId);
autoLinks = await links?.apply(tx);
if (targetDeleted) await tx.softDeletePage(row.slug, source);
- // Index installation and terminal receipt share this transaction.
- await sealPageTextProjection(tx, row.slug, row.source_id);
+ // Index installation and terminal receipt share this transaction. The import sealed the projection
+ // as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.
+ if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);
}
return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}),
status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',
diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.ts
index 1f915f58bb..4b67329466 100644
--- a/src/core/persistence/prepared-import.ts
+++ b/src/core/persistence/prepared-import.ts
@@ -1,6 +1,14 @@
import type { BrainEngine } from '../engine.ts';
import type { ImportResult, ParsedPage } from '../import-file.ts';
+/**
+ * #6007: what an apply reports to its caller. `livePageId` is the page it
+ * wrote, when the write left it live; `sealed` means sealing its text
+ * projection was its last step that can change the page's revision, title or
+ * timeline.
+ */
+export interface PreparedImportApplied { livePageId?: number; sealed: boolean }
+
/** Parsing/provider work is complete. apply must run under the coordinator's transaction. */
export interface PreparedContentImport {
slug: string;
@@ -9,5 +17,5 @@ export interface PreparedContentImport {
noop: boolean;
result: ImportResult;
validate(tx: BrainEngine): Promise<void>;
- apply(tx: BrainEngine): Promise<void>;
+ apply(tx: BrainEngine): Promise<PreparedImportApplied | void>;
}
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 6ba2644042..7ae6891c6e 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -238,15 +238,12 @@ export async function waitForWrite(engine: BrainEngine, row: WriteRequest, confi
return (await awaitWrite(engine, row, config, { waitMs })).row;
}
/**
- * #6007: wait for several admitted writes against one deadline. Requests of
- * one source publish oldest first, so waiting on each in order costs one
- * waiter at a time; rows not reached by the deadline keep their last state.
+ * #6007: wait for several admitted writes against one deadline. Every row waits at once, so each one's consumer handoff is registered
+ * before a grouped publication settles them together; waiting one after
+ * another left all but the first to the progress polls.
*/
export async function waitForWrites(engine: BrainEngine, rows: readonly WriteRequest[], config: GBrainConfig, waitMs = 5000): Promise<WriteRequest[]> {
- const deadline = performance.now() + waitMs;
- const settled: WriteRequest[] = [];
- for (const row of rows) settled.push(await waitForWrite(engine, row, config, Math.max(0, deadline - performance.now())));
- return settled;
+ return Promise.all(rows.map(row => waitForWrite(engine, row, config, waitMs)));
}
/** B4: what a terminal receipt means for the caller, without guessing a mutation. */
function terminalReceiptHint(row: WriteRequest, reason: string): string {
diff --git a/test/e2e/persistence-statement-budget.test.ts b/test/e2e/persistence-statement-budget.test.ts
index 540f86b28f..1b653d48ab 100644
--- a/test/e2e/persistence-statement-budget.test.ts
+++ b/test/e2e/persistence-statement-budget.test.ts
@@ -34,11 +34,11 @@ const CRITICAL: Phase[] = ['admission', 'claim', 'prepare', 'recovery_record', '
/**
* Per-phase statement budgets, about 10% above the measured counts (#6007
* measured admission 25, claim 9, prepare 19, recovery record 6, publication
- * 54, completion 6: 119 on the critical path, and an 8-statement receipt; the
+ * 45, completion 6: 110 on the critical path, and an 8-statement receipt; the
* code before #6007 measured 29, 9, 21, 9, 61, 10: 139, and 10).
*/
const BUDGET: Record<string, number> = {
- admission: 28, claim: 10, prepare: 21, recovery_record: 7, publication: 60, completion: 7, critical_path: 131, receipt: 9,
+ admission: 28, claim: 10, prepare: 21, recovery_record: 7, publication: 50, completion: 7, critical_path: 121, receipt: 9,
};
const SCAN = [