Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(persistence): bulk groups share one coordinated write (per-member attribution), protocol declaration and skillpack roots per transaction (#5984)
garrytan124154f679b0
diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.tsindex 1a3b6d4a8b..e866f333c7 100644--- a/src/core/persistence/context.ts+++ b/src/core/persistence/context.ts@@ -48,6 +48,15 @@ export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: stfinally { context.active = false; }}));}+/**+ * #5984 bulk: inside one coordinated write that publishes several requests,+ * names the next request as the actor of the rows it writes. One statement; the+ * enclosing coordinated write restores the outer values when it ends.+ */+export async function setMemberAttribution(engine: Pick<BrainEngine, 'executeRaw'>, attribution: WriteAttribution): Promise<void> {+ await engine.executeRaw(`SELECT ${ATTRIBUTION_SETTINGS.map((name, index) => `set_config('${name}',$${index + 1},true)`).join(',')}`,+ [attribution.requestId ?? '', attribution.principal.kind, attribution.principal.id]);+}/** Attribution without coordinator capability, for unmanaged legacy transactions. */export function withWriteAttribution<T>(engine: Pick<BrainEngine, 'executeRaw'>, attribution: WriteAttribution, fn: () => Promise<T>): Promise<T> {return withTransactionSettings(engine, ATTRIBUTION_SETTINGS, outer => attributionValues(outer, attribution), fn);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 34b58ec1cd..51ddd21600 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -23,11 +23,10 @@ import { localHostId } from './identity.ts';import { acquireWorktree, getWorktreeBinding, guardOwnership } from './ownership.ts';import { completeWrite, getWriteRequestById, lockCounters, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';-import { withCoordinatedWrite } from './context.ts';+import { setMemberAttribution, withCoordinatedWrite } from './context.ts';import { requestAttribution } from './attribution.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';import { queuePublicationEffects } from './effect-journal.ts';-import { authorizePageVisibility } from './page-visibility.ts';import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';import { declarePersistenceProtocol } from './protocol.ts';import { classifyMirrorPage } from './mirror-read-only.ts';@@ -59,25 +58,28 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prawait tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const live = await guardOwnership(tx, head, hostId);if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.');- for (const row of rows) await authorizeStoredRequest(tx, row, true);await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));const outcomes: Record<string, unknown>[] = [];- for (let i = 0; i < rows.length; i++) {- const row = rows[i]!, member = prepared[i]!;- const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- await authorizePageVisibility(tx, row.authority, row.slug);- if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.');- await assertUnboundPublication(tx, row, snapshot?.page.source_path);- if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.');- await member.validate?.(tx);- const outcome = await withCoordinatedWrite(tx, [row.source_id], () => member.apply(tx), requestAttribution(row));- await classifyUnboundPage(tx, row);- if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);- const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- decoratePublicationOutcome(row, member, outcome, final, 0, false);- await queuePublicationEffects(tx, row, final, outcome, member);- outcomes.push(outcome);- }+ // One coordinated write for the group; each member is the attributed actor of what it writes.+ await withCoordinatedWrite(tx, [head.source_id], async () => {+ for (let i = 0; i < rows.length; i++) {+ const row = rows[i]!, member = prepared[i]!;+ await authorizeStoredRequest(tx, row, true);+ const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.');+ await assertUnboundPublication(tx, row, snapshot?.page.source_path);+ if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.');+ await member.validate?.(tx);+ await setMemberAttribution(tx, requestAttribution(row));+ const outcome = await member.apply(tx);+ await classifyUnboundPage(tx, row);+ if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);+ const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ decoratePublicationOutcome(row, member, outcome, final, 0, false);+ await queuePublicationEffects(tx, row, final, outcome, member);+ outcomes.push(outcome);+ }+ }, requestAttribution(head));await lockCounters(tx, ['brain', ...new Set(rows.map(row => principalKey(requestPrincipal(row)))), `worktree:${head.worktree_id}`]);const current = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence FOR UPDATE', [rows.map(row => row.id)]);const byId = new Map(current.map(row => [row.id, row]));diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.tsindex 69443aeae6..d1d0e9a6bb 100644--- a/src/core/persistence/protocol.ts+++ b/src/core/persistence/protocol.ts@@ -1,8 +1,13 @@import type { SqlEngine, WriteRequest } from './model.ts';import { OperationError } from '../ops/contract.ts';+const declared = new WeakSet<object>();+/** Transaction-local; #5984: a transaction engine declares it once (a savepoint is its own engine object). */export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {+ const inTransaction = (tx as { _pageTransaction?: boolean })._pageTransaction === true;+ if (inTransaction && declared.has(tx)) return;await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ if (inTransaction) declared.add(tx);}export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.tsindex d861d0a469..543b8dcc8f 100644--- a/src/core/shared-skills/knowledge-guard.ts+++ b/src/core/shared-skills/knowledge-guard.ts@@ -27,19 +27,34 @@ function reject(): never {'Use put_skill with the catalog expected_revision and complete approved file bundle; an existing pack requires host-authorized adoptSharedSkillpack adoption. Imported skill text remains knowledge data, not published instructions.');}+const packsInTransaction = new WeakMap<object, Promise<PackRoot[]>>();+/** The shared skillpack roots; #5984: read once per transaction engine. */+function sharedPacks(engine: SqlEngine): Promise<PackRoot[]> {+ const read = async () => {+ const [schema] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present");+ if (!schema?.present) return [];+ return engine.executeRaw<PackRoot>(`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`, [localHostId()]);+ };+ if ((engine as { _pageTransaction?: boolean })._pageTransaction !== true) return read();+ let cached = packsInTransaction.get(engine);+ if (!cached) { cached = read(); packsInTransaction.set(engine, cached); }+ return cached;+}++/** A transaction that changes shared_skill_packs re-reads them for its later knowledge writes. */+export function forgetSharedPacks(engine: SqlEngine): void { packsInTransaction.delete(engine); }+export async function assertKnowledgePublicationAllowed(engine: SqlEngine,row: KnowledgePublicationTarget,preparedFile?: KnowledgePublicationFile,): Promise<void> {if (row.target_kind === 'skill_bundle') return;- const [schema] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present");- if (!schema?.present) return;- const packs = await engine.executeRaw<PackRoot>(`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`, [localHostId()]);+ const packs = await sharedPacks(engine);if (!packs.length) return;const ownPack = packs.find(pack => pack.source_id === row.source_id && pack.source_incarnation === row.source_incarnation);if (ownPack && reserved(row.slug)) reject();diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.tsindex 2563fb0ba8..d85f849caa 100644--- a/src/core/shared-skills/publication.ts+++ b/src/core/shared-skills/publication.ts@@ -18,6 +18,7 @@ import { localHostId } from '../persistence/identity.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { requestAttribution } from '../persistence/attribution.ts';import { normalizeSkillFiles, skillMetadata, skillName, skillPath } from './manifest.ts';+import { forgetSharedPacks } from './knowledge-guard.ts';import { assertSkillCapability, assertStoredSkillCapability, publicationEnabled, readSharedSkillPolicy, setSharedSkillPolicy } from './policy.ts';import { SHARED_SKILL_LIMITS, type SharedSkillFile, type SharedSkillPolicy, type SharedSkillPutInput, type SkillMetadata, type StoredSkillFile, type StoredSkillRevision } from './model.ts';import { assertSharedSkillRetentionCapacity, pruneSharedSkillRevisionsInTransaction, sharedSkillRetentionCapacity, sharedSkillRetentionStatus } from './retention.ts';@@ -385,6 +386,7 @@ export async function prepareSharedSkillMutation(engine: BrainEngine, row: WriteVALUES($1,$2::uuid,$3,$4::uuid,$5::text::jsonb,$6) ON CONFLICT(source_id,source_incarnation)DO UPDATE SET revision=excluded.revision,manifest=excluded.manifest,manifest_hash=excluded.manifest_hash`,[row.source_id, row.source_incarnation, intent.pack_id, packRevision, JSON.stringify(manifest), sha256(manifestContent)]);+ forgetSharedPacks(tx);const primary = revisions.find(r => r.name === intent.name)!;const retained = !row.authority.remote ? await sharedSkillRetentionStatus(tx, row.source_id, row.source_incarnation) : undefined;return { status: primary.deleted ? 'deleted' : 'published', source_id: row.source_id, source_incarnation: row.source_incarnation,diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.tsindex 1ba050a118..db3893f86b 100644--- a/test/managed-sync-bulk.test.ts+++ b/test/managed-sync-bulk.test.ts@@ -75,6 +75,11 @@ test('a bulk drain publishes groups in one transaction while every page keeps itfor (const row of rows) sharedTransaction.set(row.published, (sharedTransaction.get(row.published) ?? 0) + 1);expect(Math.max(...sharedTransaction.values())).toBeGreaterThan(1);for (let i = 0; i < 14; i++) expect((await engine.getPage(`notes/n${i}`, { sourceId: f.id }))?.title).toBe(`Note ${i}`);+ // Every page revision is attributed to its own request, also inside a shared group transaction.+ const attributed = await engine.executeRaw<{ slug: string; mismatched: boolean }>(`SELECT p.slug, p.revision_write_request_id IS DISTINCT FROM r.id AS mismatched+ FROM pages p JOIN persistence_requests r ON r.source_id=p.source_id AND r.slug=p.slug AND r.intent->>'kind'='managed_sync_import' WHERE p.source_id=$1`, [f.id]);+ expect(attributed).toHaveLength(14);+ expect(attributed.filter(row => row.mismatched)).toEqual([]);const [cursor] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0 ? 'group'");expect(cursor!.n).toBe(0);}), 300_000);