Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): an entry frozen for a waiver run is screened against its freeze's read (#5984 G3)

garrytand51966e30fcf
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index b780c15c7c..eb872ca543 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, PageSnapshot } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { loadConfig } from '../config.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -318,6 +318,15 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M
}
return diagnostic;
}
+/**
+ * #5984 G3: the page snapshot each frozen entry was validated against, read right before its sync authority check;
+ * a waiver run's screen of that entry uses it instead of reading the page and the authority again.
+ */
+const frozenSnapshots = new WeakMap<Pending, PageSnapshot | null>();
+function remember(snapshot: PageSnapshot | null | undefined, pending: Pending): Pending {
+ if (snapshot !== undefined) frozenSnapshots.set(pending, snapshot);
+ return pending;
+}
async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,
run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal }): Promise<Pending | Held> {
assertActive();
@@ -326,6 +335,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
let slug = '__managed_sync_checkpoint__', pageId: number | null = null, revision: string | null = null;
let content: string | null = null, rawHash: string | null = null;
let lineEndingOnly = false, occupantRebound = false;
+ let frozenSnapshot: PageSnapshot | null | undefined;
// #5988: company-profile sources never hold; their approved manifest keeps refusing.
const screening = entry?.action === 'import' && !cursor.companyPlan ? run.screen ?? null : null;
let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined;
@@ -363,6 +373,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
slug = entry.slug!; pageId = occupant?.page.id ?? entry.pageId ?? null; revision = occupant ? occupant.revision : entry.revision ?? null;
const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ frozenSnapshot = snapshot;
assertActive();
if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {
throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,
@@ -394,7 +405,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
}
await validateSyncAuthority(engine, cursor.authority, slug);
assertActive();
- return { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',
+ return remember(frozenSnapshot, { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',
expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,
...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),
...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),
@@ -408,7 +419,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: key, runId: cursor.runId,
slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry?.working ?? false,
...(cursor.companyPlan ? { companyApproval: { schema: cursor.companyPlan.schema!, planDigest: cursor.companyPlan.plan_digest, extractorVersion: cursor.companyPlan.extractor_version,
- policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } };
+ policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } });
}
/** A resume adopts the cursor's stored processing options unless the caller set a conflicting one explicitly. */
@@ -757,7 +768,8 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:
const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);
const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));
const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound
- ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config, frozenRun.signal).catch(() => null) : null));
+ ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config, frozenRun.signal,
+ frozenSnapshots.has(entry as Pending) ? { snapshot: frozenSnapshots.get(entry as Pending)! } : undefined).catch(() => null) : null));
for (const [i, waived] of screened.entries()) {
if (!waived) break extend;
run.push({ pending: frozen[i] as Pending, waived });
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index edc18ed0a9..86872d10b9 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -6,7 +6,7 @@
* unfinished request names the page, so a waiver never overtakes queued work.
*/
import { join } from 'node:path';
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, PageSnapshot } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
import { startClaimPhase } from './claim-phase.ts';
@@ -126,20 +126,25 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine
* unadmitted entry's publication would change nothing (a delete of a page
* already soft-deleted at its frozen revision, or an unchanged import). A
* revoked sync authority throws.
+ * #5984 G3: `frozen` is what the freeze of this entry just read and validated
+ * (its page snapshot, then the sync authority); the screen of an entry frozen
+ * for a waiver run uses it instead of reading both again. The run's waiver
+ * transaction re-validates every entry under its locks either way.
*/
-export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<NoopWaiver | null> {
+export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal,
+ frozen?: { snapshot: PageSnapshot | null }): Promise<NoopWaiver | null> {
if (!noopWaiversEnabled() || pending.pageId === null) return null;
const intent = pending.intent;
if (intent.kind === 'managed_sync_delete') {
if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;
- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ const snapshot = frozen ? frozen.snapshot : await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
if (!softDeletedAt(snapshot, pending)) return null;
- await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ if (!frozen) await validateSyncAuthority(engine, cursor.authority, pending.slug);
return { kind: 'delete', kernel: [] };
}
- const kernel = await unchangedSyncImport(engine, cursor, pending, config, signal);
+ const kernel = await unchangedSyncImport(engine, cursor, pending, config, signal, frozen?.snapshot);
if (!kernel) return null;
- await validateSyncAuthority(engine, cursor.authority, pending.slug);
+ if (!frozen) await validateSyncAuthority(engine, cursor.authority, pending.slug);
return { kind: 'import', kernel };
}
@@ -228,11 +233,12 @@ function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapsho
* #6278: the preparation races the sync budget (`raceSyncBudget`); past it
* nothing is waived, and a cancelled run propagates.
*/
-export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<NoopKernelWaiver[] | null> {
+export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal,
+ frozenSnapshot?: PageSnapshot | null): Promise<NoopKernelWaiver[] | null> {
const intent = pending.intent;
if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;
try {
- const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
+ const snapshot = frozenSnapshot !== undefined ? frozenSnapshot : await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });
const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,
worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });
// #6278 (1.4): the clock carries the budget, so the preparation's lock-prone reads end on the server at it (boundedReads).
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index ac2ce6af25..3bfc81137f 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -670,12 +670,15 @@ const runRequests = (engine: BrainEngine, sourceId: string, runId: string) => en
"SELECT intent->>'kind' AS kind,slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'runId'=$2 ORDER BY sequence", [sourceId, runId]);
const deleteRequests = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ slug: string; state: string }>(
"SELECT slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete' ORDER BY sequence", [sourceId]);
-/** Runs `hook` when the screen re-reads `slug` (the second snapshot read: the first is the freeze). */
-function onScreen(engine: BrainEngine, slug: string, hook: () => Promise<void>): BrainEngine {
+/**
+ * Runs `hook` on the `nth` snapshot read of `slug`. The default (2) is a head entry's screen, which re-reads the
+ * page after its freeze; an entry frozen for a waiver run is read once (#5984 G3: its screen reuses the freeze's read).
+ */
+function onScreen(engine: BrainEngine, slug: string, hook: () => Promise<void>, nth = 2): BrainEngine {
let reads = 0;
return new Proxy(engine, { get(target, key) {
if (key === 'readPageSnapshot') return async (read: string, opts: Parameters<BrainEngine['readPageSnapshot']>[1]) => {
- if (read === slug && ++reads === 2) await hook();
+ if (read === slug && ++reads === nth) await hook();
return target.readPageSnapshot(read, opts);
};
const value = Reflect.get(target, key);
@@ -825,7 +828,8 @@ test('a run of no-op deletes is waived in one transaction, and GBRAIN_SYNC_WAIVE
test('a page restored in the middle of a waiver run ends the run there: earlier entries are waived, it is admitted, and nothing after it is passed', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const engine of engines) {
const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));
- const proxy = onScreen(engine, 'n06', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('n02', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)));
+ // n06 is frozen (and screened) after n02 was screened and before the run's waiver transaction.
+ const proxy = onScreen(engine, 'n06', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('n02', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)), 1);
try {
const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
expect(result.waived).toEqual({ imports: 0, deletes: 2 });
@@ -837,6 +841,28 @@ test('a page restored in the middle of a waiver run ends the run there: earlier
}
}), 120_000);
+test('an entry frozen for a waiver run is read once: its screen reuses the freeze\'s page read and authority check (#5984 G3)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));
+ const reads = new Map<string, number>();
+ const counted = new Proxy(engine, { get(target, key) {
+ if (key === 'readPageSnapshot') return (read: string, opts: Parameters<BrainEngine['readPageSnapshot']>[1]) => {
+ reads.set(read, (reads.get(read) ?? 0) + 1);
+ return target.readPageSnapshot(read, opts);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ try {
+ const result = await performManagedSync(counted, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 8 } });
+ const slugs = manySlugs(8);
+ expect(reads.get(slugs[0]!)).toBe(2);
+ expect(slugs.slice(1).map(slug => reads.get(slug))).toEqual(slugs.slice(1).map(() => 1));
+ } finally { await disposePersistenceConsumer(counted); }
+ }
+}), 120_000);
+
test('a crash inside a waiver run skips nothing and waives nothing twice; a lock timeout falls back to one entry at a time', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
for (const fault of ['crash', 'lock_timeout'] as const) {