From cc665e8d40f9ac14f4faec6780fca52e3c582dff Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 18:28:33 -0500 Subject: [PATCH] fix(opencode-route-proxy): evaluate target window gates (#3225) normalizeTarget dropped target window gates, so time-windowed route targets (the background route peak/off-peak chain, opencode#639) were expanded at all hours through the proxy. Preserve the gate at normalization (name or {name, invert:true}), load experimental.model_route_windows, and expand a gated target only while its window is active in its own timezone (daysOfWeek + HH:MM range, start inclusive/end exclusive, overnight wrap), or only while inactive for the invert form. Unknown window names fail closed. OPENCODE_ROUTE_PROXY_NOW_MS pins the evaluation clock for tests/replay. --- bin/opencode-route-proxy.mjs | 80 +++++++++++++++++++++++++++- bin/opencode-route-proxy.test.mjs | 86 ++++++++++++++++++++++++++++++- 2 files changed, 163 insertions(+), 3 deletions(-) diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index 19600ae194..017fc994a7 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -37,6 +37,9 @@ // relative to this file) // OPENCODE_ROUTE_PROXY_DB opencode.db path (default: // ~/.local/share/opencode/opencode.db) +// OPENCODE_ROUTE_PROXY_NOW_MS pin the clock (epoch ms) used for +// route window gates — tests and +// incident replay; unset = wall clock import { createServer } from "node:http"; import { readFileSync, statSync } from "node:fs"; import { homedir } from "node:os"; @@ -146,6 +149,7 @@ const loadConfig = () => { mtimeMs: st.mtimeMs, providers: raw.provider || {}, routes: raw.experimental?.model_routes || raw.model_routes || {}, + windows: raw.experimental?.model_route_windows || raw.model_route_windows || {}, disabled: new Set(raw.disabled_providers || []), }; return cfgCache; @@ -312,13 +316,83 @@ const parseTargetRef = (ref) => { return { providerId: ref.slice(0, s), modelKey: ref.slice(s + 1), variant }; }; +// Route target window gates (#3225): a target may carry +// `window: ""` or `window: { name, invert: true }`, naming a +// window in experimental.model_route_windows +// ({ daysOfWeek: ["mon", ...], start: "HH:MM", end: "HH:MM", +// timezone }). The gate survives normalization — dropping it here was +// the bug — and resolveRoute expands a gated target only while its +// window is active (or, with invert, only while it is NOT). A gate +// naming an unknown window never matches: fail closed, so a config +// typo surfaces as a loud no-members route instead of silently +// ungating the target. +const normalizeWindowGate = (w) => { + if (typeof w === "string" && w) return { name: w, invert: false }; + if (w && typeof w.name === "string" && w.name) + return { name: w.name, invert: w.invert === true }; + return null; +}; + const normalizeTarget = (t) => { - if (typeof t === "string") return { ...parseTargetRef(t), variantMap: null }; + if (typeof t === "string") + return { ...parseTargetRef(t), variantMap: null, windowGate: null }; if (t && typeof t.model === "string") - return { ...parseTargetRef(t.model), variantMap: t.variants || null }; + return { + ...parseTargetRef(t.model), + variantMap: t.variants || null, + windowGate: normalizeWindowGate(t.window), + }; return null; }; +// Clock for window evaluation. OPENCODE_ROUTE_PROXY_NOW_MS pins +// "now" (epoch ms) for tests and incident replay; unset = wall clock. +const nowMs = () => { + const pinned = Number(process.env.OPENCODE_ROUTE_PROXY_NOW_MS); + return Number.isFinite(pinned) && pinned > 0 ? pinned : Date.now(); +}; + +const parseHHMM = (s) => { + const m = /^([0-9]{1,2}):([0-9]{2})$/.exec(typeof s === "string" ? s.trim() : ""); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; +}; + +// Is window `win` active at `now` (epoch ms)? Day and wall time are +// read in the window's own timezone; start inclusive, end exclusive; +// an end at or before start wraps past midnight. +const windowActive = (win, now) => { + if (!win || typeof win !== "object") return false; + const start = parseHHMM(win.start); + const end = parseHHMM(win.end); + if (start === null || end === null) return false; + let parts; + try { + parts = new Intl.DateTimeFormat("en-US", { + timeZone: win.timezone || "UTC", + weekday: "short", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(new Date(now)); + } catch { + return false; + } + const get = (type) => parts.find((part) => part.type === type)?.value; + const day = String(get("weekday") || "").slice(0, 3).toLowerCase(); + if (Array.isArray(win.daysOfWeek) && win.daysOfWeek.length) { + const days = win.daysOfWeek.map((d) => String(d).slice(0, 3).toLowerCase()); + if (!days.includes(day)) return false; + } + const mins = Number(get("hour")) * 60 + Number(get("minute")); + return start <= end ? mins >= start && mins < end : mins >= start || mins < end; +}; + +const targetEligible = (cfg, t, now) => { + if (!t.windowGate) return true; + const active = windowActive(cfg.windows?.[t.windowGate.name], now); + return t.windowGate.invert ? !active : active; +}; + const rotation = new Map(); // routeId -> counter const rotate = (arr, routeId) => { if (arr.length < 2) return arr; @@ -352,6 +426,7 @@ const weightedOrder = (targets, weights) => { // [{ providerId, modelKey, variant }]. Nested routes recurse; disabled // providers are skipped; cycles are cut. const resolveRoute = (cfg, routeId, variantIn = null) => { + const now = nowMs(); const out = []; const expand = (rid, vIn, seen) => { if (seen.has(rid)) return; @@ -361,6 +436,7 @@ const resolveRoute = (cfg, routeId, variantIn = null) => { let targets = (route.targets || []) .map(normalizeTarget) .filter(Boolean) + .filter((t) => targetEligible(cfg, t, now)) .map((t) => ({ ...t, refBase: `${t.providerId}/${t.modelKey}` })); if (route.selection === "round-robin") targets = rotate(targets, rid); else if (route.selection === "weighted") diff --git a/bin/opencode-route-proxy.test.mjs b/bin/opencode-route-proxy.test.mjs index 2c3c5b5054..dcc72825bf 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -124,7 +124,7 @@ const ROUTE_ATTEMPT_SCHEMA = `CREATE TABLE route_attempt ( quota text, tokens_estimated integer, error_body text, hedged integer, cost_usd real)`; -const startProxy = async () => { +const startProxy = async ({ nowMs: pinnedNow } = {}) => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "route-proxy-test-")); const leafA = await makeLeaf("LEAF-A", "key-a"); const leafB = await makeLeaf("LEAF-B", "key-b"); @@ -165,11 +165,17 @@ const startProxy = async () => { }, }, "experimental": { + "model_route_windows": { + "peak": { "daysOfWeek": ["mon", "tue", "wed", "thu", "fri"], "start": "01:00", "end": "04:00", "timezone": "UTC" }, + }, "model_routes": { "t-ordered": { "selection": "ordered", "targets": ["leafA/m-a", "leafB/m-b"] }, "t-variant": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "variants": { "medium": "high" } } ] }, "t-nested": { "selection": "ordered", "targets": ["opencode-route/t-ordered"] }, "t-disabled": { "selection": "ordered", "targets": ["leafOff/m-b", "leafB/m-b"] }, + "t-window": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "peak" }, "leafB/m-b" ] }, + "t-window-inv": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": { "name": "peak", "invert": true } }, "leafB/m-b" ] }, + "t-window-unknown": { "selection": "ordered", "targets": [ { "model": "leafA/m-a", "window": "no-such-window" }, "leafB/m-b" ] }, }, }, }`, @@ -183,6 +189,9 @@ const startProxy = async () => { OPENCODE_ROUTE_PROXY_CONFIG: configPath, OPENCODE_ROUTE_PROXY_DB: dbPath, OPENCODE_ROUTE_PROXY_TIMEOUT_MS: "15000", + ...(pinnedNow + ? { OPENCODE_ROUTE_PROXY_NOW_MS: String(pinnedNow) } + : {}), }; const child = spawn( process.execPath, @@ -360,3 +369,78 @@ test("unknown route and malformed bodies are rejected", async () => { await p.cleanup(); } }); + +// Window gates (#3225): the fixture "peak" window is Mon-Fri +// 01:00-04:00 UTC. 2026-11-04 is a Wednesday. +const IN_PEAK = Date.UTC(2026, 10, 4, 2, 30); +const OUT_PEAK = Date.UTC(2026, 10, 4, 12, 0); + +test("window-gated target is expanded inside its window", async () => { + const p = await startProxy({ nowMs: IN_PEAK }); + try { + const res = await p.post({ model: "opencode-route/t-window", messages: MSGS }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-A"); + const rows = p.attempts(); + assert.equal(rows.length, 1); + assert.equal(rows[0].provider_id, "leafA"); + } finally { + await p.cleanup(); + } +}); + +test("window-gated target is excluded outside its window", async () => { + const p = await startProxy({ nowMs: OUT_PEAK }); + try { + const res = await p.post({ model: "opencode-route/t-window", messages: MSGS }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-B"); + const rows = p.attempts(); + assert.equal(rows.length, 1); + assert.equal(rows[0].provider_id, "leafB"); + } finally { + await p.cleanup(); + } +}); + +test("inverted window gate is eligible only outside the window", async () => { + const inP = await startProxy({ nowMs: IN_PEAK }); + try { + const res = await inP.post({ + model: "opencode-route/t-window-inv", + messages: MSGS, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-B"); + } finally { + await inP.cleanup(); + } + const outP = await startProxy({ nowMs: OUT_PEAK }); + try { + const res = await outP.post({ + model: "opencode-route/t-window-inv", + messages: MSGS, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-A"); + } finally { + await outP.cleanup(); + } +}); + +test("a gate naming an unknown window fails closed", async () => { + const p = await startProxy({ nowMs: IN_PEAK }); + try { + const res = await p.post({ + model: "opencode-route/t-window-unknown", + messages: MSGS, + }); + assert.equal(res.status, 200); + assert.equal((await res.json()).choices[0].message.content, "LEAF-B"); + const rows = p.attempts(); + assert.equal(rows.length, 1); + assert.equal(rows[0].provider_id, "leafB"); + } finally { + await p.cleanup(); + } +});