Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
skill resolver: async session commits reclaim an expired lease
garrytand17f3c15cfbf
diff --git a/src/core/skills/resolver/lock.ts b/src/core/skills/resolver/lock.tsindex 4da2ee2e31..a34e4930b1 100644--- a/src/core/skills/resolver/lock.ts+++ b/src/core/skills/resolver/lock.ts@@ -9,7 +9,7 @@* caller's token, so a stale owner cannot act on its successor's lease.*/import { closeSync, fsyncSync, openSync, promises, readFileSync, renameSync, statSync, unlinkSync, writeSync } from 'node:fs';-const { open: openAsync, readFile: readFileAsync, unlink: unlinkAsync } = promises;+const { open: openAsync, readFile: readFileAsync, rename: renameAsync, stat: statAsync, unlink: unlinkAsync } = promises;import { randomBytes } from 'node:crypto';import { hostname } from 'node:os';import { ResolverError } from './errors.ts';@@ -21,15 +21,25 @@ export interface LeaseOpts { purpose: string; leaseMs: number; generation?: numb/** A lease file that never parses (a crash mid-create) counts as expired this long after its last write. */const UNPARSABLE_GRACE_MS = 60_000;-function readLease(path: string): LeaseRecord | 'unparsable' | null {- let text: string;- try { text = readFileSync(path, 'utf8'); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null; throw e; }+function parseLease(text: string): LeaseRecord | 'unparsable' {try {const r = JSON.parse(text) as LeaseRecord;return r && typeof r.token === 'string' && typeof r.expires_ms === 'number' ? r : 'unparsable';} catch { return 'unparsable'; }}+function readLease(path: string): LeaseRecord | 'unparsable' | null {+ let text: string;+ try { text = readFileSync(path, 'utf8'); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null; throw e; }+ return parseLease(text);+}++async function readLeaseAsync(path: string): Promise<LeaseRecord | 'unparsable' | null> {+ let text: string;+ try { text = await readFileAsync(path, 'utf8'); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null; throw e; }+ return parseLease(text);+}+function makeRecord(opts: LeaseOpts): LeaseRecord {const now = (opts.now ?? Date.now)();return { v: 1, token: randomBytes(16).toString('hex'), host: hostname(), pid: process.pid, purpose: opts.purpose, generation: opts.generation ?? 0, acquired_ms: now, expires_ms: now + opts.leaseMs };@@ -97,17 +107,35 @@ export function renewLease(lease: Lease, leaseMs: number, now: () => number = Dareturn holdsLease(lease);}+async function writeAsync(path: string, rec: LeaseRecord, flag: 'wx'): Promise<boolean> {+ let fh;+ try { fh = await openAsync(path, flag, 0o600); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'EEXIST') return false; throw e; }+ try { await fh.writeFile(JSON.stringify(rec)); await fh.sync(); } finally { await fh.close(); }+ return true;+}+/**- * One attempt with async I/O only, for a caller whose event loop owns a- * deadline (the hook lane): an expired or unparsable lease counts as held- * here (the sync acquireLease reclaims it), so this never replaces a file.+ * tryAcquireLease with async I/O only, for a caller whose event loop owns a+ * deadline (the hook lane): null while a live lease is held; an expired or+ * unparsable one is reclaimed the same way, so a holder that exited at its+ * deadline strands the file for at most its lease.*/export async function tryAcquireLeaseAsync(path: string, opts: LeaseOpts): Promise<Lease | null> {+ const now = (opts.now ?? Date.now)();const rec = makeRecord(opts);- let fh;- try { fh = await openAsync(path, 'wx', 0o600); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'EEXIST') return null; throw e; }- try { await fh.writeFile(JSON.stringify(rec)); await fh.sync(); } finally { await fh.close(); }- return { path, token: rec.token, record: rec };+ const mine = { path, token: rec.token, record: rec };+ if (await writeAsync(path, rec, 'wx')) return mine;+ const cur = await readLeaseAsync(path);+ if (cur === null) return (await writeAsync(path, rec, 'wx')) ? mine : null;+ const expired = cur === 'unparsable'+ ? await statAsync(path).then(s => now - s.mtimeMs > UNPARSABLE_GRACE_MS, () => true)+ : now > cur.expires_ms;+ if (!expired) return null;+ const tmp = `${path}.${randomBytes(6).toString('hex')}`;+ await writeAsync(tmp, rec, 'wx');+ await renameAsync(tmp, path);+ const after = await readLeaseAsync(path);+ return after !== null && after !== 'unparsable' && after.token === rec.token ? mine : null;}export async function releaseLeaseAsync(lease: Lease): Promise<boolean> {diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.tsindex b325c2b8ab..8fde21d5d1 100644--- a/test/skill-resolver.test.ts+++ b/test/skill-resolver.test.ts@@ -26,7 +26,7 @@ import { lexTerms } from '../src/core/skills/resolver/tokenize.ts';import { isAcknowledgement, mentionsSkill } from '../src/core/skills/resolver/rank.ts';import { estimateTokens } from '../src/core/skills/resolver/block.ts';import { acquireLease, holdsLease, releaseLease, tryAcquireLease } from '../src/core/skills/resolver/lock.ts';-import { commitSession, gcSessions, loadSession, sessionKey } from '../src/core/skills/resolver/session.ts';+import { commitSession, commitSessionAsync, gcSessions, loadSession, sessionKey } from '../src/core/skills/resolver/session.ts';import { catalogFile } from '../src/core/skills/resolver/paths.ts';import { STAT_CHECK_SLICE } from '../src/core/skills/resolver/resolve.ts';import { RACY_MTIME_MS } from '../src/core/skills/resolver/build.ts';@@ -587,6 +587,22 @@ describe('leases', () => {expect(releaseLease(next as never)).toBe(true);});+ test('an async session commit reclaims a lease its holder stranded at the deadline, and still yields to a live one', async () => {+ const home = tmp();+ const key = sessionKey('on', 'claude-code', 'session-a');+ const dir = join(home, 'skill-index', 'sessions');+ mkdirSync(dir, { recursive: true });+ const lock = join(dir, `${key}.json.lock`);+ const holder = (expires: number) => JSON.stringify({ v: 1, token: 'other', host: 'host-b', pid: 999_999, purpose: 'session-commit', generation: 0, acquired_ms: Date.now(), expires_ms: expires });+ const delta = { tokens: 10, suggested: ['x:a'], resuggested: [], reset: false };+ writeFileSync(lock, holder(Date.now() + 60_000));+ expect(await commitSessionAsync(home, key, delta)).toBe(false);+ writeFileSync(lock, holder(Date.now() - 1));+ expect(await commitSessionAsync(home, key, delta)).toBe(true);+ expect(loadSession(home, key)).toMatchObject({ turn: 1, spent: 10, last: { 'x:a': 1 } });+ expect(existsSync(lock)).toBe(false);+ });+test('an unparsable lease is held until its grace period passes', () => {const dir = tmp();const p = join(dir, 'lock');