Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Adopt superseded session bootstraps (#1165)

Rach Pradhana71826311b9c
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index cdca769a..3bd5a1ab 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -81,9 +81,10 @@ function mcpOffPath(): string {
// child's history; `dispose`/`dispose-page` reap children on tab close and
// page unload. Kept on globalThis so dev-server module reloads don't orphan
// running agents.
-const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>>; __graffAcpRetirements?: Map<string, Promise<void>>; __graffAcpShuttingDown?: boolean };
+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>>; __graffAcpBootstrapReplacements?: WeakMap<Promise<Slot>, Promise<Slot>>; __graffAcpRetirements?: Map<string, Promise<void>>; __graffAcpShuttingDown?: boolean };
const slots = (g.__graffAcpSlots ??= new Map<string, Slot>());
const bootstraps = (g.__graffAcpBootstraps ??= new Map<string, Promise<Slot>>());
+const bootstrapReplacements = (g.__graffAcpBootstrapReplacements ??= new WeakMap<Promise<Slot>, Promise<Slot>>());
const retirements = (g.__graffAcpRetirements ??= new Map<string, Promise<void>>());
const DEFAULT_CHAT = "default";
// Session names become a CLI argument and a filename under .graff/sessions.
@@ -258,8 +259,18 @@ function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
const live = slots.get(chat);
// Explicit changes can replace a stalled handshake. Ordinary concurrent
// requests must wait instead of killing the worker they are about to use.
- if (opts.reset || (live && !matchesBootstrap(live, opts))) bootstraps.delete(chat);
- return serializeBootstrap(bootstraps, chat, () => bootstrapNow(chat, opts));
+ const replacing = opts.reset || (live !== undefined && !matchesBootstrap(live, opts));
+ const previous = replacing ? bootstraps.get(chat) : undefined;
+ if (replacing) bootstraps.delete(chat);
+ const serialized = serializeBootstrap(bootstraps, chat, () => bootstrapNow(chat, opts));
+ const generation = bootstraps.get(chat);
+ const result = serialized.catch(error => {
+ const replacement = generation ? bootstrapReplacements.get(generation) : undefined;
+ if (replacement) return replacement;
+ throw error;
+ });
+ if (previous) bootstrapReplacements.set(previous, result);
+ return result;
}
async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
diff --git a/apps/native/lib/acp-route.test.ts b/apps/native/lib/acp-route.test.ts
index d061b39d..af9f8292 100644
--- a/apps/native/lib/acp-route.test.ts
+++ b/apps/native/lib/acp-route.test.ts
@@ -132,19 +132,20 @@ readline.createInterface({input:process.stdin}).on('line', line => {
}
}, 10000);
-test("an older failed bootstrap cannot retire a newer chat worker", async () => {
+test("superseded model bootstraps adopt the final replacement outcome", async () => {
const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-replacement-"));
const binary = path.join(temp, "agent.cjs");
const oldBin = process.env.GRAFF_BIN;
writeFileSync(binary, `#!/usr/bin/env node
const fs=require('node:fs');
-const stalled=process.argv.includes('stalled');
+const stalled=process.argv.some(arg=>arg.startsWith('stalled')),failed=process.argv.includes('failed');
fs.appendFileSync('starts',String(process.pid)+'\\n');
const send=value=>console.log(JSON.stringify(value));
require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
const req=JSON.parse(line);
if(req.method==='initialize') {
if(stalled) fs.writeFileSync('stalled',String(process.pid));
+ else if(failed) send({id:req.id,error:{code:-32603,message:'final bootstrap failure'}});
else send({id:req.id,result:{}});
}
if(req.method==='session/new') {
@@ -154,33 +155,61 @@ require('node:readline').createInterface({input:process.stdin}).on('line',line=>
}).on('close',()=>process.exit(0));
`, {mode:0o700});
const chat = `replacement-test-${path.basename(temp)}`;
- const call = (method: string, params = {}) => deadline(POST(new NextRequest("http://localhost/api/acp", {
- method:"POST",body:JSON.stringify({chat,method,params}),
+ const failedChat = `replacement-failure-${path.basename(temp)}`;
+ const callFor = (target: string, method: string, params = {}) => deadline(POST(new NextRequest("http://localhost/api/acp", {
+ method:"POST",body:JSON.stringify({chat:target,method,params}),
})), method);
+ const call = (method: string, params = {}) => callFor(chat, method, params);
+ const failedCall = (method: string, params = {}) => callFor(failedChat, method, params);
try {
process.env.GRAFF_BIN = binary;
- const older = call("bootstrap", {cwd:temp,model:"stalled",mcp:true});
- await deadline((async()=>{
+ const waitForStalled = (previous?: string) => deadline((async()=>{
for(;;) {
- try { readFileSync(path.join(temp,"stalled")); return; } catch {}
+ try {
+ const current = readFileSync(path.join(temp,"stalled"),"utf8");
+ if (current !== previous) return current;
+ } catch {}
await new Promise(resolve=>setTimeout(resolve,10));
}
})(),"stalled child ready");
- const newer = await call("bootstrap", {cwd:temp,model:"replacement",mcp:true});
- expect(newer.status).toBe(200);
- const failed = await older;
- expect(failed.status).toBe(502);
- expect((await failed.json()).error).toContain("ACP startup failed during initialize");
+ const older = call("bootstrap", {cwd:temp,model:"stalled-one",mcp:true});
+ const firstStalled = await waitForStalled();
+ const middle = call("bootstrap", {cwd:temp,model:"stalled-two",mcp:true});
+ await waitForStalled(firstStalled);
+ const newest = await call("bootstrap", {cwd:temp,model:"replacement",mcp:true});
+ expect(newest.status).toBe(200);
+ const [olderResult, middleResult] = await Promise.all([older, middle]);
+ expect(olderResult.status).toBe(200);
+ expect(middleResult.status).toBe(200);
+ expect((await olderResult.json()).sessionId).toBe("replacement");
+ expect((await middleResult.json()).sessionId).toBe("replacement");
const reused = await call("bootstrap", {cwd:temp,model:"replacement",mcp:true});
expect(reused.status).toBe(200);
expect((await reused.json()).sessionId).toBe("replacement");
expect((await call("initialize")).status).toBe(200);
const started = readFileSync(path.join(temp,"starts"),"utf8").trim().split("\n").map(Number);
- expect(started.length).toBe(2);
+ expect(started.length).toBe(3);
expect(()=>process.kill(started[0],0)).toThrow();
- expect(()=>process.kill(started[1],0)).not.toThrow();
+ expect(()=>process.kill(started[1],0)).toThrow();
+ expect(()=>process.kill(started[2],0)).not.toThrow();
+
+ const previousStalled = readFileSync(path.join(temp,"stalled"),"utf8");
+ const failedOlder = failedCall("bootstrap", {cwd:temp,model:"stalled-one",mcp:true});
+ const nextStalled = await waitForStalled(previousStalled);
+ const failedMiddle = failedCall("bootstrap", {cwd:temp,model:"stalled-two",mcp:true});
+ await waitForStalled(nextStalled);
+ const failedNewest = failedCall("bootstrap", {cwd:temp,model:"failed",mcp:true});
+ for (const response of await Promise.all([failedOlder, failedMiddle, failedNewest])) {
+ expect(response.status).toBe(502);
+ const error = (await response.json()).error as string;
+ expect(error).toContain("final bootstrap failure");
+ expect(error).not.toContain("worker retired");
+ }
+ const retry = await failedCall("bootstrap", {cwd:temp,model:"replacement",mcp:true});
+ expect(retry.status).toBe(200);
+ expect((await retry.json()).sessionId).toBe("replacement");
} finally {
- await call("dispose");
+ await Promise.all([call("dispose"), failedCall("dispose")]);
if(oldBin===undefined)delete process.env.GRAFF_BIN;else process.env.GRAFF_BIN=oldBin;
rmSync(temp,{recursive:true,force:true});
}