Skip to content
Merged
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
17 changes: 14 additions & 3 deletions bin/opencode-route-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,14 @@ const leafCredential = (cfg, providerId) => {
};
const hasCredential = (cfg, providerId) => Boolean(leafCredential(cfg, providerId));

// (provider,model) pairs demoted by the doctrine: >=3 quota failures
// (quota detail recorded, or a RateLimit tag) inside the last 4 hours.
// (provider,model) pairs demoted by the doctrine: >=3 qualifying
// failures (quota detail recorded, a RateLimit tag, or an
// Authentication tag) inside the last 4 hours, counting only the
// current failure run: a success on the pair clears the run and
// lifts the demotion. The Authentication arm is #8048: a leg whose
// credential is dead fails 100% with provider.auth and never
// carried quota detail, so the quota-only filter never demoted it
// and it stayed first-choice while killing sessions.
const demotedPairs = () => {
let db = null;
try {
Expand All @@ -344,7 +350,12 @@ const demotedPairs = () => {
.prepare(
`SELECT provider_id, model_id FROM route_attempt
WHERE time_started > ? AND outcome != 'success'
AND (quota IS NOT NULL OR error_tag = 'RateLimit')
AND (quota IS NOT NULL OR error_tag IN ('RateLimit', 'Authentication'))
AND time_started > COALESCE(
(SELECT MAX(s.time_started) FROM route_attempt s
WHERE s.provider_id = route_attempt.provider_id
AND s.model_id = route_attempt.model_id
AND s.outcome = 'success'), 0)
GROUP BY provider_id, model_id HAVING COUNT(*) >= ?`,
)
.all(Date.now() - DEMOTE_WINDOW_MS, DEMOTE_THRESHOLD);
Expand Down
99 changes: 97 additions & 2 deletions bin/opencode-route-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const freePort = () =>
const makeLeaf = (name, expectedKey) => {
const leaf = {
name,
mode: "ok", // ok | rate
mode: "ok", // ok | rate | auth
last: null,
hits: 0,
server: null,
Expand All @@ -54,6 +54,12 @@ const makeLeaf = (name, expectedKey) => {
res.writeHead(401, { "content-type": "application/json" });
return res.end(JSON.stringify({ error: { message: "bad key" } }));
}
if (leaf.mode === "auth") {
res.writeHead(401, { "content-type": "application/json" });
return res.end(
JSON.stringify({ error: { message: "expired credential" } }),
);
}
if (leaf.mode === "rate") {
res.writeHead(429, {
"content-type": "application/json",
Expand Down Expand Up @@ -223,6 +229,7 @@ const startProxy = async (arg = {}) => {
"t-group-weighted": { "selection": "ordered", "targets": ["grp-weighted/m-g"] },
"t-group-skip": { "selection": "ordered", "targets": ["grp-ordered/m-a"] },
"t-openai-default": { "selection": "ordered", "targets": ["openai/m-gpt"] },
"t-a-only": { "selection": "ordered", "targets": ["leafA/m-a"] },
},
},
}`,
Expand Down Expand Up @@ -264,7 +271,7 @@ const startProxy = async (arg = {}) => {
const ro = new DatabaseSync(dbPath, { readOnly: true });
const rows = ro
.prepare(
"SELECT route_id, provider_id, model_id, variant, outcome, error_tag, session_id, failed_over_to, output_started FROM route_attempt ORDER BY id",
"SELECT route_id, provider_id, model_id, variant, outcome, error_tag, error_status, quota, session_id, failed_over_to, output_started FROM route_attempt ORDER BY id",
)
.all();
ro.close();
Expand Down Expand Up @@ -407,6 +414,94 @@ test("429 on the first leaf fails over; both attempts recorded", async () => {
}
});

test("repeated authentication failures demote a leaf until it succeeds", async () => {
const p = await startProxy();
try {
p.leafA.mode = "auth";
for (let i = 0; i < 3; i++) {
const res = await p.post({ model: "opencode-route/t-ordered", messages: MSGS });
assert.equal(res.status, 200);
assert.equal((await res.json()).choices[0].message.content, "LEAF-B");
}

const beforeDemotion = p.attempts();
const authFailures = beforeDemotion.filter((row) => row.provider_id === "leafA");
assert.equal(authFailures.length, 3);
assert.ok(authFailures.every((row) => row.outcome === "failure"));
assert.ok(authFailures.every((row) => row.error_tag === "Authentication"));
assert.ok(authFailures.every((row) => row.error_status === 401));
assert.ok(authFailures.every((row) => row.quota === null));

// Three prior auth failures move leafA behind leafB for the next turn.
const fallback = await p.post({ model: "opencode-route/t-ordered", messages: MSGS });
assert.equal(fallback.status, 200);
assert.equal((await fallback.json()).choices[0].message.content, "LEAF-B");
assert.equal(
p.attempts().filter((row) => row.provider_id === "leafA").length,
3,
);

// A success on the demoted pair clears the failure run.
p.leafA.mode = "ok";
const recovered = await p.post({ model: "opencode-route/t-a-only", messages: MSGS });
assert.equal(recovered.status, 200);
const primaryAgain = await p.post({ model: "opencode-route/t-ordered", messages: MSGS });
assert.equal(primaryAgain.status, 200);
assert.equal(
(await primaryAgain.json()).choices[0].message.content,
"LEAF-A",
);
} finally {
await p.cleanup();
}
});

test("RateLimit-only failures still demote a leaf until its next success", async () => {
const p = await startProxy();
try {
const db = new DatabaseSync(p.dbPath);
const insert = db.prepare(
`INSERT INTO route_attempt
(time_started, time_ended, route_id, provider_id, model_id, outcome, error_tag, output_started)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
);
const now = Date.now();
for (let i = 0; i < 3; i++) {
insert.run(
now - 1000 + i,
now - 999 + i,
"t-ordered",
"leafA",
"m-a",
"failure",
"RateLimit",
0,
);
}
db.close();

const fallback = await p.post({ model: "opencode-route/t-ordered", messages: MSGS });
assert.equal(fallback.status, 200);
assert.equal((await fallback.json()).choices[0].message.content, "LEAF-B");
assert.equal(
p.attempts().filter((row) => row.provider_id === "leafA").length,
3,
);

p.leafA.mode = "ok";
const recovered = await p.post({ model: "opencode-route/t-a-only", messages: MSGS });
assert.equal(recovered.status, 200);
const primaryAgain = await p.post({ model: "opencode-route/t-ordered", messages: MSGS });
assert.equal(primaryAgain.status, 200);
assert.equal(
(await primaryAgain.json()).choices[0].message.content,
"LEAF-A",
);
} finally {
await p.cleanup();
}
});

test("variant remap reaches the leaf as reasoning_effort", async () => {
const p = await startProxy();
try {
Expand Down
Loading