mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-25 17:41:35 +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
@@ -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