Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(#6712 PR 4b): the legacy sweep answers its pass-invariant owner checks once per slice

garrytan8eac3ec80c51
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index f13226f9fc..be933e4089 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -36,6 +36,7 @@ import { fenceIssuesWire, fenceStep, type FenceIssueWire } from './fence-repair/
import type { FenceCtx, FenceFix, FencePage, FenceReason } from './fence-repair/types.ts';
import { effectiveVisibility } from './search/private-visibility.ts';
import { CODE_FILE_MAX_BYTES, PAGE_MAX_BYTES } from './page-size-policy.ts';
+import { sliceMemo } from './persistence/slice-memo.ts';
/** Largest Markdown page import admits: the Wave A ceiling (page-size-policy.ts). */
export const MAX_FILE_SIZE = PAGE_MAX_BYTES;
@@ -63,7 +64,11 @@ export interface ImportSanityConfig {
* write-gate keys ride the same lift; an unreadable value falls back to the
* defaults (flag for both), never to `off`.
*/
-export async function loadImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
+export function loadImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
+ return sliceMemo(engine, 'import-sanity', () => readImportSanityConfig(engine));
+}
+
+async function readImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
const baseCfg = loadConfig();
let effectiveCfg = baseCfg;
// One whole-table read answers the DB config lift and the write-gate keys (#6007 statement budget).
diff --git a/src/core/persistence/import-reads.ts b/src/core/persistence/import-reads.ts
index 93e4c3dba7..80905d6ce6 100644
--- a/src/core/persistence/import-reads.ts
+++ b/src/core/persistence/import-reads.ts
@@ -21,6 +21,7 @@ import { pageSnapshotKey } from '../page-snapshot-batch.ts';
import { SAFE_FENCE_SQL } from '../page-state/projections.ts';
import { STORED_TIMELINE_SQL, TAKE_COLLISIONS_SQL } from './canonical-projections.ts';
import { SYNC_ORIGIN_PAGES_SQL } from './sync-origin.ts';
+import { registerSliceView } from './slice-memo.ts';
type DuplicateInput = { hash: string; frontmatterId?: string | null; excludeSlug?: string };
type Duplicate = { slug: string; id: number } | null;
@@ -144,7 +145,7 @@ export function sliceReads(engine: BrainEngine, slice: { sourceId: string; pageI
return once(kind, async () => byKey(await engine.executeRaw<Record<string, unknown>>('SELECT DISTINCT page_id FROM takes WHERE page_id=ANY($1::bigint[])', [pageIds]), 'page_id'))
.then(rows => rows.has(id) ? engine.executeRaw(sql, params) : []);
};
- return new Proxy(engine, { get(target, key) {
+ return registerSliceView(new Proxy(engine, { get(target, key) {
if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {
const kind = flat(sql);
const answered = !opts?.signal && params && [ORIGIN, TIMELINE, TAKES, FENCE].includes(kind) ? answer(kind, sql, params) : undefined;
@@ -152,5 +153,5 @@ export function sliceReads(engine: BrainEngine, slice: { sourceId: string; pageI
};
const value = Reflect.get(target, key, target);
return typeof value === 'function' ? value.bind(target) : value;
- } });
+ } }));
}
diff --git a/src/core/persistence/slice-memo.ts b/src/core/persistence/slice-memo.ts
new file mode 100644
index 0000000000..42cd9e5ab2
--- /dev/null
+++ b/src/core/persistence/slice-memo.ts
@@ -0,0 +1,23 @@
+/**
+ * GBRA-108: the legacy sweep screens a slice of pages through one reads view (`sliceReads`, import-reads.ts). The checks
+ * every preparation of the slice repeats with the same inputs (the owner binding, the configured root, the content-sanity
+ * config lift) are answered once per view. Any other engine is not a slice view, so its callers read every time.
+ */
+const slices = new WeakMap<object, Map<string, Promise<unknown>>>();
+
+export function registerSliceView<T extends object>(view: T): T {
+ slices.set(view, new Map());
+ return view;
+}
+
+export function sliceMemo<T>(view: object, key: string, read: () => Promise<T>): Promise<T> {
+ const memo = slices.get(view);
+ if (!memo) return read();
+ const hit = memo.get(key) as Promise<T> | undefined;
+ if (hit) return hit;
+ const value = read();
+ memo.set(key, value);
+ // A failed check is not shared: the next preparation of the slice runs it again.
+ value.catch(() => memo.delete(key));
+ return value;
+}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 3fb3e8a0b6..1c8917dbd6 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -1,5 +1,5 @@
import { execFile, execFileSync } from 'node:child_process';
-import { lstatSync, readFileSync, realpathSync } from 'node:fs';
+import { lstatSync, readFileSync, realpathSync, type Stats } from 'node:fs';
import { join, relative, resolve, sep } from 'node:path';
import { promisify } from 'node:util';
import type { BrainEngine } from '../engine.ts';
@@ -132,14 +132,16 @@ export function syncFilePath(root: string, path: string, maxBytes = SYNC_READ_BO
try {
// Reject symlink components, including ones targeting another path inside the root.
let current = root;
+ let stat: Stats | undefined;
for (const part of relative(root, absolute).split(sep)) {
current = join(current, part);
- if (lstatSync(current).isSymbolicLink()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync cannot publish through a symlink.',
+ stat = lstatSync(current);
+ if (stat.isSymbolicLink()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync cannot publish through a symlink.',
`A component of ${path} is a symlink; sync reads and publishes only real files inside the root.`));
}
- if (!lstatSync(absolute).isFile()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
+ if (!stat?.isFile()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
`${path} is not a regular file.`));
- if (lstatSync(absolute).size > maxBytes) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
+ if (stat.size > maxBytes) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
`${path} is larger than the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling, so nothing was imported from it. Pages up to that size are chunked and searchable; above it, add the file to the sync.exclude config (or keep it outside the brain repo), then sync its source again. See docs/guides/memory-boundaries.md#large-pages.`);
return absolute;
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index c41ab72d4b..d113ad11c1 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -27,6 +27,7 @@ import { prepareManagedSyncStreamed, type SyncBodyRef } from './sync-streamed.ts
import { fenceBody, withoutBody } from '../page-body/page-shape.ts';
import { pipelined, transactionMemo } from '../page-state/transactions.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
+import { sliceMemo } from './slice-memo.ts';
import { withoutSafetyAssessments } from './reconcile-safety.ts';
import { digest, sha256 } from './digest.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
@@ -674,13 +675,15 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
enterClaimStep(clock, 'authority', undefined, 'db');
await validateSyncAuthority(engine, p.syncAuthority, row.slug);
enterClaimStep(clock, 'worktree_binding', undefined, 'db');
- const binding = await getWorktreeBinding(engine, row.source_id);
+ const binding = await sliceMemo(unbounded, `binding\0${row.source_id}`, () => getWorktreeBinding(engine, row.source_id));
if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner changed.', row, p,
`The canonical owner of ${row.source_id} changed, or lost its local path, after this sync was admitted. Do not claim or transfer the source to repair content.`, true);
const root = at.root = join(binding.local_path, binding.relative_path);
enterClaimStep(clock, 'configured_root', undefined, 'db');
- const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);
- assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
+ await sliceMemo(unbounded, `configured-root\0${row.source_id}\0${root}`, async () => {
+ const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);
+ assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
+ });
if (p.kind !== 'managed_sync_checkpoint') {
enterClaimStep(clock, 'knowledge_publication', undefined, 'db');
await assertKnowledgePublicationAllowed(engine, row, p.path === null ? undefined : { root, path: join(root, p.path) });
diff --git a/test/slice-memo-gbra108.test.ts b/test/slice-memo-gbra108.test.ts
new file mode 100644
index 0000000000..7107f2bf63
--- /dev/null
+++ b/test/slice-memo-gbra108.test.ts
@@ -0,0 +1,32 @@
+/**
+ * GBRA-108: the legacy sweep's preparations share one reads view per slice (`sliceReads`), and the owner checks and the
+ * content-sanity config lift each run once per view (src/core/persistence/slice-memo.ts).
+ *
+ * Protects:
+ * - a slice view answers a check once for every preparation of the slice; another view (the next slice) runs it again;
+ * - an engine that is not a slice view (a publication, a transaction) runs every check every time;
+ * - a failed check is not shared: the next preparation of the slice runs it again.
+ */
+import { describe, expect, test } from 'bun:test';
+import { registerSliceView, sliceMemo } from '../src/core/persistence/slice-memo.ts';
+
+describe('GBRA-108 slice memo', () => {
+ test('a slice view answers each check once; the next slice and a plain engine read again', async () => {
+ let reads = 0;
+ const read = async () => ++reads;
+ const first = registerSliceView({}), second = registerSliceView({}), plain = {};
+ expect(await Promise.all([sliceMemo(first, 'k', read), sliceMemo(first, 'k', read), sliceMemo(first, 'k', read)])).toEqual([1, 1, 1]);
+ expect(await sliceMemo(first, 'other', read)).toBe(2);
+ expect(await sliceMemo(second, 'k', read)).toBe(3);
+ expect([await sliceMemo(plain, 'k', read), await sliceMemo(plain, 'k', read)]).toEqual([4, 5]);
+ });
+
+ test('a failed check is not shared with the next preparation of the slice', async () => {
+ const view = registerSliceView({});
+ let calls = 0;
+ const read = async () => { calls++; if (calls === 1) throw new Error('transient'); return calls; };
+ await expect(sliceMemo(view, 'k', read)).rejects.toThrow('transient');
+ expect(await sliceMemo(view, 'k', read)).toBe(2);
+ expect(await sliceMemo(view, 'k', read)).toBe(2);
+ });
+});