Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: managed import no-op screen answers batch-shared reads once

time-attack0e55ed7fa4cf
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index 8139fdd33d..cc9e58a48e 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -8,7 +8,7 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';
+import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';
import { admitBatch } from './page-batch.ts';
import { writeOutcomeUnknown } from './admission-retry.ts';
import { assertPersistenceAccepting, waitForWrites } from './service.ts';
@@ -144,6 +144,9 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
const settle = (member: (typeof members)[number], value: ImportResult) => { open.delete(member); done(member.i, value); };
const refuse = (member: (typeof members)[number], reason: unknown) => { open.delete(member); fail(member.i, reason); };
const batch = randomUUID();
+ // The no-op screen only decides whether a file is skipped; a file it does not
+ // skip is admitted and rechecked under lock, so the batch answers its shared reads once.
+ const screening: OperationContext = { ...ctx, engine: batchSharedReads(engine, SCREENING_SHARED_READS) };
try {
const pending = await readPending(members.map(member => member.key));
const fresh: typeof members = [];
@@ -157,7 +160,7 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),
noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };
// #5470: an import whose publication would change nothing takes no admission.
- if (await unchangedManagedImport(ctx, binding, intent, snapshot)) { settle(member, { slug: member.slug, status: 'skipped', chunks: 0 }); continue; }
+ if (await unchangedManagedImport(screening, binding, intent, snapshot)) { settle(member, { slug: member.slug, status: 'skipped', chunks: 0 }); continue; }
member.params = { ...intent, ...(members.length > 1 ? { import_batch: batch } : {}), request_id: randomUUID(), source_id: sourceId };
fresh.push(member);
} catch (error) { refuse(member, error); }
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index ad92b4a482..f5ed95fd8b 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -69,7 +69,17 @@ const BATCH_SHARED_READS = new Set([
"SELECT id FROM source_ingestion_receipts WHERE source_id=$1 AND source_incarnation=$2::uuid AND profile='company-brain' LIMIT 1",
'SELECT s.id,s.local_path,h.local_path AS worktree_path,b.relative_path FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid WHERE NOT s.archived',
]);
-export function batchSharedReads(engine: BrainEngine): BrainEngine {
+/**
+ * A managed import's no-op screen (import-mutations.ts) only decides that a
+ * file is skipped; a file it does not skip is admitted and rechecked under
+ * lock. It also answers the local writer's credential check and the shared
+ * skill pack roots once per batch.
+ */
+export const SCREENING_SHARED_READS: ReadonlySet<string> = new Set([
+ 'SELECT lane,credential_hash,grant_ceiling,revoked_at FROM persistence_local_writers WHERE id=$1::uuid',
+ 'SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid',
+]);
+export function batchSharedReads(engine: BrainEngine, extra?: ReadonlySet<string>): 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;
@@ -78,8 +88,9 @@ export function batchSharedReads(engine: BrainEngine): BrainEngine {
};
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);
+ BATCH_SHARED_READS.has(flatSql(sql)) || extra?.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));
+ if (key === 'getAllConfig' && extra) return () => once('config:*', () => target.getAllConfig()).then(all => ({ ...all }));
const value = Reflect.get(target, key, target);
return typeof value === 'function' ? value.bind(target) : value;
} });
diff --git a/test/persistence-import-batch.test.ts b/test/persistence-import-batch.test.ts
index f5ed539401..435c5daf88 100644
--- a/test/persistence-import-batch.test.ts
+++ b/test/persistence-import-batch.test.ts
@@ -273,3 +273,26 @@ test('a batch admission whose COMMIT acknowledgment is lost replays its admitted
expect(await recorded('always')).toEqual(admitted);
}
}), 300_000);
+
+test('an unchanged re-import screens its files with one read of each batch-shared value', async () => withEnv(env, async () => {
+ for (const [, brain] of pairs) {
+ const sourceId = `screen-${randomUUID().slice(0, 8)}`;
+ const root = await managedSource(brain.engine, sourceId, brain.label);
+ const files = write(root, Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`notes/screen-${i}.md`, page(`Screen ${i}`)])));
+ expect((await importManagedFiles(brain.engine, files, { sourceId, noEmbed: true })).every(r => r.status === 'fulfilled' && r.value.status === 'imported')).toBe(true);
+ const counted = new Map<string, number>();
+ const original = brain.engine.executeRaw;
+ brain.engine.executeRaw = async function(this: BrainEngine, sql, params, opts) {
+ const flat = sql.replace(/\s+/g, ' ').trim();
+ for (const key of ['FROM persistence_local_writers', 'FROM shared_skill_packs', "profile='company-brain'", 'FROM sources s LEFT JOIN persistence_source_bindings'])
+ if (flat.includes(key)) counted.set(key, (counted.get(key) ?? 0) + 1);
+ return original.call(this, sql, params, opts);
+ } as BrainEngine['executeRaw'];
+ let again: PromiseSettledResult<unknown>[];
+ try { again = await importManagedFiles(brain.engine, files, { sourceId, noEmbed: true }); } finally { brain.engine.executeRaw = original; }
+ expect(again.map(r => r.status === 'fulfilled' && (r.value as { status: string }).status)).toEqual(files.map(() => 'skipped'));
+ // A per-file screen would read each of these at least once per file (12 here).
+ for (const key of counted.keys()) expect({ key, perBatch: counted.get(key)! <= 4 }).toEqual({ key, perBatch: true });
+ expect(counted.size).toBe(4);
+ }
+}), 300_000);