Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync feeder: pipelined group admission, pass every committed window group in one save, admit window groups in batches (#5984 Phase 1)

garrytand27ddb5e7b56
diff --git a/src/core/page-state/transactions.ts b/src/core/page-state/transactions.ts
index f6672e2ef3..a9fbc3beed 100644
--- a/src/core/page-state/transactions.ts
+++ b/src/core/page-state/transactions.ts
@@ -74,9 +74,9 @@ export function transactionMemo<T>(tx: object, keys: string | readonly string[],
* between them, so postgres.js pipelines those already prepared on the
* transaction's connection (docs/eval/managed-sync-catchup.md, "Pipelining
* spike": order kept, later statements of a failed pipeline fail with 25P02).
- * Each call must send its statement synchronously (`executeRaw`, engine-sql
- * `run`), so call order is send order. The first failure in call order is
- * thrown. PGLite runs the calls one at a time.
+ * A call that awaits between statements sends its later ones after the other
+ * calls' first. The first failure in call order that is not a 25P02 abort is
+ * thrown (the 25P02 itself when that is all there is). PGLite runs the calls one at a time.
*/
export async function pipelined(engine: { kind: string }, calls: ReadonlyArray<() => Promise<unknown>>): Promise<unknown[]> {
if (engine.kind !== 'postgres') {
@@ -85,7 +85,9 @@ export async function pipelined(engine: { kind: string }, calls: ReadonlyArray<(
return results;
}
const settled = await Promise.allSettled(calls.map(call => { try { return call(); } catch (error) { return Promise.reject(error); } }));
- const failed = settled.find(s => s.status === 'rejected') as PromiseRejectedResult | undefined;
+ const rejected = settled.filter((s): s is PromiseRejectedResult => s.status === 'rejected');
+ // A statement sent after the one that failed reports 25P02 (transaction aborted); the cause is the other one.
+ const failed = rejected.find(s => (s.reason as { code?: unknown } | null)?.code !== '25P02') ?? rejected[0];
if (failed) throw failed.reason;
return settled.map(s => (s as PromiseFulfilledResult<unknown>).value);
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 39d235fce3..50bc90700c 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -15,6 +15,7 @@ import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertGraduationAdmission } from './graduation-custody.ts';
+import { pipelined } from '../page-state/transactions.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
type JournalLimits, type Principal, type RecoveryRecord, type RequestState,
@@ -218,27 +219,33 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
|| input.operation !== first.operation || (input.targetKind ?? 'page') !== 'page' || (input.protocolVersion ?? 1) !== 1 || digest(input.authority) !== digest(first.authority))) {
throw new TypeError('A group admission requires one source, worktree, principal, operation and authority.');
}
- const limits = await readJournalLimits(tx, overrides);
const stamp = writerStamp();
const items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),
bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? Math.max(16_384, jsonBytes(input.authority) + 8192) }));
- await declarePersistenceProtocol(tx);
- await assertGraduationAdmission(tx);
assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });
- if (first.worktreeId) await assertWorktreeAdmission(tx, first);
- const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [first.sourceId]);
+ const ids = items.map(item => item.requestId);
+ // #5984: the checks are independent reads and share locks, so they go out back to back in the order they always
+ // had (protocol, graduation, worktree, source, writer, counters); a failure is raised in that order.
+ const [limits, , , , sources, , counters, topology, priorRows] = await pipelined(tx, [
+ () => readJournalLimits(tx, overrides),
+ () => declarePersistenceProtocol(tx),
+ () => assertGraduationAdmission(tx),
+ () => first.worktreeId ? assertWorktreeAdmission(tx, first) : Promise.resolve(),
+ () => tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [first.sourceId]),
+ () => Promise.all(items.map(({ input }) => authorizeWrite(tx, input.authority, input.operation, input.slug, true))),
+ () => lockCounters(tx, ['brain', principalKey(first.principal)]),
+ () => first.principal.kind === 'local_cli'
+ ? tx.executeRaw<{ request_id: string }>('SELECT request_id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=ANY($2::uuid[]) LIMIT 1', [first.principal.id, ids])
+ : Promise.resolve([]),
+ () => tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
+ [first.principal.kind, first.principal.id, ids]),
+ ]) as [JournalLimits, unknown, unknown, unknown, Array<{ incarnation: string; archived: boolean }>, unknown, Counter[], Array<{ request_id: string }>, WriteRequest[]];
+ const [source] = sources;
if (!source || source.archived || source.incarnation !== first.sourceIncarnation) {
throw new OperationError('source_changed', 'The write source is missing, archived, or was replaced.', 'Resolve the source again and submit a new request.');
}
- for (const { input } of items) await authorizeWrite(tx, input.authority, input.operation, input.slug, true);
- const counters = await lockCounters(tx, ['brain', principalKey(first.principal)]);
- const ids = items.map(item => item.requestId);
- if (first.principal.kind === 'local_cli') {
- const [topology] = await tx.executeRaw<{ request_id: string }>('SELECT request_id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=ANY($2::uuid[]) LIMIT 1', [first.principal.id, ids]);
- if (topology) throw lifecycleIdConflict(topology.request_id);
- }
- const priors = new Map((await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
- [first.principal.kind, first.principal.id, ids])).map(row => [row.request_id, row]));
+ if (topology[0]) throw lifecycleIdConflict(topology[0].request_id);
+ const priors = new Map(priorRows.map(row => [row.request_id, row]));
for (const item of items) {
const prior = priors.get(item.requestId);
if (!prior) continue;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 1148365e87..6da6789743 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -665,17 +665,25 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
if (foreground) bulk.foregroundAt = performance.now();
}
if (bulk.foregroundAt !== undefined && performance.now() - bulk.foregroundAt < FOREGROUND_RECENT_MS) break;
- const base: Cursor = { ...current, index: start - 1 };
- // A freeze refusal here is left for the single path to raise in order, after the publishing groups.
- const frozen = await freezeFollowers(engine, base, config, groupSize(base, bulk), freezeAt(base)).catch(() => []);
- if (!frozen.length) break;
- const after = (window.at(-1) ?? current.group!).at(-1)!.requestId;
- const members = frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after, ...(lane ? { lane } : {}) } }));
- // A failed admission ends this pass (the group is frozen again on the next); a lost cursor returns the winner's.
- const saved = await admitAndSave(engine, key, current, { ...current, window: [...window, members] }, members, assertActive).catch(() => undefined);
+ // The window's free slots are frozen and then admitted and saved in one transaction, up to a lane count of
+ // groups at a time, so lanes start on the first ones while the rest are frozen.
+ const formed: Pending[][] = [];
+ let next = start;
+ while (window.length + formed.length < depth && formed.length < Math.max(1, depth / 2) && next < current.entries.length) {
+ const base: Cursor = { ...current, index: next - 1 };
+ // A freeze refusal here is left for the single path to raise in order, after the publishing groups.
+ const frozen = await freezeFollowers(engine, base, config, groupSize(base, bulk), freezeAt(base)).catch(() => []);
+ if (!frozen.length) break;
+ const after = (formed.at(-1) ?? window.at(-1) ?? current.group!).at(-1)!.requestId;
+ formed.push(frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after, ...(lane ? { lane } : {}) } })));
+ next += frozen.length;
+ }
+ if (!formed.length) break;
+ // A failed admission ends this pass (the groups are frozen again on the next); a lost cursor returns the winner's.
+ const saved = await admitAndSave(engine, key, current, { ...current, window: [...window, ...formed] }, formed.flat(), assertActive).catch(() => undefined);
if (saved === undefined) break;
if (saved === null) return currentCursor(engine, key, current);
- (bulk.admitted ??= new Set()).add(members[0]!.requestId);
+ for (const group of formed) (bulk.admitted ??= new Set()).add(group[0]!.requestId);
current = saved;
}
assertActive();
@@ -744,6 +752,21 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
const stuck = members[committed];
const stuckRow = stuck ? states.get(stuck.requestId) : undefined;
const failed = !!stuck && !!stuckRow && isTerminalWriteState(stuckRow.state);
+ if (!stuck && next.window?.length) {
+ next.window = [...next.window];
+ // Window groups that lanes already committed are passed in this same save: the feeder's cost per wait stays
+ // one save however many groups committed meanwhile. It stops at the first group not wholly committed.
+ const ids = next.window.flat().map(member => member.requestId);
+ const done = new Map((await engine.executeRaw<WriteRequest>(`SELECT request_id,state,outcome FROM persistence_requests
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[]) AND state='committed'`, [principal.kind, principal.id, ids])).map(row => [row.request_id, row]));
+ while (next.window.length && next.window[0]!.every(member => done.has(member.requestId))) {
+ const group = next.window.shift()!;
+ for (const member of group) countCommitted(next.counts, member, done.get(member.requestId)!.outcome);
+ onProgress?.({ phase: 'managed_sync.group', bankedFiles: next.index, total: cursor.entries.length, group: group.length });
+ next.index += group.length;
+ }
+ if (next.index !== cursor.index + committed) next.progress = stampProgress(cursor.progress, cursor.index, next.index, drainStartedAt);
+ }
if (!stuck) {
// The window's first group becomes the cursor's group; its requests are already admitted and queued.
const [promoted, ...rest] = next.window ?? [];