Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: review fixes for the drain lease and fan-in (#6712 PR 1)

garrytan0eb356748ae1
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index fe28a1964c..ec54d698aa 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -122,11 +122,13 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
if (err instanceof SyncLockBusyError) {
// #6712 PR 1 (folds #6706's live-job guard): one drainer per source is the drain lease; a job that finds it held completes as a skip.
const id = sourceId ?? 'default';
- const read = await (await import('../../persistence/sync-lease.ts')).readDrainHolder(engine, id).catch(() => null);
+ const { readDrainHolder, publicDrainHolder } = await import('../../persistence/sync-lease.ts');
+ const read = await readDrainHolder(engine, id).catch(() => null);
const holder = read && read.kind !== 'unknown' ? read : null;
const runningJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;
console.error(`[sync] skipped: sync already in progress for ${id} (lock ${err.lockKey} held${holder ? ` by a ${holder.kind} drainer` : ''}).`);
- return { skipped: true, reason: 'sync_in_progress', source_id: id, ...(holder ? { holder } : {}),
+ // A job result is readable by remote callers (get_job), so it carries the public holder: kind and times only.
+ return { skipped: true, reason: 'sync_in_progress', source_id: id, ...(holder ? { holder: publicDrainHolder(holder) } : {}),
...(runningJob !== null ? { running_job_id: runningJob, next: { command: `gbrain jobs get ${runningJob} --json`, safe_to_loop: true, retry_after_ms: 30_000,
why: `Sync job #${runningJob} is draining source ${id}; it resumes the cursor, so nothing else needs to run.` } } : {}) };
}
diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.ts
index f4561a0f9b..1bfe6c5c23 100644
--- a/src/core/persistence/sync-cursor-key.ts
+++ b/src/core/persistence/sync-cursor-key.ts
@@ -68,9 +68,12 @@ export interface CursorResolution {
interface CursorRow { key: string; done: boolean; company_receipt_id: string | null; run_id: string | null }
-/** Picks the cursor a pass uses and folds in the others (module header); `readOnly` (a dry run) only picks. */
+/**
+ * Picks the cursor a pass uses and folds in the others (module header). `readOnly` (a dry run) only picks; `foldIn: false`
+ * (a remote caller) picks and finds what to wait for, but cancels and retires nothing.
+ */
export async function resolveManagedCursor(engine: BrainEngine, input: { sourceId: string; incarnation: string; company: CompanySync; assertActive: () => void;
- readOnly?: boolean }): Promise<CursorResolution> {
+ readOnly?: boolean; foldIn?: boolean }): Promise<CursorResolution> {
const { sourceId, incarnation, company, assertActive } = input;
const canonical = managedCursorKey(incarnation, company);
const rows = (await engine.executeRaw<CursorRow>(`SELECT fingerprint AS key, COALESCE(completed_keys->0->>'done','false')='true' AS done,
@@ -85,7 +88,12 @@ export async function resolveManagedCursor(engine: BrainEngine, input: { sourceI
const fence = (tx: BrainEngine) => assertDrainLease(tx, sourceId);
for (const row of input.readOnly ? [] : rows) {
if (row.key === key || row.key === canonical && row.done) continue;
- if (row.done) {
+ if (input.foldIn === false) {
+ if (row.done) continue;
+ const busy = await busyRequest(engine, input.sourceId, row.key);
+ resolution.retained.push(row.key);
+ if (busy) resolution.waitFor ??= waitOn(busy);
+ } else if (row.done) {
if (company) continue;
await engine.transaction(async tx => {
await fence(tx);
@@ -99,8 +107,9 @@ export async function resolveManagedCursor(engine: BrainEngine, input: { sourceI
await faultPoint('sync:cursor_adopted', { sourceId });
} else {
resolution.retained.push(row.key);
- if (open !== 'kept') resolution.waitFor ??= { request_id: open.request_id, kind: (open.intent as { kind?: string } | null)?.kind ?? null, slug: open.slug,
- state: open.state, recovery: !!open.recovery };
+ // `kept`: a consumer claimed a request between the read and the retirement; wait for whatever is open now.
+ const busy = open === 'kept' ? await busyRequest(engine, input.sourceId, row.key) : open;
+ if (busy) resolution.waitFor ??= waitOn(busy);
}
}
assertActive();
@@ -108,6 +117,16 @@ export async function resolveManagedCursor(engine: BrainEngine, input: { sourceI
return resolution;
}
+const waitOn = (request: WriteRequest): NonNullable<CursorResolution['waitFor']> => ({ request_id: request.request_id,
+ kind: (request.intent as { kind?: string } | null)?.kind ?? null, slug: request.slug, state: request.state, recovery: !!request.recovery });
+
+/** The first request under a cursor key that is not merely queued: running, recovering, publishing or carrying recovery. */
+async function busyRequest(engine: BrainEngine, sourceId: string, key: string): Promise<WriteRequest | null> {
+ const open = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'cursorKey'=$2
+ AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence`, [sourceId, key]);
+ return open.find(request => request.state !== 'queued' || request.recovery || request.publication_started) ?? null;
+}
+
/**
* Cancels the queued requests of a passed-over cursor, then retires it (null). While a request under it is running,
* recovering or publishing, nothing is touched and that request is returned; `kept` when the retirement found it no
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 0202eb24a1..54e8279a73 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -64,7 +64,7 @@ export interface DrainHolder { kind: DrainHolderKind | 'unknown'; id: string | n
version: string | null; progress: DrainHolderProgress | null }
/** `safe_to_loop` and `retry_after_ms` are the `next` fields of the drain's other owner stops (`owner_wedged_here`). */
export interface DrainLeaseHeld { code: typeof SYNC_DRAIN_LEASE_HELD; holder: DrainHolder | null; retry_after_ms: number; safe_to_loop: true; lost?: true; fix: Action }
-interface DrainLease { lockId: string; sourceId: string; token: string }
+interface DrainLease { lockId: string; sourceId: string; token: string; signal: AbortSignal }
const leases = new AsyncLocalStorage<ReadonlyMap<string, DrainLease>>();
@@ -80,7 +80,9 @@ export function currentDrainLease(sourceId: string): DrainLease | null {
export async function assertDrainLease(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<void> {
const lease = currentDrainLease(sourceId);
if (!lease) return;
- const rows = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid FOR SHARE', [lease.lockId, lease.token]);
+ // A renewal that failed aborts the lease's signal before its row is released; an expired row is lost even untaken.
+ if (lease.signal.aborted) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} lapsed in this pass`);
+ const rows = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [lease.lockId, lease.token]);
if (!rows.length) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} is no longer held by this pass`);
}
@@ -121,7 +123,8 @@ export function holderStalled(holder: DrainHolder | null, now = Date.now()): boo
}
/** What a remote caller may see of a holder: its kind and times, never its host, pid or job id. */
-const redacted = (holder: DrainHolder | null): DrainHolder | null => holder && { ...holder, id: null, host: null, pid: null };
+export const publicDrainHolder = (holder: DrainHolder | null): DrainHolder | null => holder && { ...holder, id: null, host: null, pid: null };
+const redacted = publicDrainHolder;
/** The `resumable` result of a run that did not get (or lost) the lease. Nothing was admitted by it; the cursor stands. */
export function leaseHeldResult(sourceId: string, holder: DrainHolder | null, opts: { lost?: boolean; remote?: boolean; resumeArgv?: string[] } = {}): SyncResult {
@@ -214,7 +217,7 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, opts
for (;;) {
try {
return await withRefreshingLock(engine, lockId, async (signal, handle) => {
- const lease: DrainLease = { lockId, sourceId, token: handle.acquisitionToken };
+ const lease: DrainLease = { lockId, sourceId, token: handle.acquisitionToken, signal };
await writeHolderRecord(engine, sourceId, lease, opts.holder);
const beacon = setInterval(() => {
void engine.executeRaw(`UPDATE minion_jobs SET lock_until=now()+make_interval(mins => $3),updated_at=now() WHERE queue=$1 AND lock_token=$2`,
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index c5998483e3..f7714e6e1e 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -1440,11 +1440,12 @@ async function oldRunBlocker(engine: Pick<BrainEngine, 'executeRaw'>, cursor: Pi
export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
if (opts.dryRun || currentDrainLease(opts.sourceId ?? 'default')) return performManagedPass(engine, opts, slice);
const sourceId = opts.sourceId ?? 'default';
- return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null } },
+ const remote = currentSubmissionAuthority()?.kind === 'remote_generic';
+ return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null }, remote },
signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice))
.catch(async error => {
if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(sourceId)) throw error;
- return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote: currentSubmissionAuthority()?.kind === 'remote_generic' });
+ return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote });
});
}
async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
@@ -1519,7 +1520,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
};
try {
assertActive();
- const resolution = await resolveManagedCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, assertActive, readOnly: !!opts.dryRun });
+ // A remote caller folds nothing in: the cursors it would cancel or retire may belong to another principal (it adopts only its own).
+ const resolution = await resolveManagedCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, assertActive, readOnly: !!opts.dryRun,
+ foldIn: !authority.writer.remote });
key = resolution.key;
if (resolution.adoptedLegacyKey || resolution.superseded.length || resolution.retained.length) state.fanIn = { adopted: !!resolution.adoptedLegacyKey, superseded: resolution.superseded.length, retained: resolution.retained.length };
// #6712 PR 1: a superseded run's write still in flight settles before the adopted run publishes beside it.
diff --git a/test/persistence-sync-cursor-adoption.test.ts b/test/persistence-sync-cursor-adoption.test.ts
index 2ccf0111d3..fa65fed6d1 100644
--- a/test/persistence-sync-cursor-adoption.test.ts
+++ b/test/persistence-sync-cursor-adoption.test.ts
@@ -207,6 +207,71 @@ test('fan-in: the newest older-key cursor finishes in place; an older one is kep
expect(await engine.getPage('e', { sourceId: id })).not.toBeNull();
}), 180_000);
+// Outside-voice review: a request claimed between the fan-in's read and its retirement must still hold the pass back.
+test('fan-in: a request claimed between the read and the retirement keeps the pass waiting (writer_pending), not draining beside it', async () => each(async engine => {
+ const id = await fixture(engine, ['a', 'b', 'c', 'd']);
+ const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
+ const newest = `${id}-newest`, raced = `${id}-raced`;
+ let release = () => {};
+ try {
+ __setManagedCursorKeyForTests(() => newest);
+ expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ await park(newest, 'managed-sync-parked');
+ __setManagedCursorKeyForTests(() => raced);
+ release = stallPreparation(async () => true);
+ expect(await performManagedSync(engine, opts(id))).toMatchObject({ status: 'partial', reason: 'writer_pending' });
+ await park(newest, 'managed-sync');
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [raced]);
+ } finally { __setManagedCursorKeyForTests(null); }
+ // The fan-in's first read of the raced cursor's requests sees nothing open (the claim lands right after it).
+ const execute = engine.executeRaw;
+ let hidden = false;
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ if (!hidden && sql.includes("intent->>'cursorKey'=$2") && sql.startsWith('SELECT * FROM persistence_requests') && params?.[1] === raced) { hidden = true; return []; }
+ return execute.call(this, sql, params);
+ } as BrainEngine['executeRaw'];
+ let waited;
+ try { waited = await performManagedSync(engine, opts(id)); } finally { engine.executeRaw = execute; }
+ expect(hidden).toBe(true);
+ expect(waited).toMatchObject({ status: 'partial', reason: 'writer_pending', retryWait: { state: 'running' }, cursorFanIn: { adopted: true, superseded: 0, retained: 1 } });
+ release();
+ installFaultHook(undefined);
+ for (let i = 0; i < 100 && (await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [id])).length; i++) await new Promise(resolve => setTimeout(resolve, 100));
+ expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
+}), 180_000);
+
+// Outside-voice review: a remote caller refused adoption must not have cancelled or retired the local runs it passed over.
+test('a remote job refused the local winner folds nothing in: every older-key cursor and its requests stay as they were', async () => each(async engine => {
+ const id = await fixture(engine, ['a', 'b', 'c', 'd']);
+ const park = (key: string, op: string) => engine.executeRaw('UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN (\'managed-sync\',\'managed-sync-parked\')', [key, op]);
+ const newest = `${id}-newest`, older = `${id}-older`;
+ const keys = async () => (await engine.executeRaw<{ key: string }>("SELECT fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [id])).map(row => row.key);
+ try {
+ __setManagedCursorKeyForTests(() => older);
+ expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ await park(older, 'managed-sync-parked');
+ __setManagedCursorKeyForTests(() => newest);
+ expect(await performManagedSync(engine, opts(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ await park(older, 'managed-sync');
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '1 hour' WHERE op='managed-sync' AND fingerprint=$1", [older]);
+ } finally { __setManagedCursorKeyForTests(null); }
+ const before = { keys: await keys(), requests: await requests(engine, id) };
+ expect(before.keys).toEqual([newest, older].sort());
+ const clientId = `adopt-client-${randomUUID()}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
+ VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);
+ try {
+ const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
+ allowedOperations: ['submit_job'] } } as unknown as OperationContext;
+ const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
+ const refused = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts)).then(() => null, (error: unknown) => error);
+ expect(refused).toMatchObject({ code: 'sync_in_progress', reason: 'local_resume_required' });
+ } finally { await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]); }
+ expect({ keys: await keys(), requests: await requests(engine, id) }).toEqual(before);
+ // The host CLI then folds them in.
+ expect((await performManagedSync(engine, opts(id))).status).toBe('first_sync');
+}), 180_000);
+
test('a company approval\'s cursor is never adopted or superseded by an ordinary run of the source', async () => each(async engine => {
const id = await fixture(engine);
const inc = (await engine.executeRaw<{ i: string }>('SELECT incarnation::text AS i FROM sources WHERE id=$1', [id]))[0]!.i;
diff --git a/test/persistence-sync-lease.test.ts b/test/persistence-sync-lease.test.ts
index 2fce7d4ea3..197daec3f4 100644
--- a/test/persistence-sync-lease.test.ts
+++ b/test/persistence-sync-lease.test.ts
@@ -20,6 +20,8 @@ import { SyncLockBusyError } from '../src/core/sync-lock.ts';
import { noteForwardProgress, registerRunDeadline } from '../src/core/forward-progress.ts';
import { withEnv } from './helpers/with-env.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
// #6712 PR 1: the drain lease. One managed drainer per source, whoever started it, fenced on the lock's acquisition
// token; a plain CLI sync follows a live holder within its budget instead of draining beside it. Each test here fails on
@@ -174,6 +176,37 @@ test('fencing: a pass whose lease was taken over after its TTL admits nothing an
expect((await performSync(engine, plain(id))).status).toBe('first_sync');
}), 120_000);
+// Outside-voice review: a lease that lapsed with nobody taking it over is lost too; the token alone does not admit.
+test('fencing: a pass whose lease expired untaken admits nothing and advances no checkpoint', async () => isolated(async engine => {
+ const id = await fixture(engine);
+ let lapsed = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:lease_acquired' || detail.sourceId !== id || lapsed) return;
+ lapsed = true;
+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET ttl_expires_at=now()-interval '1 second' WHERE id=$1`, [syncLockId(id)]);
+ });
+ const stale = await performSync(engine, plain(id));
+ installFaultHook(undefined);
+ expect(lapsed).toBe(true);
+ expect(stale).toMatchObject({ reason: 'drain_lease_held', leaseHeld: { lost: true } });
+ expect(await managedRows(engine, id)).toEqual({ cursors: 0, requests: 0 });
+ expect((await performSync(engine, plain(id))).status).toBe('first_sync');
+}), 120_000);
+
+// Outside-voice review: a job result is readable remotely (get_job), so the skip names the holder's kind, never its host, pid or id.
+test('a sync job that finds the lease held skips with the public holder only', async () => isolated(async engine => {
+ const id = await fixture(engine);
+ const holder = hold(engine, id, 'cli');
+ await holder.ready;
+ try {
+ const ctx = { id: 9101, name: 'sync', data: { sourceId: id, pull: false }, attempts_made: 0, signal: new AbortController().signal, shutdownSignal: new AbortController().signal,
+ deadlineAtMs: Date.now() + 60_000, updateProgress: async () => undefined, updateTokens: async () => undefined, log: async () => undefined, isActive: async () => true,
+ readInbox: async () => [] } as unknown as MinionJobContext;
+ const skipped = await makeSyncHandler(engine)(ctx) as Record<string, unknown>;
+ expect(skipped).toMatchObject({ skipped: true, reason: 'sync_in_progress', holder: { kind: 'cli', host: null, pid: null, id: null } });
+ } finally { await holder.release(); }
+}), 120_000);
+
test('the follower stops before the process watchdog: the lesser of its deadline and the hard deadline, less a margin', () => {
const now = Date.now();
registerRunDeadline({ atMs: now + 13 * 60_000, strict: true });