Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): the preparation deadline kills the pending-import Git process group (#7436)

garrytan27ee6a56a2c8
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 1b370444d7..1ce68175e1 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -367,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 waitingOnWhile(options.clock, 'git', () => 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, options.clock?.signal))) 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.`,
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index c147bbad31..7c52db91af 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -16,30 +16,78 @@
* imports the file (`replayImportedRemembers`, repair/failed-writes.ts); any other write
* is resubmitted by its caller after that sync.
*/
+import { spawn } from 'node:child_process';
import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
+import { gitChildEnv } from '../git-env.ts';
import { opError, type OperationError } from '../ops/contract.ts';
-import { syncGitAsync } from './sync-discovery.ts';
import { PENDING_IMPORT_MESSAGE } from './verb-errors.ts';
export const PENDING_IMPORT = 'pending_import';
/** #6693: the receipt origin of a write refused because sync holds the page's file (heldFileRefusal). */
export const SYNC_HELD = 'sync_held';
-/** Whether the file at `path` (inside the source checkout `root`) is a committed change the source has not imported yet. */
-export async function committedPendingImport(engine: BrainEngine, sourceId: string, root: string, path: string): Promise<boolean> {
+const GIT_TIMEOUT_MS = 30_000;
+/** #7436: how long a Git child the check ended with SIGTERM gets before its process group is sent SIGKILL. */
+export const GIT_KILL_GRACE_MS = 2_000;
+
+/**
+ * #7436: one Git command of the check, awaited (never a synchronous spawn, which stopped the whole write owner) and ended with
+ * the preparation: when `signal` aborts (the consumer aborts it at the preparation deadline) or the command passes
+ * GIT_TIMEOUT_MS, the call rejects at once and the command's process group gets SIGTERM, then SIGKILL after
+ * GIT_KILL_GRACE_MS, so no Git process outlives the request that started it.
+ */
+function gitRead(root: string, args: string[], signal?: AbortSignal): Promise<string> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) { reject(signal.reason); return; }
+ const group = process.platform !== 'win32';
+ const child = spawn('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'], detached: group });
+ const kill = (name: NodeJS.Signals) => { try { if (group && child.pid) process.kill(-child.pid, name); else child.kill(name); } catch { /* already gone */ } };
+ let stdout = '', settled = false;
+ const settle = (error: unknown, value = '') => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ if (error === undefined) { resolve(value); return; }
+ if (child.exitCode === null && child.signalCode === null) {
+ kill('SIGTERM');
+ setTimeout(() => kill('SIGKILL'), GIT_KILL_GRACE_MS).unref();
+ }
+ reject(error);
+ };
+ const onAbort = () => settle(signal!.reason);
+ const timer = setTimeout(() => settle(new Error(`git ${args[0]} did not finish within ${GIT_TIMEOUT_MS} ms`)), GIT_TIMEOUT_MS);
+ signal?.addEventListener('abort', onAbort, { once: true });
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => { stdout += chunk; });
+ child.on('error', error => settle(error));
+ child.on('close', code => settle(code === 0 ? undefined : new Error(`git ${args[0]} exited ${code}`), stdout));
+ });
+}
+
+/**
+ * Whether the file at `path` (inside the source checkout `root`) is a committed change the source has not imported yet.
+ * #7436: `signal` is the preparation's cancellation; when it aborts, the Git command in flight is killed and the check
+ * rejects with its reason instead of answering, so the preparation stops.
+ */
+export async function committedPendingImport(engine: BrainEngine, sourceId: string, root: string, path: string, signal?: AbortSignal): Promise<boolean> {
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 = (await syncGitAsync(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`])).trim();
- if (!head || (await syncGitAsync(root, ['hash-object', '--', rel])).trim() !== head) return false;
+ const head = (await gitRead(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`], signal)).trim();
+ if (!head || (await gitRead(root, ['hash-object', '--', rel], signal)).trim() !== head) return false;
if (!source?.last_commit) return true;
- await syncGitAsync(root, ['cat-file', '-e', `${source.last_commit}^{commit}`]);
+ await gitRead(root, ['cat-file', '-e', `${source.last_commit}^{commit}`], signal);
let imported = '';
- try { imported = (await syncGitAsync(root, ['rev-parse', '--verify', '--quiet', `${source.last_commit}:${rel}`])).trim(); } catch { imported = ''; }
+ try { imported = (await gitRead(root, ['rev-parse', '--verify', '--quiet', `${source.last_commit}:${rel}`], signal)).trim(); } catch (error) {
+ if (signal?.aborted) throw error;
+ imported = '';
+ }
return imported !== head;
- } catch {
+ } catch (error) {
+ if (signal?.aborted) throw signal.reason;
return false;
}
}
diff --git a/test/pending-import-async-git-7436.test.ts b/test/pending-import-async-git-7436.test.ts
index 71bc40eace..46a2b9b24b 100644
--- a/test/pending-import-async-git-7436.test.ts
+++ b/test/pending-import-async-git-7436.test.ts
@@ -2,17 +2,21 @@
* #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.
+ * Git now runs as an awaited child process, and the step's stamp says `waiting_on=git` while it runs. A production
+ * preparation also kept running for minutes after its deadline and its terminal receipt: the deadline (the preparation's
+ * abort signal) now kills the Git process group, SIGTERM then SIGKILL after a grace, and the preparation stops there.
* 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 { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, 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 { GIT_KILL_GRACE_MS } from '../src/core/persistence/pending-import.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { durableGitRepo, git } from './helpers/git-publication.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -20,6 +24,29 @@ 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']); };
+
+async function pendingImportPage(engine: BrainEngine, ctx: Parameters<typeof submitPageMutation>[0], root: string) {
+ 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'");
+ return { snapshot, row: { source_id: 'default', worktree_id: binding!.worktree_id, slug } };
+}
+function gitShim(script: (realGit: string) => string): string {
+ const shims = mkdtempSync(join(tmpdir(), 'gbrain-slow-git-'));
+ writeFileSync(join(shims, 'git'), script(Bun.which('git')!));
+ chmodSync(join(shims, 'git'), 0o755);
+ return shims;
+}
+/** A pid that is gone or a zombie (an orphaned grandchild waits to be reaped by whatever adopted it). */
+function alive(pid: number): boolean {
+ try { process.kill(pid, 0); } catch { return false; }
+ const stat = `/proc/${pid}/stat`;
+ return !existsSync(stat) || !/^\d+ \(.*\) Z /.test(readFileSync(stat, 'utf8'));
+}
+
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' } });
@@ -49,4 +76,39 @@ describe('#7436 pending-import Git check during page preparation', () => {
expect(clock.waitingOn).toBe('db');
expect(clock.step).toBe('link_resolution');
}, { setup }), 120_000);
+
+ test.skipIf(process.platform === 'win32')('the preparation deadline kills the Git process group and the preparation stops', () => managedBrain(async ({ engine, ctx, root }) => {
+ const { snapshot, row } = await pendingImportPage(engine, ctx, root);
+ const pids = join(mkdtempSync(join(tmpdir(), 'gbrain-git-pids-')), 'pids');
+ // hash-object ignores SIGTERM and leaves a grandchild that does too, both outliving any deadline: only the group SIGKILL ends them.
+ const shims = gitShim(realGit => `#!/bin/sh\nfor a in "$@"; do if [ "$a" = "hash-object" ]; then trap '' TERM; sleep 120 & echo "$PPID $$ $!" >> ${pids}; wait; fi; done\nexec "${realGit}" "$@"\n`);
+ const deadline = new AbortController();
+ const clock = startClaimPhase(Date.now(), deadline.signal);
+ enterClaimStep(clock, 'link_resolution', undefined, 'db');
+ let callsAfterAbort = 0;
+ const watched = new Proxy(engine, { get(target, key) {
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? (...args: unknown[]) => { if (deadline.signal.aborted) callsAfterAbort++; return value.apply(target, args); } : value;
+ } }) as BrainEngine;
+ try {
+ const outcome = withEnv({ PATH: `${shims}:${process.env.PATH}` }, () =>
+ prepareFileTarget(watched, row, snapshot, 'replacement\n', undefined, { clock }).then(() => null, (error: unknown) => error));
+ // Background Git effects of the seed write may run the shim too: the check's own command is the one this process spawned.
+ const ours = () => existsSync(pids) ? readFileSync(pids, 'utf8').trim().split('\n').map(line => line.split(' ').map(Number)).find(([parent]) => parent === process.pid) : undefined;
+ while (!ours()) await Bun.sleep(20);
+ const [, child, grandchild] = ours()!;
+ const reason = Object.assign(new Error('preparation deadline'), { code: 'deadline_exceeded' });
+ const abortedAt = Date.now();
+ deadline.abort(reason);
+ expect(await outcome).toBe(reason);
+ expect(Date.now() - abortedAt).toBeLessThan(1_000);
+ // SIGTERM was ignored, so both are still there until the grace ends.
+ expect([alive(child!), alive(grandchild!)]).toEqual([true, true]);
+ while ((alive(child!) || alive(grandchild!)) && Date.now() - abortedAt < GIT_KILL_GRACE_MS + 3_000) await Bun.sleep(50);
+ expect([alive(child!), alive(grandchild!)]).toEqual([false, false]);
+ expect(Date.now() - abortedAt).toBeLessThan(GIT_KILL_GRACE_MS + 3_000);
+ expect(callsAfterAbort).toBe(0);
+ expect(clock.waitingOn).toBe('db');
+ } finally { rmSync(shims, { recursive: true, force: true }); rmSync(dirname(pids), { recursive: true, force: true }); }
+ }, { setup }), 120_000);
});