mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-23 08:31:44 +01:00
Four tests and two tools stop failing at random: gate-ahead worktrees and the gbrain MCP probe (GST-3543) (#4710)
Two gate-ahead preparations for one PR no longer fail each other, and `gstack-gbrain-mcp-verify` no longer misreads a valid SSE reply as broken. Both turned up in the daily flaky-test pass from CI runs that failed once and passed on retry. Two test fixtures that raced on timing are fixed too. Nothing to do for users; the version is written at merge. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=testing Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice Review-Finding: p1/adversarial-native#1 reader=adversarial-native Review-Finding: p1/adversarial-native#2 reader=adversarial-native Review-Finding: p1/adversarial-native#3 reader=adversarial-native Review-Finding: p1/adversarial-native#5 reader=adversarial-native Also: the fixture trace test's control looks for the push by name, which the Windows runner spells differently (windows-scoped-shard, run 45036384878). Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#3 reader=red-team
This commit is contained in:
1 parent
4ae9ec7b00
commit
5962f0d4f3
9 files changed
+305
-18
No files matched your search
@@ -110,7 +110,7 @@ case "$HTTP_CODE" in
|
||||
exit 1
|
||||
;;
|
||||
500)
|
||||
if echo "$BODY" | grep -qiE '"(error_description|message)":[[:space:]]*"[^"]*(auth|token|unauthorized)' 2>/dev/null; then
|
||||
if grep -qiE '"(error_description|message)":[[:space:]]*"[^"]*(auth|token|unauthorized)' <<<"$BODY" 2>/dev/null; then
|
||||
emit "auth" "" "" "AUTH" "rotate token on the brain host, re-run /setup-gbrain (HTTP 500 stale-token shape)" false "$BODY"
|
||||
exit 1
|
||||
fi
|
||||
@@ -129,8 +129,11 @@ esac
|
||||
# --- 2xx path: body may be JSON or SSE-wrapped JSON. Strip SSE if present. ---
|
||||
# MCP servers return SSE format: `event: message\ndata: {...}\n\n`. Extract
|
||||
# just the JSON payload from the data: line, falling back to the body as-is.
|
||||
if echo "$BODY" | head -1 | grep -q '^event:'; then
|
||||
JSON_BODY=$(echo "$BODY" | sed -n 's/^data: //p' | head -1)
|
||||
# No early-exit pipes here: under pipefail, `echo | head -1 | grep -q` fails with
|
||||
# SIGPIPE when grep or head exits before echo finishes writing, so a valid SSE
|
||||
# body was read as plain JSON and jq's parse error (exit 5) ended the script.
|
||||
if [ "${BODY#event:}" != "$BODY" ]; then
|
||||
JSON_BODY=$(sed -n '/^data: /{s/^data: //p;q;}' <<<"$BODY")
|
||||
else
|
||||
JSON_BODY="$BODY"
|
||||
fi
|
||||
@@ -177,8 +180,8 @@ set -e
|
||||
|
||||
if [ "$TOOLS_EXIT" -eq 0 ]; then
|
||||
TOOLS_BODY=$(cat "$TOOLS_BODY_FILE" 2>/dev/null || echo "")
|
||||
if echo "$TOOLS_BODY" | head -1 | grep -q '^event:'; then
|
||||
TOOLS_JSON=$(echo "$TOOLS_BODY" | sed -n 's/^data: //p' | head -1)
|
||||
if [ "${TOOLS_BODY#event:}" != "$TOOLS_BODY" ]; then
|
||||
TOOLS_JSON=$(sed -n '/^data: /{s/^data: //p;q;}' <<<"$TOOLS_BODY")
|
||||
else
|
||||
TOOLS_JSON="$TOOLS_BODY"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
**`gstack-gbrain-mcp-verify` no longer misreads a large or slow-to-write SSE reply as broken.** It checked the first line through `echo | head -1 | grep -q` under `pipefail`, which fails with SIGPIPE when a reader exits early, so a valid reply could end the probe with jq's exit 5. Two gate-ahead preparations for one PR no longer fail each other with `failed to read .git/worktrees/worktree/commondir: Success`: the worktree adds and removals of the version stamp and the gate-ahead queue now take one lock per repository. (GST-3543)
|
||||
@@ -21,6 +21,7 @@ import { spawnSync } from '../../lib/spawn-sync';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { mergeChangelogs } from '../../lib/changelog-check';
|
||||
import { removeWorktree } from '../../lib/git-worktree-lock';
|
||||
import { ensureTmpExcluded, restamp, versionFiles } from '../../lib/restamp';
|
||||
import type { ResultCodeName } from '../../lib/result-codes';
|
||||
import type { ShipPolicy } from '../../lib/ship-policy';
|
||||
@@ -180,9 +181,8 @@ export function prepareGateAhead(o: PrepareOptions): { record: AttemptRecord; fi
|
||||
}
|
||||
const ga = r.gateAhead;
|
||||
const drop = (code: ResultCodeName, message: string): QueueFailure => {
|
||||
git(o.repoRoot, ['worktree', 'remove', '--force', worktree]);
|
||||
removeWorktree(o.repoRoot, worktree);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
git(o.repoRoot, ['worktree', 'prune']);
|
||||
return { code, message };
|
||||
};
|
||||
const mergeTree = git(o.repoRoot, ['rev-parse', `${ga.gated_head}^^{tree}`]).out;
|
||||
@@ -234,8 +234,7 @@ export function recordGateAhead(o: RecordOptions): { record: AttemptRecord; file
|
||||
rec.result = { exit: o.exit, log: path.relative(o.repoRoot, kept), log_sha256: logSha, recorded_at: (o.now ?? new Date()).toISOString() };
|
||||
rec.state = 'recorded';
|
||||
writeJsonAtomic(file, rec);
|
||||
git(o.repoRoot, ['worktree', 'remove', '--force', rec.worktree]);
|
||||
removeWorktree(o.repoRoot, rec.worktree);
|
||||
fs.rmSync(path.dirname(rec.worktree), { recursive: true, force: true });
|
||||
git(o.repoRoot, ['worktree', 'prune']);
|
||||
return { record: rec, file, current, repeated: false };
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* gstack-restamp's and the gate-ahead queue's `git worktree add` and removal run
|
||||
* one at a time per repository. While git adds a worktree it reads every
|
||||
* sibling's commondir, and a concurrent add leaves its own commondir empty for
|
||||
* an instant, so the other add dies with "failed to read
|
||||
* .git/worktrees/<name>/commondir: Success". Two gate-ahead preparations for one
|
||||
* PR are concurrent by design and hit this on CI (test/gstack-ship-queue.test.ts,
|
||||
* Trunk e3ed3abf). Other worktree callers in crew/lib run one at a time inside
|
||||
* their own command and do not take this lock.
|
||||
*
|
||||
* The lock is a pid file in the repository's git common dir, published with a
|
||||
* hard link so it is never seen half-written and dated the moment it is
|
||||
* published. Every hold is one git call with a 60 s timeout, so a lock whose
|
||||
* holder is dead, whose pid is this process's own, or that is older than STALE_MS (a
|
||||
* killed holder's pid can be reused after a restart) is stale. Only one waiter
|
||||
* at a time may remove a stale lock (the takeover directory), and it removes the
|
||||
* lock only if the file there is still the one it judged stale and still stale.
|
||||
* The lock only narrows a race: when it cannot be taken (no hard links, an
|
||||
* unwritable common dir, or 3 x STALE_MS of waiting) the command runs unlocked,
|
||||
* as it did before the lock existed, instead of failing.
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { spawnSync } from './spawn-sync';
|
||||
|
||||
const STALE_MS = 120_000;
|
||||
const TAKEOVER_STALE_MS = 10_000;
|
||||
const LOCK_NAME = 'gstack-worktree.lock';
|
||||
|
||||
type GitResult = { ok: boolean; out: string; err: string; status: number | null };
|
||||
type Held = { ino: number; mtimeMs: number; pid: number };
|
||||
|
||||
function git(cwd: string, args: string[]): GitResult {
|
||||
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000 });
|
||||
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
|
||||
}
|
||||
|
||||
function holderAlive(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return false;
|
||||
try { process.kill(pid, 0); return true; } catch (e: any) { return e?.code === 'EPERM'; }
|
||||
}
|
||||
|
||||
function readHeld(lock: string): Held | null {
|
||||
try {
|
||||
const fd = fs.openSync(lock, 'r');
|
||||
try { const st = fs.fstatSync(fd); return { ino: st.ino, mtimeMs: st.mtimeMs, pid: Number(fs.readFileSync(fd, 'utf8')) }; } finally { fs.closeSync(fd); }
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
const isStale = (h: Held) => h.pid === process.pid || !holderAlive(h.pid) || Date.now() - h.mtimeMs >= STALE_MS;
|
||||
const pause = () => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
||||
|
||||
function takeOverStale(lock: string, judged: Held): void {
|
||||
const gate = `${lock}.takeover`;
|
||||
try { fs.mkdirSync(gate); } catch (e: any) {
|
||||
if (e?.code !== 'EEXIST') throw e;
|
||||
try { if (Date.now() - fs.statSync(gate).mtimeMs >= TAKEOVER_STALE_MS) fs.rmSync(gate, { recursive: true, force: true }); } catch { /* gone */ }
|
||||
pause();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const now = readHeld(lock);
|
||||
if (now && now.ino === judged.ino && isStale(now)) fs.rmSync(lock, { force: true });
|
||||
} finally { fs.rmSync(gate, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
export function withWorktreeLock<T>(repoRoot: string, fn: () => T): T {
|
||||
const common = git(repoRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
||||
if (!common.ok) return fn();
|
||||
const lock = path.join(common.out, LOCK_NAME);
|
||||
const mine = acquire(lock);
|
||||
if (mine === null) return fn();
|
||||
try { return fn(); } finally {
|
||||
try { if (fs.statSync(lock).ino === mine) fs.rmSync(lock, { force: true }); } catch { /* already gone */ }
|
||||
}
|
||||
}
|
||||
|
||||
function acquire(lock: string): number | null {
|
||||
const staged = `${lock}.${process.pid}`;
|
||||
const giveUpAt = Date.now() + 3 * STALE_MS;
|
||||
try {
|
||||
fs.writeFileSync(staged, String(process.pid));
|
||||
for (;;) {
|
||||
const now = new Date();
|
||||
fs.utimesSync(staged, now, now);
|
||||
try { fs.linkSync(staged, lock); return fs.statSync(lock).ino; } catch (e: any) {
|
||||
if (e?.code !== 'EEXIST' || Date.now() >= giveUpAt) return null;
|
||||
}
|
||||
const held = readHeld(lock);
|
||||
if (held && isStale(held)) takeOverStale(lock, held); else pause();
|
||||
}
|
||||
} catch { return null; } finally {
|
||||
try { fs.rmSync(staged, { force: true }); } catch { /* not ours to remove */ }
|
||||
}
|
||||
}
|
||||
|
||||
export function addWorktree(repoRoot: string, dir: string, commit: string): GitResult {
|
||||
return withWorktreeLock(repoRoot, () => git(repoRoot, ['worktree', 'add', '--detach', '-q', dir, commit]));
|
||||
}
|
||||
|
||||
export function removeWorktree(repoRoot: string, dir: string): void {
|
||||
withWorktreeLock(repoRoot, () => git(repoRoot, ['worktree', 'remove', '--force', dir]));
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
withWorktreeLock(repoRoot, () => git(repoRoot, ['worktree', 'prune']));
|
||||
}
|
||||
+3
-8
@@ -26,6 +26,7 @@ import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { bunIsolationArgs } from './bun-isolation';
|
||||
import { checkChangelog, mergeChangelogs, parseChangelog, reheadChangelog } from './changelog-check';
|
||||
import { addWorktree, removeWorktree } from './git-worktree-lock';
|
||||
import { effectiveBump, foldIntoUnreleased, readFragments, type FragmentSet } from './changelog-fragments';
|
||||
import { releaseRefusal } from '../crew/lib/restamp-release';
|
||||
import { type ResultCodeName } from './result-codes';
|
||||
@@ -662,12 +663,6 @@ function fragmentsOf(o: RestampOptions, dir: string, changelog: string | null):
|
||||
return set;
|
||||
}
|
||||
|
||||
function removeWorktree(repoRoot: string, dir: string): void {
|
||||
git(repoRoot, ['worktree', 'remove', '--force', dir]);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
git(repoRoot, ['worktree', 'prune']);
|
||||
}
|
||||
|
||||
export function restamp(o: RestampOptions): RestampResult {
|
||||
const stages: StageRecord[] = [];
|
||||
let staging: string | null = null;
|
||||
@@ -711,7 +706,7 @@ export function restamp(o: RestampOptions): RestampResult {
|
||||
const wtree = fp.tree;
|
||||
staging = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-restamp-staging-'));
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
const add = git(o.repoRoot, ['worktree', 'add', '--detach', '-q', staging, 'HEAD']);
|
||||
const add = addWorktree(o.repoRoot, staging, 'HEAD');
|
||||
if (!add.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot create the staging worktree: ${add.err}; nothing written`);
|
||||
const seed = git(staging, ['read-tree', '--reset', '-u', wtree]);
|
||||
if (!seed.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot seed the staging worktree: ${seed.err}; nothing written`);
|
||||
@@ -752,7 +747,7 @@ function gateAhead(o: RestampOptions, plan: Plan, stages: StageRecord[], common:
|
||||
const dir = o.gateWorktree ?? path.join(o.repoRoot, '.gstack', 'tmp', 'gate-ahead-worktree');
|
||||
if (fs.existsSync(dir)) removeWorktree(o.repoRoot, dir);
|
||||
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
||||
const add = git(o.repoRoot, ['worktree', 'add', '--detach', '-q', dir, branchHead]);
|
||||
const add = addWorktree(o.repoRoot, dir, branchHead);
|
||||
if (!add.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot create the gate-ahead worktree: ${add.err}; nothing written`);
|
||||
const env = { ...(o.env ?? process.env), GIT_AUTHOR_NAME: 'gstack-restamp', GIT_AUTHOR_EMAIL: 'restamp@gstack.local', GIT_COMMITTER_NAME: 'gstack-restamp', GIT_COMMITTER_EMAIL: 'restamp@gstack.local' };
|
||||
const merge = git(dir, ['-c', 'commit.gpgsign=false', 'merge', '--no-ff', '--no-edit', '-q', pred.head], env);
|
||||
|
||||
@@ -24,6 +24,7 @@ function build(root: string): { head: string } {
|
||||
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000 });
|
||||
fs.mkdirSync(work);
|
||||
git(work, 'init', '-q', '-b', 'main');
|
||||
for (const dir of [origin, work]) for (const [key, value] of [['maintenance.auto', 'false'], ['gc.auto', '0']]) git(dir, 'config', key, value!);
|
||||
git(work, 'remote', 'add', 'origin', origin);
|
||||
fs.writeFileSync(path.join(work, 'a.txt'), 'base\n');
|
||||
git(work, 'add', '-A');
|
||||
@@ -90,6 +91,23 @@ describe('git fixture template', () => {
|
||||
} finally { for (const s of skipped) s.dispose(); for (const { t } of leaks) t.dispose(); }
|
||||
});
|
||||
|
||||
test('the template build starts no detached git maintenance, which would change the template while a copy walks it (Trunk 3a4e1509)', () => {
|
||||
const traceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-fixture-trace-'));
|
||||
roots.push(traceDir);
|
||||
const trace = path.join(traceDir, 'trace2.json');
|
||||
const traced = gitFixtureTemplate({ prefix: 'gstack-fixture-template-maint-', build: (root) => {
|
||||
process.env.GIT_TRACE2_EVENT = trace;
|
||||
try { return build(root); } finally { delete process.env.GIT_TRACE2_EVENT; }
|
||||
}, rebind: (copy, tpl) => rebindGitDir(path.join(copy, 'work', '.git'), tpl, copy) });
|
||||
try {
|
||||
roots.push(traced.copy().root);
|
||||
const spawned = fs.readFileSync(trace, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l) as { event: string; argv?: string[] })
|
||||
.filter(e => e.event === 'start').map(e => e.argv!);
|
||||
expect(spawned.some(argv => argv.includes('push'))).toBe(true);
|
||||
expect(spawned.filter(argv => argv.includes('maintenance') || argv.includes('gc'))).toEqual([]);
|
||||
} finally { traced.dispose(); }
|
||||
});
|
||||
|
||||
test('native, forward-slash, backslash-escaped and Git Bash spellings are each rewritten, and each one left behind is found', () => {
|
||||
const to = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-fixture-spellings-'));
|
||||
roots.push(to);
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* lib/git-worktree-lock.ts: gstack's own worktree adds and removals take one
|
||||
* lock per repository, because concurrent `git worktree add`s can read each
|
||||
* other's half-written commondir ("failed to read
|
||||
* .git/worktrees/worktree/commondir: Success", Trunk e3ed3abf).
|
||||
*/
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const LIB = path.resolve(import.meta.dir, '..', 'lib', 'git-worktree-lock.ts');
|
||||
const roots: string[] = [];
|
||||
const children: ChildProcess[] = [];
|
||||
afterEach(() => {
|
||||
for (const c of children.splice(0)) c.kill('SIGKILL');
|
||||
for (const r of roots.splice(0)) fs.rmSync(r, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function repo(): { root: string; lock: string } {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-worktree-lock-'));
|
||||
roots.push(root);
|
||||
const git = (...args: string[]) => spawnSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'commit.gpgsign=false', ...args], { cwd: root, encoding: 'utf8', timeout: 30_000 });
|
||||
git('init', '-q', '-b', 'main');
|
||||
git('config', 'maintenance.auto', 'false');
|
||||
git('commit', '-q', '--allow-empty', '-m', 'base');
|
||||
return { root, lock: path.join(root, '.git', 'gstack-worktree.lock') };
|
||||
}
|
||||
|
||||
function adder(root: string, dirs: string[]): ChildProcess {
|
||||
const script = `import { addWorktree } from ${JSON.stringify(LIB)};
|
||||
for (const dir of ${JSON.stringify(dirs)}) { const r = addWorktree(${JSON.stringify(root)}, dir, 'HEAD'); if (!r.ok) { console.error(r.err); process.exit(1); } }`;
|
||||
const child = spawn(process.execPath, ['-e', script], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
children.push(child);
|
||||
return child;
|
||||
}
|
||||
const exited = (c: ChildProcess) => new Promise<{ code: number | null; err: string }>(resolve => {
|
||||
let err = '';
|
||||
c.stderr?.on('data', d => { err += d; });
|
||||
c.on('exit', code => resolve({ code, err }));
|
||||
});
|
||||
const holder = () => {
|
||||
const c = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60_000)'], { stdio: 'ignore' });
|
||||
children.push(c);
|
||||
return c;
|
||||
};
|
||||
|
||||
test('an add waits while a live process holds the lock, then runs once that holder is gone', async () => {
|
||||
const { root, lock } = repo();
|
||||
const live = holder();
|
||||
fs.writeFileSync(lock, String(live.pid));
|
||||
const dir = path.join(root, 'attempt', 'worktree');
|
||||
const add = adder(root, [dir]);
|
||||
const done = exited(add);
|
||||
await Bun.sleep(1500);
|
||||
expect(fs.existsSync(path.join(dir, '.git'))).toBe(false);
|
||||
live.kill('SIGKILL');
|
||||
const r = await done;
|
||||
expect(r, r.err).toMatchObject({ code: 0 });
|
||||
expect(fs.existsSync(path.join(dir, '.git'))).toBe(true);
|
||||
expect(fs.existsSync(lock)).toBe(false);
|
||||
}, 30_000);
|
||||
|
||||
test('a lock left by a dead process is taken over at once', () => {
|
||||
const { root, lock } = repo();
|
||||
const dead = spawnSync(process.execPath, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8', timeout: 30_000 }).stdout;
|
||||
fs.writeFileSync(lock, dead);
|
||||
const { addWorktree } = require(LIB) as typeof import('../lib/git-worktree-lock');
|
||||
const r = addWorktree(root, path.join(root, 'wt'), 'HEAD');
|
||||
expect(r.ok, r.err).toBe(true);
|
||||
expect(fs.existsSync(lock)).toBe(false);
|
||||
});
|
||||
|
||||
test('a lock older than the longest hold is taken over even when its pid belongs to a live process (pid reuse)', () => {
|
||||
const { root, lock } = repo();
|
||||
const live = holder();
|
||||
fs.writeFileSync(lock, String(live.pid));
|
||||
const old = (Date.now() - 10 * 60_000) / 1000;
|
||||
fs.utimesSync(lock, old, old);
|
||||
const { addWorktree } = require(LIB) as typeof import('../lib/git-worktree-lock');
|
||||
const started = Date.now();
|
||||
const r = addWorktree(root, path.join(root, 'wt'), 'HEAD');
|
||||
expect(r.ok, r.err).toBe(true);
|
||||
expect(Date.now() - started).toBeLessThan(10_000);
|
||||
expect(fs.existsSync(lock)).toBe(false);
|
||||
});
|
||||
|
||||
test('contenders that find a dead holder\'s lock never hold the lock at the same time', async () => {
|
||||
const { root, lock } = repo();
|
||||
const dead = spawnSync(process.execPath, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8', timeout: 30_000 }).stdout;
|
||||
fs.writeFileSync(lock, dead);
|
||||
const log = path.join(root, 'holds.log');
|
||||
const script = `import fs from 'node:fs'; import { withWorktreeLock } from ${JSON.stringify(LIB)};
|
||||
for (let i = 0; i < 3; i++) withWorktreeLock(${JSON.stringify(root)}, () => { const t = Date.now(); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30); fs.appendFileSync(${JSON.stringify(log)}, t + ' ' + Date.now() + '\\n'); });`;
|
||||
const procs = Array.from({ length: 6 }, () => { const c = spawn(process.execPath, ['-e', script], { stdio: ['ignore', 'ignore', 'pipe'] }); children.push(c); return c; });
|
||||
const results = await Promise.all(procs.map(exited));
|
||||
for (const r of results) expect(r, r.err).toMatchObject({ code: 0 });
|
||||
const holds = fs.readFileSync(log, 'utf8').trim().split('\n').map(l => l.split(' ').map(Number) as [number, number]).sort((a, b) => a[0] - b[0]);
|
||||
expect(holds).toHaveLength(18);
|
||||
for (let i = 1; i < holds.length; i++) expect(holds[i]![0]).toBeGreaterThanOrEqual(holds[i - 1]![1]);
|
||||
}, 60_000);
|
||||
|
||||
test('a lock is dated when it is taken, so time spent waiting never makes a live holder look stale', async () => {
|
||||
const { root, lock } = repo();
|
||||
const live = holder();
|
||||
fs.writeFileSync(lock, String(live.pid));
|
||||
const out = path.join(root, 'acquired.json');
|
||||
const script = `import fs from 'node:fs'; import { withWorktreeLock } from ${JSON.stringify(LIB)};
|
||||
withWorktreeLock(${JSON.stringify(root)}, () => fs.writeFileSync(${JSON.stringify(out)}, JSON.stringify({ now: Date.now(), mtimeMs: fs.statSync(${JSON.stringify(lock)}).mtimeMs })));`;
|
||||
const child = spawn(process.execPath, ['-e', script], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
children.push(child);
|
||||
const done = exited(child);
|
||||
await Bun.sleep(1500);
|
||||
live.kill('SIGKILL');
|
||||
const r = await done;
|
||||
expect(r, r.err).toMatchObject({ code: 0 });
|
||||
const { now, mtimeMs } = JSON.parse(fs.readFileSync(out, 'utf8')) as { now: number; mtimeMs: number };
|
||||
expect(now - mtimeMs).toBeLessThan(1000);
|
||||
}, 30_000);
|
||||
|
||||
test('a lock naming this process\'s own pid is a leftover from a recycled pid and is taken over at once', () => {
|
||||
const { root, lock } = repo();
|
||||
fs.writeFileSync(lock, String(process.pid));
|
||||
const { addWorktree } = require(LIB) as typeof import('../lib/git-worktree-lock');
|
||||
const started = Date.now();
|
||||
const r = addWorktree(root, path.join(root, 'wt'), 'HEAD');
|
||||
expect(r.ok, r.err).toBe(true);
|
||||
expect(Date.now() - started).toBeLessThan(10_000);
|
||||
expect(fs.existsSync(lock)).toBe(false);
|
||||
});
|
||||
|
||||
test('an add still runs, unlocked, when the lock cannot be written', () => {
|
||||
const { root, lock } = repo();
|
||||
fs.mkdirSync(`${lock}.${process.pid}`);
|
||||
const { addWorktree } = require(LIB) as typeof import('../lib/git-worktree-lock');
|
||||
const r = addWorktree(root, path.join(root, 'wt'), 'HEAD');
|
||||
expect(r.ok, r.err).toBe(true);
|
||||
expect(fs.existsSync(lock)).toBe(false);
|
||||
});
|
||||
|
||||
test('concurrent adds of worktrees that share one basename all succeed', async () => {
|
||||
const { root } = repo();
|
||||
const procs = Array.from({ length: 6 }, (_, p) => adder(root, Array.from({ length: 8 }, (_, i) => path.join(root, `p${p}-${i}`, 'worktree'))));
|
||||
const results = await Promise.all(procs.map(exited));
|
||||
for (const r of results) expect(r, r.err).toMatchObject({ code: 0 });
|
||||
const list = spawnSync('git', ['worktree', 'list', '--porcelain'], { cwd: root, encoding: 'utf8', timeout: 30_000 }).stdout;
|
||||
expect(list.split('\n').filter(l => l.startsWith('worktree ')).length).toBe(1 + 6 * 8);
|
||||
}, 120_000);
|
||||
@@ -144,6 +144,20 @@ describe('gstack-gbrain-mcp-verify', () => {
|
||||
expect(j.sources_add_url_supported).toBe(true);
|
||||
});
|
||||
|
||||
test('SUCCESS: an SSE body larger than a pipe buffer is still read as SSE (pipefail SIGPIPE, Trunk 1afdd260)', () => {
|
||||
const pad = 'x'.repeat(70_000);
|
||||
const initBody =
|
||||
'event: message\ndata: {"result":{"protocolVersion":"2024-11-05","capabilities":{"tools":{}},"serverInfo":{"name":"gbrain","version":"0.99.0"}},"jsonrpc":"2.0","id":1}\n\nevent: message\ndata: {"jsonrpc":"2.0","method":"notifications/message","params":{"data":"' + pad + '"}}';
|
||||
const toolsBody = 'event: message\ndata: {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"search"},{"name":"sources_add"}],"padding":"' + pad + '"}}\n\nevent: message\ndata: {"padding":"' + pad + '"}';
|
||||
makeFakeCurl({ httpCode: '200', bodyOnInit: initBody, bodyOnTools: toolsBody });
|
||||
|
||||
const r = runVerify('faketoken', 'https://example.com/mcp');
|
||||
expect(r.code, r.stderr).toBe(0);
|
||||
const j = JSON.parse(r.stdout);
|
||||
expect(j.server_version).toBe('0.99.0');
|
||||
expect(j.sources_add_url_supported).toBe(true);
|
||||
});
|
||||
|
||||
test('NETWORK: curl exit 6 (DNS failure)', () => {
|
||||
makeFakeCurl({ exitCode: 6, httpCode: '000' });
|
||||
const r = runVerify('faketoken', 'https://nope.invalid/mcp');
|
||||
|
||||
@@ -146,10 +146,13 @@ test('late SDK completion cannot run metric/assertion/snapshot validation', asyn
|
||||
const completions: Array<(result: AgentSdkResult) => void> = [];
|
||||
let metrics = 0; let validations = 0; let records = 0;
|
||||
try {
|
||||
await runOverlayCaseLifecycle({ fixture, workMs: 15, graceMs: 5,
|
||||
// Both arms must reach invoke() before the work deadline; 15 ms was missed when a loaded runner stalled the first
|
||||
// trial's setup (Trunk 5a3199f2: Expected 3, Received 2 records).
|
||||
await runOverlayCaseLifecycle({ fixture, workMs: 250, graceMs: 5,
|
||||
execute: (_arm, _index, _signal, active, deadlineAt) => runOverlayTrial({ fixture: { ...fixture, metric: () => { metrics++; return 3; }, verify: () => { validations++; } }, directory: dir, isActive: active, deadlineAt, invoke: () => new Promise(resolve => completions.push(resolve)), record: () => {} }),
|
||||
recordTrial: () => { records++; }, recordAggregate: () => { records++; }, cleanup: async () => {},
|
||||
});
|
||||
expect(completions).toHaveLength(2);
|
||||
completions.forEach(resolve => resolve(sdkResult())); await Bun.sleep(10);
|
||||
expect(metrics).toBe(0); expect(validations).toBe(0); expect(records).toBe(3);
|
||||
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
||||
|
||||
Reference in new issue
Block a user