Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): run the pending-import Git check asynchronously and stamp waiting_on=git (#7436)

garrytan1bb6b5f7ea9e
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index f60cda43f6..c239e0df27 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -104,6 +104,18 @@ export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string,
if (clock.step !== step) { clock.step = step; clock.stepSince = now; }
clock.waitingOn = waitingOn;
}
+/**
+ * #7436: runs a wait on something other than the database (a Git child process) inside the current step, with the
+ * stamp's `waiting_on` naming it until it ends; the step keeps its name, so a stall reads `step=link_resolution
+ * waiting_on=git` instead of blaming the last statement. Checks the preparation's cancellation first, like a step boundary.
+ */
+export async function waitingOnWhile<T>(clock: ClaimPhaseClock | undefined, waitingOn: WaitingOn, run: () => Promise<T>): Promise<T> {
+ clock?.signal?.throwIfAborted();
+ if (!clock) return run();
+ const prior = clock.waitingOn;
+ clock.waitingOn = waitingOn;
+ try { return await run(); } finally { if (clock.waitingOn === waitingOn) clock.waitingOn = prior; }
+}
/** #6317: the label of a raw statement for the stamp: its first keyword and the first table it names; never text or parameters. */
export function sqlLabel(sql: string): string {
const text = sql.replace(/\s+/g, ' ').trim();
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index a89a060464..1b370444d7 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1,7 +1,7 @@
import { isEmbedSkipped } from '../embed-skip.ts';
import { appendPurgeCommitted } from '../belief/purge-mirror.ts';
import { sizeStateField } from '../page-embedding-budget.ts';
-import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
+import { enterClaimStep, waitingOnWhile, type ClaimPhaseClock } from './claim-phase.ts';
import { boundedReads } from './bounded-reads.ts';
import { isQuarantined, quarantineOutcome } from '../quarantine.ts';
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
@@ -260,7 +260,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */
sharedOrigin?: { onShared: (shared: SharedOrigin) => void };
/** Runs between the pieces of a segmented page's file comparison (an effect's claim renewal). */
- between?: () => Promise<void> } = {}): Promise<PreparedMutation['file']> {
+ between?: () => Promise<void>;
+ /** #7436: the preparation's clock, so its stamp says `waiting_on=git` while a Git check runs. */
+ clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
// An in-memory canonical file over the 25 MiB push-scan cap is refused (only a page over the 24 MiB single-string
// ceiling renders one). That page's file is streamed instead (restore_page of a page whose body was not read back,
@@ -304,7 +306,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// target file does not exist yet: an existing page keeps its file (and its drift checks and storage refusals), and only a
// person's detach turns it database-only. A Git-durable source keeps writing the file: its Git effect cannot commit an
// ignored target and parks it (`git_target_unsafe`), which already shows the page needs a decision.
- if (options.newPageIgnoredDatabaseOnly && !snapshot && content !== null && !existsSync(path) && !isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await gitIgnoresUntracked(root, relative(root, path).split(sep).join('/'))
+ if (options.newPageIgnoredDatabaseOnly && !snapshot && content !== null && !existsSync(path) && !isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await waitingOnWhile(options.clock, 'git', () => gitIgnoresUntracked(root, relative(root, path).split(sep).join('/')))
&& !(await gitDurabilityPolicy(binding, root)).durable) return undefined;
if (options.excludeTombstone && snapshot?.page.deleted_at) {
const rel = relative(root, path).split(sep).join('/');
@@ -365,7 +367,7 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
// #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.
const adopt = !snapshot.page.source_path && !snapshot.page.source_uri ? ['--adopt-slug-path'] : [];
// #6693: a committed Git change sync has not imported yet (another agent's commit), on a page that records its file.
- if (!adopt.length && await committedPendingImport(engine, row.source_id, root, path)) throw pendingImportRefusal(row, options.remote === true);
+ if (!adopt.length && await waitingOnWhile(options.clock, 'git', () => committedPendingImport(engine, row.source_id, root, path))) throw pendingImportRefusal(row, options.remote === true);
throw opError('source_changed', 'The canonical file contains an uncoordinated local edit.',
`On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview${adopt.length ? ' --adopt-slug-path (the page records no file of its own, so the preview adopts the file at its slug path)' : ''}, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`,
{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,
@@ -579,7 +581,7 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap
const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: snapshot.page });
enterClaimStep(options.clock, 'file_target', undefined, 'fs');
const file = await prepareFileTarget(engine, row, snapshot, await unreadPageFile(engine, snapshot), undefined,
- { allowMissing: options.allowMissingFile, activePack: options.activePack, remote: row.authority.remote });
+ { allowMissing: options.allowMissingFile, activePack: options.activePack, remote: row.authority.remote, clock: options.clock });
const pageId = Number(snapshot.page.id);
enterClaimStep(options.clock, 'seal_probe', undefined, 'db');
const generation = Number(snapshot.bodyGeneration), live = noop ? [] : await engine.readManifest(pageId, { generation });
@@ -805,7 +807,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
resolveParsedSubtype(incoming, snapshot.page);
const tags = versionTags ?? [...new Set([...snapshot.tags,...incoming.tags])].sort();
if (digest(canonical(snapshot.page,snapshot.tags)) === digest(canonical(incoming,tags))) {
- const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags),undefined,{ activePack, remote: row.authority.remote });
+ const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags),undefined,{ activePack, remote: row.authority.remote, clock });
return {observedRevision,noop:true,file,...await pageDatabaseOnlyPublication(engine,row,file),
apply:async()=>({...pageNoopAdvisories(row),status:'skipped',slug:row.slug,source_id:row.source_id,noop:true,chunks:0,chunk_skip_reason:'write_skipped',
...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{}),...fenceRepairOutcome})};
@@ -895,7 +897,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),
async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,
- () => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true }),
+ () => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true, clock }),
// Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).
async () => noop ? null : prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage }),
]) as [Awaited<ReturnType<typeof prepareCanonicalProjections>> | undefined, Record<string, unknown>,
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index debfa6fbaa..c147bbad31 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -20,7 +20,7 @@ import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { opError, type OperationError } from '../ops/contract.ts';
-import { syncGit } from './sync-discovery.ts';
+import { syncGitAsync } from './sync-discovery.ts';
import { PENDING_IMPORT_MESSAGE } from './verb-errors.ts';
export const PENDING_IMPORT = 'pending_import';
@@ -32,12 +32,12 @@ export async function committedPendingImport(engine: BrainEngine, sourceId: stri
const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
const rel = `./${relative(root, path).split(sep).join('/')}`;
try {
- const head = syncGit(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`]).trim();
- if (!head || syncGit(root, ['hash-object', '--', rel]).trim() !== head) return false;
+ const head = (await syncGitAsync(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`])).trim();
+ if (!head || (await syncGitAsync(root, ['hash-object', '--', rel])).trim() !== head) return false;
if (!source?.last_commit) return true;
- syncGit(root, ['cat-file', '-e', `${source.last_commit}^{commit}`]);
+ await syncGitAsync(root, ['cat-file', '-e', `${source.last_commit}^{commit}`]);
let imported = '';
- try { imported = syncGit(root, ['rev-parse', '--verify', '--quiet', `${source.last_commit}:${rel}`]).trim(); } catch { imported = ''; }
+ try { imported = (await syncGitAsync(root, ['rev-parse', '--verify', '--quiet', `${source.last_commit}:${rel}`])).trim(); } catch { imported = ''; }
return imported !== head;
} catch {
return false;
diff --git a/test/pending-import-async-git-7436.test.ts b/test/pending-import-async-git-7436.test.ts
new file mode 100644
index 0000000000..71bc40eace
--- /dev/null
+++ b/test/pending-import-async-git-7436.test.ts
@@ -0,0 +1,52 @@
+/**
+ * #7436: the pending-import check (a page write onto a file that differs from the database) ran Git synchronously, up
+ * to 30 s per call, so a slow checkout froze the owner process (its lease renewals and every other preparation) while
+ * one page was prepared, and the stall line blamed the last statement (`waiting_on=db last_sql=SELECT_sources`).
+ * Git now runs as an awaited child process, and the step's stamp says `waiting_on=git` while it runs.
+ * A `git` shim on PATH that sleeps before each call stands in for the slow checkout. Managed PGLite brain, no providers.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { enterClaimStep, startClaimPhase, type WaitingOn } from '../src/core/persistence/claim-phase.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const slug = 'people/alice-example';
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+
+describe('#7436 pending-import Git check during page preparation', () => {
+ test.skipIf(process.platform === 'win32')('keeps the event loop running and stamps waiting_on=git while Git runs', () => managedBrain(async ({ engine, ctx, root }) => {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: '---\ntype: person\ntitle: Alice\n---\n\nBody.\n' } });
+ const file = join(root, `${slug}.md`);
+ writeFileSync(file, readFileSync(file, 'utf8').replace('Body.', 'Body.\n\nAnother agent added this line through Git.'));
+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'agent commit not yet imported');
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ const [binding] = await engine.executeRaw<{ worktree_id: string }>("SELECT worktree_id FROM persistence_source_bindings WHERE source_id='default'");
+ const realGit = Bun.which('git')!;
+ const shims = mkdtempSync(join(tmpdir(), 'gbrain-slow-git-'));
+ writeFileSync(join(shims, 'git'), `#!/bin/sh\nsleep 0.4\nexec "${realGit}" "$@"\n`);
+ chmodSync(join(shims, 'git'), 0o755);
+ const clock = startClaimPhase();
+ enterClaimStep(clock, 'link_resolution', undefined, 'db');
+ let ticks = 0;
+ const seen = new Set<WaitingOn>();
+ const timer = setInterval(() => { ticks++; seen.add(clock.waitingOn); }, 20);
+ try {
+ const outcome = await withEnv({ PATH: `${shims}:${process.env.PATH}` }, () =>
+ prepareFileTarget(engine, { source_id: 'default', worktree_id: binding!.worktree_id, slug }, snapshot, 'replacement\n', undefined, { clock })
+ .then(() => null, (error: { reason?: string }) => error));
+ expect(outcome?.reason).toBe('pending_import');
+ } finally { clearInterval(timer); rmSync(shims, { recursive: true, force: true }); }
+ // At least two shimmed Git calls (0.8 s): a synchronous spawn let the 20 ms timer run at most once in that time.
+ expect(ticks).toBeGreaterThanOrEqual(10);
+ expect(seen.has('git')).toBe(true);
+ expect(clock.waitingOn).toBe('db');
+ expect(clock.step).toBe('link_resolution');
+ }, { setup }), 120_000);
+});