Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

20.5 KB
Raw Blame
import { describe, it, beforeEach, afterEach, before, after } from "node:test";
import assert from "node:assert";
import net from "node:net";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts";
import type { ExecutorLog, ProviderCredentials } from "../../open-sse/executors/base.ts";
import { resolveProxyForRequest } from "../../open-sse/utils/proxyFetch.ts";
import {
  BURST_PARK_THRESHOLD,
  PARK_WAIT_MS,
  setAsideParkWaitMs,
} from "../../open-sse/executors/opencodeParkResume.ts";
import * as throttle from "../../open-sse/executors/opencodeEgressThrottle.ts";
import {
  __resetProxyRefusalMemoryForTesting,
  noteProxyRefusal,
  proxyEgressKey,
  proxySetAsideStatus,
} from "../../open-sse/utils/proxyRefusalMemory.ts";

const FLAG = "OPENCODE_PARK_AND_RESUME";
const MARKER_ENV = "OPENCODE_POOL_STRAIN_MARKER_PATH";

const log: ExecutorLog = { debug() {}, info() {}, warn() {}, error() {} };
const FPS = ["p", "q", "r", "s", "t", "u", "v", "w"].map((c) => c.repeat(32));

const servers: net.Server[] = [];
const ports: number[] = [];

function listen(server: net.Server): Promise<number> {
  return new Promise((resolve) => {
    server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port));
  });
}

before(async () => {
  for (let i = 0; i < FPS.length; i++) {
    const server = net.createServer((s) => s.destroy());
    servers.push(server);
    ports.push(await listen(server));
  }
});

after(() => {
  servers.forEach((s) => s.close());
});

function credentialsFor(count: number): ProviderCredentials {
  const fingerprints = FPS.slice(0, count);
  return {
    apiKey: null,
    accessToken: null,
    connectionId: "noauth",
    providerSpecificData: {
      fingerprints,
      accountProxies: fingerprints.map((fp, i) => ({
        fingerprint: fp,
        proxy: { type: "http", host: "127.0.0.1", port: ports[i] },
      })),
    },
  };
}

const BURST_BODY = JSON.stringify({ error: { message: "upstream busy, try again" } });

describe("opencode 429 park-and-resume", () => {
  let originalFetch: typeof globalThis.fetch;
  let priorFlag: string | undefined;
  let priorMarker: string | undefined;
  let observed: string[];
  let markerDir: string;

  beforeEach(() => {
    // PROXY_SKIP_RECENTLY_FAILED is on by default (#14688): a refusal recorded by one
    // case would otherwise set its proxy aside for the next case.
    __resetProxyRefusalMemoryForTesting();
    originalFetch = globalThis.fetch;
    priorFlag = process.env[FLAG];
    priorMarker = process.env[MARKER_ENV];
    process.env[FLAG] = "true";
    observed = [];
    markerDir = fs.mkdtempSync(path.join(os.tmpdir(), "park-resume-"));
    process.env[MARKER_ENV] = path.join(markerDir, "strain.json");
  });

  afterEach(() => {
    globalThis.fetch = originalFetch;
    if (priorFlag === undefined) delete process.env[FLAG];
    else process.env[FLAG] = priorFlag;
    if (priorMarker === undefined) delete process.env[MARKER_ENV];
    else process.env[MARKER_ENV] = priorMarker;
    fs.rmSync(markerDir, { recursive: true, force: true });
  });

  function installFetch(plan: Array<{ status: number; body?: string }>) {
    let call = 0;
    globalThis.fetch = (async (input: RequestInfo | URL) => {
      const url =
        typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
      const resolved = resolveProxyForRequest(url);
      observed.push(resolved.proxyUrl ? new URL(resolved.proxyUrl).port : "direct");
      const step = plan[Math.min(call, plan.length - 1)];
      call++;
      return new Response(step.body ?? JSON.stringify({ ok: step.status === 200 }), {
        status: step.status,
        headers: { "Content-Type": "application/json" },
      });
    }) as typeof globalThis.fetch;
  }

  function writeMarker(payload: Record<string, unknown>): void {
    const markerPath = process.env[MARKER_ENV] as string;
    fs.writeFileSync(markerPath, JSON.stringify(payload));
    // #14487: the marker is only trusted when it is owner-locked-down (no
    // group/other write bit) — the fixture must reflect that, not just the
    // umask-derived default mode.
    fs.chmodSync(markerPath, 0o600);
  }

  async function run(count: number, stream: boolean, signal: AbortSignal | null = null) {
    const exec = new OpencodeExecutor("opencode-zen");
    exec.parkSleep = async () => true;
    return exec.execute({
      model: "muse-spark-1.3-contributor-free",
      body: { messages: [{ role: "user", content: "hi" }], stream: false },
      stream,
      signal,
      credentials: credentialsFor(count),
      log,
    });
  }

  it("below the threshold the wave stays normal with no park", async () => {
    installFetch(
      Array.from({ length: BURST_PARK_THRESHOLD - 1 }, () => ({ status: 429, body: BURST_BODY }))
    );
    const result = await run(BURST_PARK_THRESHOLD - 1, false);
    assert.strictEqual((result as { response: Response }).response.status, 429);
    assert.strictEqual(observed.length, BURST_PARK_THRESHOLD - 1);
    const text = await (result as { response: Response }).response.text();
    assert.ok(!text.includes(":ping"), "no heartbeat below the threshold");
  });

  it("at the threshold it parks once with a heartbeat then replays one capped leg", async () => {
    installFetch([
      ...Array.from({ length: BURST_PARK_THRESHOLD }, () => ({ status: 429, body: BURST_BODY })),
      { status: 200 },
    ]);
    const warnings: string[] = [];
    const loud: ExecutorLog = { ...log, warn: (...a: unknown[]) => void warnings.push(String(a)) };
    const exec = new OpencodeExecutor("opencode-zen");
    exec.parkSleep = async () => true;
    const result = await exec.execute({
      model: "muse-spark-1.3-contributor-free",
      body: { messages: [{ role: "user", content: "hi" }], stream: false },
      stream: true,
      signal: null,
      credentials: credentialsFor(BURST_PARK_THRESHOLD + 1),
      log: loud,
    });
    const response = (result as { response: Response }).response;
    assert.strictEqual(response.status, 200);
    assert.ok(response.headers.get("content-type")?.includes("text/event-stream"));
    const text = await response.text();
    assert.ok(text.includes(":ping"), "heartbeat precedes the replayed leg");
    assert.ok(
      observed.length <= BURST_PARK_THRESHOLD + 3,
      `replay leg capped (saw ${observed.length})`
    );
    assert.ok(
      warnings.some((w) => w.includes("burstStreak") && w.includes("freshD2")),
      "park decision logged with its inputs"
    );
  });

  it("a fresh pool-strain marker parks directly without recounting", async () => {
    writeMarker({ since: Date.now() - 10_000, reason: "i2-zero", ttl_s: 300 });
    installFetch([{ status: 429, body: BURST_BODY }, { status: 200 }]);
    const result = await run(4, true);
    const text = await (result as { response: Response }).response.text();
    assert.ok(text.includes(":ping"), "fresh marker justifies the park");
    assert.ok(observed.length <= 1 + 3, `single replay leg (saw ${observed.length})`);
  });

  it("a stale marker is ignored and only the counter decides", async () => {
    const markerPath = process.env[MARKER_ENV] as string;
    writeMarker({ since: Date.now() - 400_000, reason: "i2-zero", ttl_s: 300 });
    const aged = Date.now() - 400_000;
    fs.utimesSync(markerPath, new Date(aged), new Date(aged));
    installFetch(
      Array.from({ length: BURST_PARK_THRESHOLD - 1 }, () => ({ status: 429, body: BURST_BODY }))
    );
    const result = await run(BURST_PARK_THRESHOLD - 1, true);
    const text = await (result as { response: Response }).response.text();
    assert.ok(!text.includes(":ping"), "stale marker never parks");
    assert.strictEqual(observed.length, BURST_PARK_THRESHOLD - 1);
  });

  it("a future marker stays bounded instead of parking past the ceiling", async () => {
    writeMarker({ since: Date.now() + 60_000, reason: "i2-zero", ttl_s: 300 });
    installFetch([{ status: 429, body: BURST_BODY }, { status: 200 }]);
    const result = await run(4, true);
    const text = await (result as { response: Response }).response.text();
    assert.ok(text.includes(":ping"), "future marker still justifies the park");
  });

  it("flag off keeps the exact current rotation", async () => {
    delete process.env[FLAG];
    installFetch(
      Array.from({ length: BURST_PARK_THRESHOLD }, () => ({ status: 429, body: BURST_BODY }))
    );
    const result = await run(BURST_PARK_THRESHOLD, true);
    const response = (result as { response: Response }).response;
    assert.strictEqual(response.status, 429);
    const text = await response.text();
    assert.ok(!text.includes(":ping"), "no park when the flag is off");
    assert.strictEqual(observed.length, BURST_PARK_THRESHOLD);
  });

  it("a fleet-suspect slot budget hands over to park-and-replay", async () => {
    // A "park" arm from the throttle must run the park-and-replay,
    // not surface the last 429.
    process.env.OPENCODE_EGRESS_THROTTLE_ENABLED = "1";
    process.env.OPENCODE_EGRESS_THROTTLE_FLEET_THRESHOLD = "1";
    process.env.OPENCODE_EGRESS_THROTTLE_SUSPECT_SLOTS = "1";
    throttle._clearEgressThrottleForTest();
    throttle.configureFleetFromConfig(throttle.resolveEgressThrottleConfig(process.env));
    throttle.noteEgress429(Date.now());
    installFetch([{ status: 429, body: BURST_BODY }, { status: 200 }]);
    const result = await run(4, true);
    const response = (result as { response: Response }).response;
    assert.strictEqual(response.status, 200);
    const text = await response.text();
    assert.ok(text.includes(":ping"), "throttle park runs the heartbeat + replay");
    delete process.env.OPENCODE_EGRESS_THROTTLE_ENABLED;
    delete process.env.OPENCODE_EGRESS_THROTTLE_FLEET_THRESHOLD;
    delete process.env.OPENCODE_EGRESS_THROTTLE_SUSPECT_SLOTS;
    throttle._clearEgressThrottleForTest();
  });

  it("a client abort mid-park stops without any further route call", async () => {
    installFetch([
      ...Array.from({ length: BURST_PARK_THRESHOLD }, () => ({ status: 429, body: BURST_BODY })),
      { status: 200 },
    ]);
    const controller = new AbortController();
    const exec = new OpencodeExecutor("opencode-zen");
    exec.parkSleep = async () => {
      controller.abort();
      return false;
    };
    const callsBefore = observed.length;
    const result = await exec.execute({
      model: "muse-spark-1.3-contributor-free",
      body: { messages: [{ role: "user", content: "hi" }], stream: false },
      stream: true,
      signal: controller.signal,
      credentials: credentialsFor(BURST_PARK_THRESHOLD + 1),
      log,
    });
    void result;
    assert.strictEqual(observed.length, BURST_PARK_THRESHOLD, "no route call after abort");
    void callsBefore;
  });

  function egressKeys(count: number): string[] {
    return Array.from({ length: count }, (_, i) => {
      const key = proxyEgressKey({ type: "http", host: "127.0.0.1", port: ports[i] });
      assert.ok(key !== null, "dedicated proxy key for the test account");
      return key as string;
    });
  }

  describe("set-aside reader", () => {
    it("reports quota-only set-aside with the real end", () => {
      const nowMs = Date.now();
      const [key] = egressKeys(1);
      noteProxyRefusal(key, "ip_quota_429", nowMs - (300_000 - 30_000));
      const status = proxySetAsideStatus(key, nowMs);
      assert.strictEqual(status.setAside, true);
      assert.strictEqual(status.quotaOnly, true);
      assert.ok(
        status.endsAt !== null && Math.abs(status.endsAt - (nowMs + 30_000)) < 5_000,
        `real end near now+30s (saw ${status.endsAt})`
      );
      assert.strictEqual(setAsideParkWaitMs([key], nowMs) !== null, true);
    });

    it("reports mixed motives on one key as not quota-only, with the real end", () => {
      for (const order of [0, 1]) {
        __resetProxyRefusalMemoryForTesting();
        const nowMs = Date.now();
        const [key] = egressKeys(1);
        // Both writes land in force (quota 300s, slow 60s); only the write
        // order differs, proving the verdict follows the rule, not recency.
        if (order === 0) {
          noteProxyRefusal(key, "ip_quota_429", nowMs);
          noteProxyRefusal(key, "slow", nowMs);
        } else {
          noteProxyRefusal(key, "slow", nowMs);
          noteProxyRefusal(key, "ip_quota_429", nowMs);
        }
        const status = proxySetAsideStatus(key, nowMs);
        assert.strictEqual(status.setAside, true);
        assert.strictEqual(status.quotaOnly, false);
        assert.ok(
          status.endsAt !== null && status.endsAt > nowMs,
          `real end in the future (saw ${status.endsAt})`
        );
        assert.strictEqual(setAsideParkWaitMs([key], nowMs), null);
      }
    });

    it("reports an unknown key and empty memory as not set aside", () => {
      const nowMs = Date.now();
      const [key] = egressKeys(1);
      assert.deepStrictEqual(proxySetAsideStatus(key, nowMs), {
        setAside: false,
        quotaOnly: false,
        endsAt: null,
      });
      assert.deepStrictEqual(proxySetAsideStatus(null, nowMs), {
        setAside: false,
        quotaOnly: false,
        endsAt: null,
      });
      assert.strictEqual(setAsideParkWaitMs([], nowMs), null);
      assert.strictEqual(setAsideParkWaitMs([null], nowMs), null);
      assert.strictEqual(setAsideParkWaitMs([key], nowMs), null);
    });

    it("waits for the nearest real end of quota-only keys, bounded by the park window", () => {
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      noteProxyRefusal(first, "ip_quota_429", nowMs - (300_000 - 30_000));
      noteProxyRefusal(second, "ip_quota_429", nowMs - (300_000 - 60_000));
      const wait = setAsideParkWaitMs([first, second], nowMs);
      assert.ok(wait !== null && Math.abs(wait - 30_000) < 5_000, `nearest wait (saw ${wait})`);
    });

    it("returns no wait outside the park window or across mixed motives", () => {
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      noteProxyRefusal(first, "ip_quota_429", nowMs - 300_000);
      noteProxyRefusal(second, "slow", nowMs - (60_000 - 30_000));
      assert.strictEqual(setAsideParkWaitMs([first], nowMs - 300_000), null);
      assert.strictEqual(setAsideParkWaitMs([first, second], nowMs), null);
    });
  });

  describe("set-aside park trigger", () => {
    it("parks when every egress is set aside for quota with a release inside the window", async () => {
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      const setAsideAt = nowMs - (300_000 - 30_000);
      noteProxyRefusal(first, "ip_quota_429", setAsideAt);
      noteProxyRefusal(second, "ip_quota_429", setAsideAt);
      installFetch([
        { status: 429, body: BURST_BODY },
        { status: 429, body: BURST_BODY },
        { status: 200 },
      ]);
      const exec = new OpencodeExecutor("opencode-zen");
      let waitedMs = 0;
      exec.parkSleep = async (ms) => {
        waitedMs += ms;
        return true;
      };
      const result = await exec.execute({
        model: "muse-spark-1.3-contributor-free",
        body: { messages: [{ role: "user", content: "hi" }], stream: false },
        stream: true,
        signal: null,
        credentials: credentialsFor(2),
        log,
      });
      const text = await (result as { response: Response }).response.text();
      assert.ok(text.includes(":ping"), "set-aside park emits the heartbeat");
      assert.ok(
        waitedMs > 0 && waitedMs <= PARK_WAIT_MS,
        `park waits within the window (saw ${waitedMs})`
      );
    });

    it("returns 429 untouched when slow-only set-asides hold every egress", async () => {
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      const setAsideAt = nowMs - (60_000 - 30_000);
      noteProxyRefusal(first, "slow", setAsideAt);
      noteProxyRefusal(second, "slow", setAsideAt);
      installFetch([
        { status: 429, body: BURST_BODY },
        { status: 429, body: BURST_BODY },
      ]);
      const result = await run(2, true);
      assert.strictEqual((result as { response: Response }).response.status, 429);
      const text = await (result as { response: Response }).response.text();
      assert.ok(!text.includes(":ping"), "slow set-asides never park on this path");
    });

    it("returns 429 untouched when mixed motives share one egress", async () => {
      for (const order of [0, 1]) {
        __resetProxyRefusalMemoryForTesting();
        const nowMs = Date.now();
        const [first, second] = egressKeys(2);
        const quotaAt = nowMs - (300_000 - 30_000);
        const slowAt = nowMs - (60_000 - 90_000);
        if (order === 0) {
          noteProxyRefusal(first, "ip_quota_429", quotaAt);
          noteProxyRefusal(first, "slow", slowAt);
        } else {
          noteProxyRefusal(first, "slow", slowAt);
          noteProxyRefusal(first, "ip_quota_429", quotaAt);
        }
        noteProxyRefusal(second, "ip_quota_429", quotaAt);
        installFetch([
          { status: 429, body: BURST_BODY },
          { status: 429, body: BURST_BODY },
        ]);
        const result = await run(2, true);
        assert.strictEqual((result as { response: Response }).response.status, 429);
        const text = await (result as { response: Response }).response.text();
        assert.ok(!text.includes(":ping"), `mixed motives never park (order ${order})`);
      }
    });

    it("returns 429 untouched when no set-aside ends inside the window", async () => {
      for (const expired of [true, false]) {
        __resetProxyRefusalMemoryForTesting();
        const nowMs = Date.now();
        const [first, second] = egressKeys(2);
        const setAsideAt = expired ? nowMs - 300_000 : nowMs;
        noteProxyRefusal(first, "ip_quota_429", setAsideAt);
        noteProxyRefusal(second, "ip_quota_429", setAsideAt);
        installFetch([
          { status: 429, body: BURST_BODY },
          { status: 429, body: BURST_BODY },
        ]);
        const result = await run(2, true);
        assert.strictEqual((result as { response: Response }).response.status, 429);
        const text = await (result as { response: Response }).response.text();
        assert.ok(!text.includes(":ping"), `no park outside the window (expired=${expired})`);
      }
    });

    it("keeps the current rotation when the park flag is off, even with set-asides", async () => {
      delete process.env[FLAG];
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      const setAsideAt = nowMs - (300_000 - 30_000);
      noteProxyRefusal(first, "ip_quota_429", setAsideAt);
      noteProxyRefusal(second, "ip_quota_429", setAsideAt);
      installFetch([
        { status: 429, body: BURST_BODY },
        { status: 429, body: BURST_BODY },
      ]);
      const result = await run(2, true);
      assert.strictEqual((result as { response: Response }).response.status, 429);
      const text = await (result as { response: Response }).response.text();
      assert.ok(!text.includes(":ping"), "no park when the flag is off");
    });

    it("parks, then the replay path stays covered by the threshold case", async () => {
      // 1b (weakened per review m2): a real 1s sleep would prove the replay
      // leg serves a fresh dispatch, but module-load periods (min 1000ms)
      // forbid a fast in-process replay. This asserts the park envelope on
      // the set-aside path (heartbeat + bounded wait); the served replay
      // itself stays covered by the threshold case above plus the unchanged
      // replayCandidates unit suite.
      const exec = new OpencodeExecutor("opencode-zen");
      let waitedMs = 0;
      exec.parkSleep = async (ms) => {
        waitedMs += ms;
        return true;
      };
      const nowMs = Date.now();
      const [first, second] = egressKeys(2);
      const setAsideAt = nowMs - (300_000 - 30_000);
      noteProxyRefusal(first, "ip_quota_429", setAsideAt);
      noteProxyRefusal(second, "ip_quota_429", setAsideAt);
      installFetch([
        { status: 429, body: BURST_BODY },
        { status: 429, body: BURST_BODY },
        { status: 200, body: JSON.stringify({ ok: true }) },
      ]);
      const result = await exec.execute({
        model: "muse-spark-1.3-contributor-free",
        body: { messages: [{ role: "user", content: "hi" }], stream: false },
        stream: true,
        signal: null,
        credentials: credentialsFor(2),
        log,
      });
      const text = await (result as { response: Response }).response.text();
      assert.ok(text.includes(":ping"), "set-aside park emits the heartbeat");
      assert.ok(
        Math.abs(waitedMs - 30_000) < 5_000,
        `park waits until the nearest set-aside end (saw ${waitedMs})`
      );
    });
  });
});