Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): re-check an exiting git before refusing an index-lock reclaim
garrytan3830af463251
diff --git a/src/core/persistence/index-lock-reclaim.ts b/src/core/persistence/index-lock-reclaim.tsindex 1fc973e6c9..cd7d29e42b 100644--- a/src/core/persistence/index-lock-reclaim.ts+++ b/src/core/persistence/index-lock-reclaim.ts@@ -17,7 +17,11 @@* `GIT_INDEX_FILE` inside the checkout or its git directory. A git process* whose open files or environment cannot be read fails the proof. Another* user's processes that are not git cannot be read and are not checked: only- * git creates this lock, and their git processes still fail the proof.+ * git creates this lock, and their git processes still fail the proof. This+ * user's own git denies its open files only while it exits (its memory is+ * gone, its files not yet closed): it is re-checked until it is gone, a+ * zombie or readable, for at most {@link RECLAIM_MIN_AGE_MS} per proof, and+ * fails the proof if it is still unreadable then.* - The lock is empty and at least {@link RECLAIM_MIN_AGE_MS} old, or older* than the stale threshold.*@@ -85,39 +89,71 @@ export function processTableBlind(): string | null {return null;}+/** Real uid and state of a process from /proc/<pid>/status, or null when it ended. */+function owner(proc: string, pid: string): { uid: number; zombie: boolean } | null {+ let status: string;+ try { status = readFileSync(`${proc}/${pid}/status`, 'utf8'); } catch { return null; }+ return { uid: Number(/^Uid:\s+(\d+)/m.exec(status)?.[1] ?? -1), zombie: /^State:\s+[ZX]/m.test(status) };+}++/** Synchronous pause for the re-check below; the proof itself is synchronous. */+const pause = (ms: number) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };+/** The git environment variables that place a process's repository or index. */const GIT_LOCATION_VARIABLES = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE'];+/**+ * Read a /proc entry of a git process. A denied read belongs to another user's process (`foreign`) or to+ * this user's own process while it exits; that one is read again until it reads, ends or turns zombie (`gone`:+ * a zombie holds no files), or `until` passes (`denied`).+ */+function readGit<T>(proc: string, pid: string, until: number, read: () => T): T | 'gone' | 'foreign' | 'denied' {+ for (;;) {+ try { return read(); } catch (error) { if (gone(error)) return 'gone'; }+ const who = owner(proc, pid);+ if (!who || who.zombie) return 'gone';+ if (who.uid !== (process.getuid?.() ?? -1)) return 'foreign';+ if (Date.now() >= until) return 'denied';+ pause(10);+ }+}+/*** A process that holds the lock or runs git in the checkout, or a git process this process cannot inspect.* A process that has the lock open is named first, then a git in the checkout, then a git that cannot be* inspected, so a refusal names the actual holder when there is one.*/-function liveHolder(lock: { dev: number; ino: number }, roots: string[]): string | null {+function liveHolder(lock: { dev: number; ino: number }, roots: string[], proc: string): string | null {const opaque: string[] = [];const inRepository: string[] = [];- for (const pid of readdirSync('/proc')) {+ const until = Date.now() + RECLAIM_MIN_AGE_MS;+ const unreadable = (pid: string, comm: string) => `git process ${pid} (${comm}) is this user's, but it stayed unreadable for ${RECLAIM_MIN_AGE_MS / 1000}s`;+ for (const pid of readdirSync(proc)) {if (!/^\d+$/.test(pid)) continue;let comm: string;- try { comm = readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); } catch { continue; }- let fds: string[] | null = null;- try { fds = readdirSync(`/proc/${pid}/fd`); } catch (error) { if (gone(error)) continue; }- for (const fd of fds ?? []) {- let opened;- try { opened = statSync(`/proc/${pid}/fd/${fd}`); } catch { continue; }- if (opened.dev === lock.dev && opened.ino === lock.ino) return `process ${pid} (${comm}) has the lock open`;- }- if (!comm.startsWith('git')) continue;- if (fds === null) { opaque.push(`git process ${pid} (${comm}) belongs to another user, so its open files cannot be checked`); continue; }- let cwd: string;- let environ: string;- try {- cwd = readlinkSync(`/proc/${pid}/cwd`).replace(/ \(deleted\)$/, '');- environ = readFileSync(`/proc/${pid}/environ`, 'utf8');- } catch (error) {- if (!gone(error)) opaque.push(`git process ${pid} (${comm}) could not be inspected`);+ try { comm = readFileSync(`${proc}/${pid}/comm`, 'utf8').trim(); } catch { continue; }+ const holds = (fds: string[]) => fds.some(fd => {+ try { const opened = statSync(`${proc}/${pid}/fd/${fd}`); return opened.dev === lock.dev && opened.ino === lock.ino; } catch { return false; }+ });+ if (!comm.startsWith('git')) {+ let fds: string[];+ try { fds = readdirSync(`${proc}/${pid}/fd`); } catch { continue; }+ if (holds(fds)) return `process ${pid} (${comm}) has the lock open`;continue;}+ const fds = readGit(proc, pid, until, () => readdirSync(`${proc}/${pid}/fd`));+ if (fds === 'gone') continue;+ if (fds === 'foreign') { opaque.push(`git process ${pid} (${comm}) belongs to another user, so its open files cannot be checked`); continue; }+ if (fds === 'denied') { opaque.push(unreadable(pid, comm)); continue; }+ if (holds(fds)) return `process ${pid} (${comm}) has the lock open`;+ const place = readGit(proc, pid, until, () => ({+ cwd: readlinkSync(`${proc}/${pid}/cwd`).replace(/ \(deleted\)$/, ''),+ environ: readFileSync(`${proc}/${pid}/environ`, 'utf8'),+ }));+ if (place === 'gone') continue;+ if (place === 'foreign') { opaque.push(`git process ${pid} (${comm}) could not be inspected`); continue; }+ if (place === 'denied') { opaque.push(unreadable(pid, comm)); continue; }+ const { cwd, environ } = place;if (inside(cwd, roots)) { inRepository.push(`git process ${pid} (${comm}) is running in the checkout`); continue; }for (const entry of environ.split('\0')) {const at = entry.indexOf('=');@@ -136,8 +172,9 @@ function liveHolder(lock: { dev: number; ino: number }, roots: string[]): string* Whether `lock` (the checkout's own index lock) is provably abandoned. `checkout` is the worktree root;* the lock's directory is the git directory that owns the index. A lock older than `staleMs` qualifies* whatever its size; a younger one only when it is empty and at least {@link RECLAIM_MIN_AGE_MS} old.+ * `proc` is where the process table is read (`/proc`; a test points it at a fixture tree).*/-export function proveIndexLockAbandoned(lock: string, checkout: string, staleMs: number): IndexLockVerdict {+export function proveIndexLockAbandoned(lock: string, checkout: string, staleMs: number, proc = '/proc'): IndexLockVerdict {const blind = processTableBlind();if (blind) return doubt(blind);let before;@@ -151,7 +188,7 @@ export function proveIndexLockAbandoned(lock: string, checkout: string, staleMs:if (SHARED_FILESYSTEMS.has(Number(statfsSync(dirname(lock)).type) >>> 0)) return doubt('the checkout is on a network or userspace filesystem, where a git on another machine is invisible');} catch { return doubt('the filesystem holding the lock could not be identified'); }let holder: string | null;- try { holder = liveHolder(before, [canonical(checkout), canonical(dirname(lock))]); }+ try { holder = liveHolder(before, [canonical(checkout), canonical(dirname(lock))], proc); }catch { return doubt('the process table under /proc could not be read'); }if (holder) return doubt(holder);let after;diff --git a/test/persistence-index-lock-reclaim-6932.test.ts b/test/persistence-index-lock-reclaim-6932.test.tsindex 847c01b47f..eb15e8a096 100644--- a/test/persistence-index-lock-reclaim-6932.test.ts+++ b/test/persistence-index-lock-reclaim-6932.test.ts@@ -13,7 +13,7 @@*/import { afterEach, expect, test } from 'bun:test';import { execFileSync, spawn, type ChildProcess } from 'node:child_process';-import { existsSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync, closeSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync, closeSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { commitGitTargets, gitStepTimeoutMs, INDEX_LOCK_GRACE_FOR_TESTS } from '../src/core/persistence/effect-git.ts';@@ -46,6 +46,7 @@ function repo(): { root: string; home: string; lock: string } {const home = mkdtempSync(join(tmpdir(), 'gbrain-reclaim-home-'));scratch.push(root, home);git(root, 'init', '-q');+ git(root, 'config', 'maintenance.auto', 'false'); git(root, 'config', 'gc.auto', '0');git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');writeFileSync(join(root, 'a.md'), 'first\n');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');@@ -57,11 +58,16 @@ const until = async (done: () => boolean, ms = 20_000) => {for (const deadline = Date.now() + ms; !done() && Date.now() < deadline;) await Bun.sleep(10);expect(done()).toBe(true);};-/** Another user's git on this host (a CI agent, a system service) cannot be inspected, so it blocks every proof while it runs. */+/**+ * Another user's git on this host (a CI agent, a system service) cannot be inspected, so it blocks every proof while+ * it runs. This user's own git also denies its open files while it exits; the proof re-checks that one, so it is not+ * foreign (its status Uid is ours).+ */const foreignGit = () => process.platform === 'linux' && readdirSync('/proc').some(pid => {if (!/^\d+$/.test(pid)) return false;try { if (!readFileSync(`/proc/${pid}/comm`, 'utf8').startsWith('git')) return false; } catch { return false; }- try { readdirSync(`/proc/${pid}/fd`); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EACCES'; }+ try { readdirSync(`/proc/${pid}/fd`); return false; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EACCES') return false; }+ try { return Number(/^Uid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1]) !== process.getuid?.(); } catch { return false; }});/** Whether a reclaim can be proven here now: the process table is visible and no uninspectable git runs (waited out up to 30 s). */async function canProve(): Promise<boolean> {@@ -347,5 +353,91 @@ test('probe: the writer recovers on its own: a Git effect parked by a held lockexpect(readIndexLockReclaims()).toEqual([expect.objectContaining({ lock, size: 0 })]);const doctor = await checkParkedEffects(engine);expect(doctor).toMatchObject({ status: 'ok', details: { parked_effects: 0, index_lock_reclaims: { last_7_days: 1 } } });- }, { setup: ({ root }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); } });+ }, { setup: ({ root }) => {+ git(root, 'init', '-q'); git(root, 'config', 'maintenance.auto', 'false'); git(root, 'config', 'gc.auto', '0');+ writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']);+ } });}, 120_000);++/**+ * Fixture process tables for the proof's /proc reader: pid directories with comm, status and an fd directory.+ * An fd directory with mode 000 denies its listing the way the kernel does for a process whose open files this+ * user may not read (another user's, or this user's own git while it exits). Root reads it anyway, and only+ * Linux has the process table the proof reads.+ */+const fixtureProcRunnable = !blind && process.getuid?.() !== 0;+const procFixtures: string[] = [];+afterEach(() => {+ for (const proc of procFixtures.splice(0)) {+ execFileSync('chmod', ['-R', 'u+rwx', proc]);+ rmSync(proc, { recursive: true, force: true });+ }+});+function fixtureProc(pids: Record<string, { uid: number; state?: string; fds?: Record<string, string>; denied?: boolean; environDenied?: boolean }>): string {+ const proc = mkdtempSync(join(tmpdir(), 'gbrain-reclaim-proc-'));+ procFixtures.push(proc);+ for (const [pid, p] of Object.entries(pids)) {+ mkdirSync(join(proc, pid, 'fd'), { recursive: true });+ writeFileSync(join(proc, pid, 'comm'), 'git\n');+ writeFileSync(join(proc, pid, 'status'), `Name:\tgit\nState:\t${p.state ?? 'R (running)'}\nUid:\t${p.uid}\t${p.uid}\t${p.uid}\t${p.uid}\n`);+ writeFileSync(join(proc, pid, 'environ'), 'PATH=/usr/bin\0');+ symlinkSync(tmpdir(), join(proc, pid, 'cwd'));+ for (const [fd, target] of Object.entries(p.fds ?? {})) symlinkSync(target, join(proc, pid, 'fd', fd));+ if (p.denied) chmodSync(join(proc, pid, 'fd'), 0o000);+ if (p.environDenied) chmodSync(join(proc, pid, 'environ'), 0o000);+ }+ return proc;+}+/** Change a fixture process after `ms` from another process, while the synchronous proof runs. */+const later = (ms: number, script: string) => { const child = spawn('sh', ['-c', `sleep ${ms / 1000}; ${script}`], { stdio: 'ignore' }); children.push(child); };+const staleEmptyLock = () => { const r = repo(); writeFileSync(r.lock, ''); age(r.lock, RECLAIM_MIN_AGE_MS + 1_000); return r; };++test.skipIf(!fixtureProcRunnable)('this user\'s git that denies its open files while it exits is re-checked, and the proof follows once it is gone', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!(), denied: true } });+ later(300, `chmod 755 '${proc}/4242/fd' && rm -rf '${proc}/4242'`);+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toMatchObject({ abandoned: true, size: 0 });+});++test.skipIf(!fixtureProcRunnable)('this user\'s git that is a zombie holds no files, so it does not block the proof', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!(), state: 'Z (zombie)', denied: true } });+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toMatchObject({ abandoned: true, size: 0 });+});++test.skipIf(!fixtureProcRunnable)('this user\'s git whose open files become readable after the re-check and hold the lock still fails the proof', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!(), fds: { 3: lock }, denied: true } });+ later(300, `chmod 755 '${proc}/4242/fd'`);+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toEqual({ abandoned: false, reason: 'process 4242 (git) has the lock open' });+});++test.skipIf(!fixtureProcRunnable)('this user\'s git that stays alive and unreadable through the re-check fails the proof', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!(), denied: true } });+ const started = Date.now();+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toEqual({ abandoned: false,+ reason: `git process 4242 (git) is this user's, but it stayed unreadable for ${RECLAIM_MIN_AGE_MS / 1000}s` });+ expect(Date.now() - started).toBeGreaterThanOrEqual(RECLAIM_MIN_AGE_MS);+}, 60_000);++test.skipIf(!fixtureProcRunnable)('this user\'s git whose environment is denied while it exits is re-checked, and the proof follows once it is gone', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!(), environDenied: true } });+ later(300, `rm -rf '${proc}/4242'`);+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toMatchObject({ abandoned: true, size: 0 });+});++test.skipIf(!fixtureProcRunnable)('another user\'s git whose environment is denied still fails the proof at once, uninspected', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!() + 1, environDenied: true } });+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toEqual({ abandoned: false,+ reason: 'git process 4242 (git) could not be inspected' });+});++test.skipIf(!fixtureProcRunnable)('another user\'s git still fails the proof at once, unchecked', () => {+ const { root, lock } = staleEmptyLock();+ const proc = fixtureProc({ 4242: { uid: process.getuid!() + 1, denied: true } });+ expect(proveIndexLockAbandoned(lock, root, INDEX_LOCK_GRACE_FOR_TESTS, proc)).toEqual({ abandoned: false,+ reason: 'git process 4242 (git) belongs to another user, so its open files cannot be checked' });+});