Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 42 additions & 11 deletions src/agent/fork-adopt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,29 +479,47 @@ export function resetForkCapabilityCacheForTest(): void {
forkCapabilityCache.clear();
}

/** Old proxies have no fork endpoints at all; probing manifest keeps adoption
* off their request path (and avoids harmless 404 noise). Cached per base —
* register.base changes when the extension re-registers with a new proxy. */
export async function manifestForkCapable(base: string, fetchImpl?: typeof fetch): Promise<boolean> {
/** Capability-probe result. `definitive` separates two DIFFERENT "not capable"
* outcomes that must drive different retry policy (#4266 item ⑨):
* - definitive=true — the manifest was READ but does not advertise fork (an
* old proxy with no fork endpoints). Terminal: retrying can never change the
* answer, so adoption closes on the first probe (keeps such proxies off the
* request path and avoids repeated 404 noise).
* - definitive=false — the manifest could not be read RIGHT NOW (proxy still
* starting up / restarting / port changing: !res.ok, timeout, network error).
* Transient: the window stays open so a later request retries within the
* attempt budget instead of permanently retiring the child.
* Only definitive results are cached per base (register.base changes when the
* extension re-registers with a new proxy); a failed read is never cached, so a
* later probe re-hits the wire and self-heals once the proxy is reachable. */
type ForkCapabilityProbe = { capable: boolean; definitive: boolean };

export async function probeForkCapability(base: string, fetchImpl?: typeof fetch): Promise<ForkCapabilityProbe> {
const cached = forkCapabilityCache.get(base);
if (cached !== undefined) return cached;
if (cached !== undefined) return { capable: cached, definitive: true };
const doFetch = fetchImpl ?? fetch;
try {
const res = await doFetch(`${base}/__bili/plugin/manifest`, { signal: AbortSignal.timeout(5000) });
if (!res.ok) return false;
if (!res.ok) return { capable: false, definitive: false };
const manifest = await res.json() as { capabilities?: { fork?: { protocolVersion?: unknown } } };
// #2671 Phase 2b: fork protocol v2 proxies advertise protocolVersion 2;
// v1 proxies advertise 1. The adoption payload stays v1 during the
// transition (the server accepts both), so accept either major here.
const version = manifest.capabilities?.fork?.protocolVersion;
const capable = version === 1 || version === 2;
forkCapabilityCache.set(base, capable);
return capable;
return { capable, definitive: true };
} catch {
return false;
return { capable: false, definitive: false };
}
}

/** Boolean convenience kept for direct callers/tests: true only when the probe
* is capable (a failed read reports false, matching the pre-#4266 contract). */
export async function manifestForkCapable(base: string, fetchImpl?: typeof fetch): Promise<boolean> {
return (await probeForkCapability(base, fetchImpl)).capable;
}

export type ForkAdoptInput = { base: string; parent: string; child: string; body: unknown };

/** Per-host fork-adoption coordinator (#2399 stage 2): absorbs the bookkeeping
Expand Down Expand Up @@ -548,9 +566,22 @@ export function createForkAdopter(log: (line: string) => void, opts?: { maxAttem
done.add(input.child);
return;
}
if (!(await manifestForkCapable(input.base, opts?.fetchImpl))) {
log(`fork adoption for ${input.child} skipped — the proxy does not advertise the fork capability (#2399)`);
done.add(input.child);
const capability = await probeForkCapability(input.base, opts?.fetchImpl);
if (!capability.capable) {
if (capability.definitive) {
// Manifest read OK but fork not advertised (old proxy): terminal —
// retrying can never change the answer.
log(`fork adoption for ${input.child} skipped — the proxy does not advertise the fork capability (#2399)`);
done.add(input.child);
} else {
// Manifest unreadable right now (proxy starting/restarting/port
// changing) — transient. Leave the window open so a later request
// retries within the budget instead of permanently retiring the
// child (#4266 item ⑨).
const attempt = attempts.get(input.child) ?? 0;
log(`fork adoption for ${input.child} deferred — could not confirm fork capability yet (attempt ${attempt}/${maxAttempts}) (#2399/#4266)`);
if (attempt >= maxAttempts) done.add(input.child);
}
return;
}
const result = await tryForkAdoption({
Expand Down
39 changes: 33 additions & 6 deletions tests/pi-omp-fork-adopt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,18 +224,45 @@ test("createForkAdopter lets responses children reach the protocol — no termin
assert.ok(!lines.some((l) => l.includes("wire requests are not supported")), "no unsupported-wire skip for responses");
});

test("createForkAdopter never throws — an exploding network soft-degrades and closes the window", async () => {
test("createForkAdopter never throws — an unreachable proxy defers adoption until the cap (#4266 item ⑨)", async () => {
resetForkCapabilityCacheForTest();
const boom = (async () => { throw new Error("network exploded"); }) as unknown as typeof fetch;
const lines: string[] = [];
const adopter = createForkAdopter((l) => lines.push(l), { fetchImpl: boom });
// manifestForkCapable swallows the explosion (false = not capable), so the
// child degrades on the capability line and maybeAdopt never rejects.
// probeForkCapability swallows the explosion (capable=false, definitive=false),
// so the child DEFERS instead of terminating: maybeAdopt never rejects, and the
// window stays open for retries within the budget rather than closing on the
// first failed probe (the pre-fix behavior permanently retired the child).
await adopter.maybeAdopt(adoptInput());
assert.ok(lines.some((l) => l.includes("does not advertise the fork capability")), "the failure is logged, not thrown");
const callsBefore = lines.length;
assert.ok(lines.some((l) => l.includes("could not confirm fork capability yet")), "the unreachable probe is logged as deferred, not thrown");
await adopter.maybeAdopt(adoptInput());
assert.equal(lines.length, callsBefore, "the child is done after the first terminal outcome");
await adopter.maybeAdopt(adoptInput());
assert.equal(lines.filter((l) => l.includes("could not confirm fork capability yet")).length, 3, "each attempt within the cap re-probes");
const afterCap = lines.length;
await adopter.maybeAdopt(adoptInput());
assert.equal(lines.length, afterCap, "past the cap the window is closed");
});

test("createForkAdopter adopts once the proxy comes up — a failed probe does not retire the child (#4266 item ⑨)", async () => {
resetForkCapabilityCacheForTest();
const core = openaiBodyToCore(adoptInput().body as Record<string, unknown>)!;
const matchSnapshot = { match: snapshotRoute.match, respond: () => Response.json({ ok: true, protocolVersion: 1, status: "exact", parentRevision: hash("rev1"), orderHash: hash("full"), orderedMessages: [{ rawId: "a", ref: "m00001", identityHash: forkIdentityHashOf(core[0]!) }] }) };
// The proxy is down for the first request (manifest probe gets a 5xx / connection
// refused) and comes up before the second — exactly the host-startup window the
// production incident hit. Pre-fix the first failed probe marked the child done
// forever; now the window stays open and the second request adopts.
let manifestHits = 0;
const flakyManifest = { match: manifestRoute.match, respond: () => { manifestHits += 1; return manifestHits === 1 ? new Response("{}", { status: 503 }) : Response.json({ capabilities: { fork: { protocolVersion: 1 } } }); } };
const { fetchImpl, calls } = fakeFetchRouting([flakyManifest, matchSnapshot, forkRoute]);
const lines: string[] = [];
const adopter = createForkAdopter((l) => lines.push(l), { fetchImpl });
await adopter.maybeAdopt(adoptInput());
assert.ok(!lines.some((l) => l.includes("degraded")) && !lines.some((l) => l.includes("does not advertise")), "the transient probe failure neither degrades nor terminally skips");
assert.ok(lines.some((l) => l.includes("could not confirm fork capability yet")), "the first request defers");
assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 0, "no fork POST while the proxy is down");
await adopter.maybeAdopt(adoptInput());
assert.equal(calls.filter((c) => c.url.endsWith("/__bili/plugin/fork")).length, 1, "the next request adopts once the proxy is reachable");
assert.equal(lines.filter((l) => l.includes("could not confirm fork capability yet")).length, 1, "exactly one deferral — the retry succeeded");
});

test("createForkAdopter retries transient failures until the cap, then closes (#2403 review)", async () => {
Expand Down
Loading