From ce9c4c20d96d69e7d25a831f56cbbed99009449c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:17 +0700 Subject: [PATCH 01/10] fix(auth): harden the request entry point Authentication and the rate limiter were `preHandler` hooks, and Fastify parses the body between `preParsing` and `preHandler`, so an anonymous caller made the gateway buffer and JSON-parse up to OPENCODE_MAX_BODY_BYTES (64 MiB) per connection with no credential. Both hooks now run `onRequest`, after the CORS hooks. Credential-less callers are bucketed by `request.ip` (proxy-aware when `trustProxy` is on) instead of sharing one anonymous bucket, and the bucket map is capped so a rotating address cannot grow it without bound. The public-path check canonicalises trailing slashes and repeated separators, so `/metrics/` can no longer fingerprint `/metrics`. The public `GET /` index now lists every registered route, with a test asserting the two sets stay equal. --- src/auth.ts | 26 ++++- src/http/rateLimit.ts | 65 ++++++++---- src/server.ts | 22 +++- test/regressions.test.ts | 211 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 296 insertions(+), 28 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index 231ff9d..9fe6e57 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -20,9 +20,24 @@ import { ApiError } from "./errors.js"; const PUBLIC_PATHS = new Set(["/", "/health", "/ready", "/healthz"]); -/** Path of a request URL, ignoring the query string. */ +/** + * Canonical path of a request URL: the query string is dropped, repeated + * separators are collapsed and a trailing slash is removed; `/` stays `/`. + * + * The router treats `/metrics/` and `//metrics` as distinct (unmatched) paths, + * so without canonicalisation an anonymous caller could tell whether `/metrics` + * is public from the status code of a differently spelled URL. Every + * public-path and `/metrics` comparison goes through this function instead. + */ +export function canonicalPath(url: string): string { + const raw = url.split("?")[0] ?? ""; + const collapsed = raw.replace(/\/{2,}/g, "/").replace(/\/+$/, ""); + return collapsed === "" ? "/" : collapsed; +} + +/** Path of a request URL, ignoring the query string and normalising spelling. */ export function requestPath(request: FastifyRequest): string { - return request.url.split("?")[0] ?? ""; + return canonicalPath(request.url); } /** True for the routes that never require a credential. */ @@ -104,7 +119,12 @@ function unauthorized(): ApiError { ); } -/** Fastify preHandler enforcing authentication. */ +/** + * Fastify `onRequest` hook enforcing authentication. + * + * It is registered as `onRequest` so an anonymous caller is rejected before + * Fastify buffers and parses the body (up to `bodyLimitBytes` per connection). + */ export function requireApiKey(config: Config) { return async function authenticate(request: FastifyRequest, _reply: FastifyReply): Promise { const path = requestPath(request); diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts index eb4c0fe..bd87fd8 100644 --- a/src/http/rateLimit.ts +++ b/src/http/rateLimit.ts @@ -2,10 +2,14 @@ * In-process token-bucket rate limiting. * * One bucket per authenticated API key (never the raw key: only a SHA-256 hash - * is retained) plus one shared bucket for anonymous callers. The limiter is a - * `preHandler` beside `requireApiKey`, so an unauthenticated caller is rejected - * before any bucket is touched, and `/admin/*` gets its own bucket so operator - * traffic cannot be starved by completion traffic. + * is retained) plus one bucket per client address for credential-less callers + * (never the raw address either). The limiter runs as an `onRequest` hook beside + * `requireApiKey`, so an unauthenticated caller is rejected before any bucket is + * touched, and `/admin/*` gets its own bucket so operator traffic cannot be + * starved by completion traffic. + * + * The bucket map is bounded: an anonymous deployment cannot let a spoofed or + * rotating client address grow it without limit. * * There is no distributed state: every gateway instance limits on its own. That * is deliberate — no new runtime dependency and no shared store. @@ -23,6 +27,16 @@ interface BucketState { refreshedAt: number; } +/** + * Maximum number of live buckets per limiter. + * + * With `OPENCODE_ALLOW_NO_AUTH=true` callers are bucketed by client address, and + * a spoofed or rotating address must not be able to grow the map without bound. + * At the cap the oldest bucket is evicted; the evicted caller starts with a full + * bucket again, which is the accepted trade-off for a bounded fairness map. + */ +export const MAX_RATE_LIMIT_BUCKETS = 10_000; + export interface TokenBucketLimiterOptions { /** Sustained requests per minute; `0` disables the limiter. */ rpm: number; @@ -30,6 +44,8 @@ export interface TokenBucketLimiterOptions { burst: number; /** Injectable clock, for tests. */ now?: () => number; + /** Live-bucket cap; defaults to `MAX_RATE_LIMIT_BUCKETS`. */ + maxBuckets?: number; } /** Bucket capacity when `OPENCODE_RATE_LIMIT_BURST` is left at 0. */ @@ -41,12 +57,14 @@ export class TokenBucketLimiter { readonly #rpm: number; readonly #burst: number; readonly #now: () => number; + readonly #maxBuckets: number; readonly #buckets = new Map(); constructor(options: TokenBucketLimiterOptions) { this.#rpm = Math.max(0, options.rpm); this.#burst = options.burst > 0 ? options.burst : derivedBurst(this.#rpm); this.#now = options.now ?? Date.now; + this.#maxBuckets = Math.max(1, Math.floor(options.maxBuckets ?? MAX_RATE_LIMIT_BUCKETS)); } /** False when the limiter is disabled (`rpm` is 0). */ @@ -79,6 +97,11 @@ export class TokenBucketLimiter { if (bucket === undefined) { bucket = { tokens: this.#burst, refreshedAt: now }; this.#buckets.set(key, bucket); + // `Map` iterates in insertion order, so the first key is the oldest. + if (this.#buckets.size > this.#maxBuckets) { + const oldest = this.#buckets.keys().next(); + if (!oldest.done) this.#buckets.delete(oldest.value); + } } else { const elapsed = Math.max(0, now - bucket.refreshedAt); bucket.tokens = Math.min(this.#burst, bucket.tokens + elapsed * refillPerMs); @@ -98,23 +121,24 @@ export class TokenBucketLimiter { } } -/** Hash an identifying credential so a raw API key is never retained. */ -function bucketKey(scope: string, credential: string | undefined): string { - const material = credential === undefined ? "anonymous" : credential; - return createHash("sha256").update(`${scope}\u0000${material}`).digest("hex"); +/** Hash a bucket identity so neither a raw API key nor a client address is retained. */ +function bucketKey(scope: string, identity: string): string { + return createHash("sha256").update(`${scope}\u0000${identity}`).digest("hex"); } /** - * Credential used for bucketing. + * Identity a request is bucketed on. * - * Only a key that is actually configured may create its own bucket; with - * `OPENCODE_ALLOW_NO_AUTH=true` an arbitrary caller-supplied header would - * otherwise grow the bucket map without bound. + * A configured API key gets its own bucket. Every other caller — that is, any + * caller in a deployment with `OPENCODE_ALLOW_NO_AUTH=true` — is bucketed by + * `request.ip`, which is proxy-aware when `trustProxy` is enabled, so one client + * cannot spend another client's budget. Caller-supplied headers are never used, + * because an arbitrary value would grow the bucket map without bound. */ -function credentialFor(config: Config, request: FastifyRequest): string | undefined { +function bucketIdentity(config: Config, request: FastifyRequest): string { const presented = extractApiKey(request); - if (presented === undefined) return undefined; - return config.apiKeys.includes(presented) ? presented : undefined; + if (presented !== undefined && config.apiKeys.includes(presented)) return `key:${presented}`; + return `ip:${request.ip.length > 0 ? request.ip : "unknown"}`; } /** Limiter pair wired into the request lifecycle. */ @@ -129,12 +153,13 @@ export function createRateLimiters(config: Config, now?: () => number): RateLimi } /** - * Build the rate-limiting `preHandler`. + * Build the rate-limiting `onRequest` hook. * * Health/metrics probes and preflight requests are exempt; `/admin/*` uses the - * admin bucket. A rejected request answers `429 rate_limit_error` with the - * documented `retry-after` header (Fastify's error handler derives it from - * `retryAfterMs`). + * admin bucket. Authenticated callers are bucketed per configured key, every + * other caller per client address (see `bucketIdentity`). A rejected request + * answers `429 rate_limit_error` with the documented `retry-after` header + * (Fastify's error handler derives it from `retryAfterMs`). */ export function requireRateLimit(config: Config, limiters: RateLimiters, onReject?: (scope: "api" | "admin") => void) { return async function rateLimit(request: FastifyRequest, _reply: FastifyReply): Promise { @@ -144,7 +169,7 @@ export function requireRateLimit(config: Config, limiters: RateLimiters, onRejec const scope = path === "/admin" || path.startsWith("/admin/") ? "admin" : "api"; const limiter = scope === "admin" ? limiters.admin : limiters.api; - const retryAfterMs = limiter.take(bucketKey(scope, credentialFor(config, request))); + const retryAfterMs = limiter.take(bucketKey(scope, bucketIdentity(config, request))); if (retryAfterMs === undefined) return; onReject?.(scope); diff --git a/src/server.ts b/src/server.ts index 4bbf2ac..0261c85 100644 --- a/src/server.ts +++ b/src/server.ts @@ -125,14 +125,19 @@ export async function buildServer(ctx: AppContext): Promise { }); // ---------------------------------------------------------------- auth --- - app.addHook("preHandler", requireApiKey(ctx.config)); + // `onRequest`, not `preHandler`: Fastify parses the body between `preParsing` + // and `preHandler`, so a `preHandler` authenticator lets an anonymous caller + // make the gateway buffer and JSON-parse up to `bodyLimitBytes`. Registered + // after the CORS hooks above, so a preflight is still answered without a key. + app.addHook("onRequest", requireApiKey(ctx.config)); // --------------------------------------------------------- rate limit --- - // Beside `requireApiKey`, so a rejected caller is counted against its own - // bucket only after authentication; `/admin/*` has a separate bucket. + // Beside `requireApiKey`, and for the same reason an `onRequest` hook: the + // limiter charges the caller before any body is read, and `/admin/*` has a + // separate bucket. const limiters = createRateLimiters(ctx.config); app.addHook( - "preHandler", + "onRequest", requireRateLimit(ctx.config, limiters, (scope) => { ctx.metrics.rateLimitRejections.inc({ scope }); }), @@ -140,7 +145,8 @@ export async function buildServer(ctx: AppContext): Promise { // ------------------------------------------------------------- timeout --- // Buffered routes get a bounded socket timeout; streaming routes stay - // unbounded so a long SSE answer is never cut off. + // unbounded so a long SSE answer is never cut off. This must stay a + // `preHandler` because the bound depends on the parsed request body. app.addHook("preHandler", async (request, reply) => { applyRequestTimeout(request, reply, ctx.config); }); @@ -223,12 +229,18 @@ export async function buildServer(ctx: AppContext): Promise { "POST /v1/messages/count_tokens", "GET /v1/models", "GET /v1/models/{id}", + "GET /v1/models/*", "POST /v1/embeddings", "GET /health", "GET /ready", + "GET /healthz", "GET /metrics", "GET /admin/status", "GET /admin/config", + "POST /admin/models/refresh", + "GET /admin/sessions", + "DELETE /admin/sessions", + "POST /admin/upstream/restart", ], })); diff --git a/test/regressions.test.ts b/test/regressions.test.ts index 55692cf..f4db4e0 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -5,7 +5,9 @@ import { describe, expect, it } from "vitest"; import http from "node:http"; import type { AddressInfo } from "node:net"; +import { canonicalPath } from "../src/auth.js"; import { ApiError } from "../src/errors.js"; +import { MAX_RATE_LIMIT_BUCKETS, TokenBucketLimiter } from "../src/http/rateLimit.js"; import { isPrivateHost } from "../src/media/resolve.js"; import { buildServer } from "../src/server.js"; import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; @@ -765,4 +767,213 @@ describe("HTTP metrics label cardinality", () => { expect(exposition).not.toContain("random-path-abc-123"); expect(exposition).not.toContain("another-path-zzz-456"); }); +}); + +describe("P-01 request bodies are not parsed before authentication", () => { + const oversized = (): string => + JSON.stringify({ model: MODEL, messages: [{ role: "user", content: "x".repeat(4_096) }] }); + + it("answers an unauthenticated oversized POST with 401 instead of 413", async () => { + const ctx = createTestContext({ config: { bodyLimitBytes: 1_024 } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: { "content-type": "application/json" }, + payload: oversized(), + }); + // The body limit is a parser option, so a 413 here would mean the gateway + // buffered a body for a caller that never presented a credential. + expect(response.statusCode).toBe(401); + } finally { + await app.close(); + } + }); + + it("answers unauthenticated malformed JSON with 401 instead of 400", async () => { + const ctx = createTestContext({ config: { bodyLimitBytes: 1_024 } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: { "content-type": "application/json" }, + payload: '{"model":', + }); + // Reaching the parser would mean the JSON error is visible without a key. + expect(response.statusCode).toBe(401); + } finally { + await app.close(); + } + }); + + it("still enforces the body limit for an authenticated caller", async () => { + const ctx = createTestContext({ config: { bodyLimitBytes: 1_024 } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: { ...AUTH, "content-type": "application/json" }, + payload: oversized(), + }); + expect(response.statusCode).toBe(413); + } finally { + await app.close(); + } + }); + + it("lets an authenticated caller reach the handler", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "hi" }] }, + }); + expect(response.statusCode).toBe(200); + expect((response.json() as { choices: unknown[] }).choices).toHaveLength(1); + } finally { + await app.close(); + } + }); +}); + +describe("P-02 rate-limit buckets for credential-less callers", () => { + it("does not share one bucket between two client addresses", async () => { + const ctx = createTestContext({ config: { allowNoAuth: true, rateLimitRpm: 1, rateLimitBurst: 1 } }); + const app = await buildServer(ctx); + try { + const first = await app.inject({ method: "GET", url: "/v1/models", remoteAddress: "198.51.100.10" }); + expect(first.statusCode).toBe(200); + + // The same bucket for both addresses would answer 429 here. + const second = await app.inject({ method: "GET", url: "/v1/models", remoteAddress: "198.51.100.20" }); + expect(second.statusCode).toBe(200); + + const exhausted = await app.inject({ method: "GET", url: "/v1/models", remoteAddress: "198.51.100.10" }); + expect(exhausted.statusCode).toBe(429); + expect((exhausted.json() as { error: { type: string } }).error.type).toBe("rate_limit_error"); + + // A fresh address must not inherit another address' rejection... + const fresh = await app.inject({ method: "GET", url: "/v1/models", remoteAddress: "198.51.100.30" }); + expect(fresh.statusCode).toBe(200); + + // ...and the second address keeps its own spent budget. + const spent = await app.inject({ method: "GET", url: "/v1/models", remoteAddress: "198.51.100.20" }); + expect(spent.statusCode).toBe(429); + } finally { + await app.close(); + } + }); + + it("keeps the bucket map bounded when the key space rotates", () => { + const limiter = new TokenBucketLimiter({ rpm: 60, burst: 1 }); + for (let index = 0; index < MAX_RATE_LIMIT_BUCKETS + 25; index += 1) { + limiter.take(`ip:198.51.100.${index}`); + } + expect(limiter.size).toBe(MAX_RATE_LIMIT_BUCKETS); + }); + + it("drops the oldest bucket when the cap is reached", () => { + const limiter = new TokenBucketLimiter({ rpm: 60, burst: 1, maxBuckets: 2 }); + limiter.take("ip:a"); + limiter.take("ip:b"); + limiter.take("ip:c"); + + expect(limiter.size).toBe(2); + // `ip:a` was evicted; `ip:c` is the newest and still limited. + expect(limiter.take("ip:c")).toBeDefined(); + expect(limiter.take("ip:b")).toBeDefined(); + }); +}); + +describe("P-03 public-path canonicalisation", () => { + it("canonicalises the path used for public-path checks", () => { + expect(canonicalPath("/metrics/")).toBe("/metrics"); + expect(canonicalPath("//metrics")).toBe("/metrics"); + expect(canonicalPath("/health//")).toBe("/health"); + expect(canonicalPath("/v1/models?refresh=1")).toBe("/v1/models"); + expect(canonicalPath("/")).toBe("/"); + expect(canonicalPath("//")).toBe("/"); + expect(canonicalPath("")).toBe("/"); + }); + + it("treats differently spelled public paths as public", async () => { + const ctx = createTestContext({ config: { metricsEnabled: true, metricsPublic: true } }); + const app = await buildServer(ctx); + try { + const canonical = await app.inject({ method: "GET", url: "/metrics" }); + expect(canonical.statusCode).toBe(200); + + for (const url of ["/metrics/", "/health/", "//metrics"]) { + const response = await app.inject({ method: "GET", url }); + // Not 401 and not 200: the auth decision is canonical, while the router + // itself still does not match these spellings. Answering 401 here would + // fingerprint whether `/metrics` is public. + expect(response.statusCode).toBe(404); + } + } finally { + await app.close(); + } + }); +}); + +/** Normalise one `GET /v1/models/{id}` index entry to `GET /v1/models/:id`. */ +function indexEntry(entry: string): string { + const [method = "", path = ""] = entry.trim().split(/\s+/); + return `${method} ${path.replace("{id}", ":id")}`; +} + +/** + * Every route the finished server registers, as `METHOD /path`. + * + * `printRoutes({ commonPrefix: false })` prints one node per line with a + * four-column indent per tree level and the methods in trailing parentheses; + * the path is rebuilt by concatenating the segments down to that level. + */ +function registeredRoutes(app: Awaited>): Set { + const routes = new Set(); + const segments: string[] = []; + for (const line of app.printRoutes({ commonPrefix: false }).split("\n")) { + const connector = line.search(/(?:├── |└── )/); + if (connector < 0) continue; + const parsed = /^(.+) \(([A-Z, ]+)\)$/.exec(line.slice(connector + 4)); + if (parsed === null) continue; + const depth = connector / 4; + segments.length = depth; + // `printRoutes` labels a wildcard node with a bare `*`, losing the `/` the + // registered route path has in front of it. + segments[depth] = parsed[1] === "*" ? "/*" : (parsed[1] ?? ""); + const path = depth === 0 ? "/" : `/${segments.slice(1).join("")}`; + for (const method of (parsed[2] ?? "").split(", ")) { + // Fastify exposes a HEAD route next to every GET; it is not in the index. + if (method === "HEAD") continue; + routes.add(`${method} ${path}`); + } + } + return routes; +} + +describe("P-14 GET / route index", () => { + it("lists exactly the routes the server registers", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + await app.ready(); + const body = (await app.inject({ method: "GET", url: "/" })).json() as { endpoints: string[] }; + const listed = body.endpoints.map(indexEntry).sort(); + + const registered = registeredRoutes(app); + // The index is served by `GET /` itself and therefore does not list it. + registered.delete("GET /"); + + expect(listed).toEqual([...registered].sort()); + } finally { + await app.close(); + } + }); }); \ No newline at end of file From 3312156fc67a554a57b53ee9b83ac0a494eebe3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:26 +0700 Subject: [PATCH 02/10] fix(events): keep a healthy stream and bound its buffer `AbortSignal.timeout()` cannot be disarmed and undici keeps the signal attached to the response body, so the connect-phase watchdog aborted every healthy `/api/event` stream after 45 s. Each reconnect marked a stream gap for every in-flight turn, which then failed with `503 event_stream_lost` when its terminal event did not arrive within the grace window. The connect deadline is now a cancellable timer that is cleared once the response head arrives; reads stay bounded by the same watchdog. The frame-assembly buffer was also unbounded and rescanned from offset zero on every chunk, so a stream without a blank line grew without limit and cost quadratic CPU. It is capped at 1 MiB: an oversized partial frame is dropped and counted instead of retained. Finally, `stop()` retires the running loop with a generation stamp so a racing `start()` cannot leave two consumers on the same response body. --- src/upstream/events.ts | 168 ++++++++++++++++++++++++++++++----------- test/events.test.ts | 112 +++++++++++++++++++++++++++ 2 files changed, 236 insertions(+), 44 deletions(-) diff --git a/src/upstream/events.ts b/src/upstream/events.ts index dcb7ae4..7f572f5 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -34,6 +34,17 @@ const MAX_RECONNECT_DELAY_MS = 5_000; */ const HEALTHY_CONNECTION_MS = 5_000; +/** + * Hard cap on the unterminated frame remainder kept between reads. + * + * A stream that never sends a blank line would otherwise grow the buffer without + * bound, and every chunk would rescan the whole buffer (`findBoundary()` runs from + * offset 0), i.e. O(buffer) per chunk and quadratic CPU for the life of the + * stream. An upstream frame is a few KiB at most, so 1 MiB is far above any + * legitimate frame while keeping the rescan cost flat. + */ +const MAX_FRAME_BUFFER_BYTES = 1024 * 1024; + type ReconnectReason = "idle" | "ended" | "rejected"; export interface EventHubOptions { @@ -49,6 +60,16 @@ export class EventHub { #controller?: AbortController; #running = false; + /** + * Incremented by `stop()`; every loop stamps the generation it was started + * with and exits as soon as it no longer matches. + * + * Without this, a `stop()` while the loop is parked in the reconnect delay + * followed by a `start()` leaves the old loop alive: it wakes up, observes + * `#running === true` again and consumes a second upstream stream in parallel, + * delivering every frame twice. + */ + #generation = 0; #connected = false; #reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; /** When `server.connected` was parsed on the current connection. */ @@ -90,11 +111,16 @@ export class EventHub { start(): void { if (this.#running) return; this.#running = true; - void this.#loop(); + const generation = this.#generation; + void this.#loop(generation); } async stop(): Promise { this.#running = false; + // Invalidate the current loop *before* aborting: a loop parked in the + // reconnect delay would otherwise wake up after a later `start()`, still see + // `#running === true` and reconnect next to the loop that replaced it. + this.#generation += 1; this.#controller?.abort(); this.#controller = undefined; this.#connected = false; @@ -149,59 +175,99 @@ export class EventHub { return () => this.#reconnectListeners.delete(listener); } - async #loop(): Promise { - while (this.#running) { + async #loop(generation: number): Promise { + while (this.#isCurrentLoop(generation)) { this.#dropReason = undefined; try { - await this.#connectOnce(); + await this.#connectOnce(generation); } catch (error) { - if (!this.#running) return; + if (!this.#isCurrentLoop(generation)) return; this.#log.debug({ err: error instanceof Error ? error.message : String(error) }, "event stream ended"); - } finally { - const wasConnected = this.#connected; - const connectedAt = this.#connectedAt; - const reason = this.#dropReason ?? "ended"; - this.#connected = false; - this.#connectedAt = undefined; - if (wasConnected) { - this.#metrics.eventStream.set(0); - this.#metrics.eventStreamReconnects.inc({ reason }); - for (const listener of this.#reconnectListeners) { - try { - listener(); - } catch { - /* listener errors must not kill the hub */ - } - } - // A connection that survived long enough to prove it works resets the - // backoff; a flapping one keeps doubling it. - const lifetime = connectedAt === undefined ? 0 : Date.now() - connectedAt; - if (lifetime >= HEALTHY_CONNECTION_MS) this.#reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; - } } - if (!this.#running) return; + // A `stop()` replaced this loop while it was parked: never reconnect next + // to the new one, and never touch shared state on its behalf. + if (!this.#isCurrentLoop(generation)) return; + this.#recordDisconnect(); await delay(this.#reconnectDelayMs); + if (!this.#isCurrentLoop(generation)) return; if (this.#reconnectDelayMs < MAX_RECONNECT_DELAY_MS) this.#reconnectDelayMs *= 2; } } - async #connectOnce(): Promise { + /** Whether `generation` still owns the hub; `stop()` retires it. */ + #isCurrentLoop(generation: number): boolean { + return this.#running && this.#generation === generation; + } + + /** Book-keeping for a connection that just ended, run only by the live loop. */ + #recordDisconnect(): void { + const wasConnected = this.#connected; + const connectedAt = this.#connectedAt; + const reason = this.#dropReason ?? "ended"; + this.#connected = false; + this.#connectedAt = undefined; + if (!wasConnected) return; + this.#metrics.eventStream.set(0); + this.#metrics.eventStreamReconnects.inc({ reason }); + for (const listener of this.#reconnectListeners) { + try { + listener(); + } catch { + /* listener errors must not kill the hub */ + } + } + // A connection that survived long enough to prove it works resets the + // backoff; a flapping one keeps doubling it. + const lifetime = connectedAt === undefined ? 0 : Date.now() - connectedAt; + if (lifetime >= HEALTHY_CONNECTION_MS) this.#reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; + } + + async #connectOnce(generation: number): Promise { const endpoint = await this.#upstream.resolve(); - if (!this.#running) return; + if (!this.#isCurrentLoop(generation)) return; const controller = new AbortController(); this.#controller = controller; - // The idle watchdog only wraps `reader.read()`, i.e. it is reached after the - // response head. A server that accepts the connection and never writes the - // head would park this `await` for undici's ~300 s header timeout, during - // which the hub is not connected and every turn fails with - // `503 event_stream_unavailable`. Bound the connect phase only. - const connect = AbortSignal.timeout(this.#idleTimeoutMs); - try { - const response = await fetch(`${endpoint.url}/api/event`, { - headers: { ...authHeaders(endpoint.password), accept: "text/event-stream", "cache-control": "no-cache" }, - signal: AbortSignal.any([controller.signal, connect]), - }); + // The idle watchdog only wraps `reader.read()`, i.e. it is reached after the + // response head. A server that accepts the connection and never writes the + // head would park this `await` for undici's ~300 s header timeout, during + // which the hub is not connected and every turn fails with + // `503 event_stream_unavailable`. Bound the connect phase only. + // + // `AbortSignal.timeout()` cannot be disarmed and undici keeps the signal on + // the response body, so attaching it to `fetch` used to abort a healthy + // stream one `idleTimeoutMs` after it opened. The timer aborts the same + // controller `stop()` uses and is cleared as soon as the head arrives. + let connectTimedOut = false; + const connectTimer = setTimeout(() => { + connectTimedOut = true; + controller.abort(); + }, this.#idleTimeoutMs); + // The watchdog must not keep the process alive on its own. + connectTimer.unref?.(); + + let response: Response; + try { + response = await fetch(`${endpoint.url}/api/event`, { + headers: { ...authHeaders(endpoint.password), accept: "text/event-stream", "cache-control": "no-cache" }, + signal: controller.signal, + }); + } catch (error) { + if (connectTimedOut) throw new Error(`event stream connect timed out after ${this.#idleTimeoutMs} ms`); + throw error; + } finally { + // The head arrived (or the attempt failed): reading is bounded per chunk + // by `withIdleDeadline()` from here on, so the connect deadline must + // never fire again. + clearTimeout(connectTimer); + } + + if (!this.#isCurrentLoop(generation)) { + // A `stop()` (or a stop+start) retired this loop while the head was in + // flight: release the body instead of leaving an unread SSE connection. + await response.body?.cancel().catch(() => undefined); + return; + } if (!response.ok || !response.body) { this.#dropReason = "rejected"; @@ -219,7 +285,7 @@ export class EventHub { let buffer = ""; try { - while (this.#running) { + while (this.#isCurrentLoop(generation)) { // A socket that is half-open after the upstream died never rejects // `read()`, so each read is bounded by the idle watchdog: on expiry the // stream fails and `#loop` reconnects instead of hanging forever. @@ -237,18 +303,32 @@ export class EventHub { this.#handleFrame(frame); boundary = findBoundary(buffer); } + + if (buffer.length > MAX_FRAME_BUFFER_BYTES) { + // No blank line in over a megabyte: the partial frame is unusable, and + // keeping it would grow without bound while every chunk rescans it. + // Drop it and start the next frame from a clean buffer. + this.#metrics.eventFramesDropped.inc({ reason: "malformed" }); + this.#log.debug({ bytes: buffer.length }, "dropping oversized event frame"); + buffer = ""; + // Discard the bytes of a split UTF-8 code point that belong to the + // dropped frame, so they cannot prefix the next one. + decoder.decode(); + } } } catch (error) { // Only the idle watchdog rejects here; a `stop()`-aborted read settles // through `reader.cancel()` below. - this.#dropReason = "idle"; + if (this.#isCurrentLoop(generation)) this.#dropReason = "idle"; throw error; } finally { - // Release the response body on every exit path; without this a stop() or a - // reconnect leaks one upstream SSE consumer. + // Release the response body on every exit path; without this a stop() or + // a reconnect leaks one upstream SSE consumer. await reader.cancel().catch(() => undefined); } } finally { + // Only the live attempt may drop the reference: a stale loop must not + // disarm the controller of the loop that replaced it. if (this.#controller === controller) this.#controller = undefined; } } diff --git a/test/events.test.ts b/test/events.test.ts index b22299f..a0dd6c6 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -444,6 +444,118 @@ describe("EventHub", () => { 3_000, ); }); + + it("keeps a healthy stream connected past several idle-timeout periods", async () => { + const idleTimeoutMs = 500; + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // A healthy upstream keeps the idle watchdog satisfied with heartbeats. The + // connect watchdog used to be an un-cancellable `AbortSignal.timeout()` that + // stayed attached to the response body, so it aborted this stream at the + // first deadline (45 s in production) and forced a reconnect under every + // in-flight turn. + const timer = setInterval(() => response.write(": heartbeat\n\n"), 50); + return () => clearInterval(timer); + }, { idleTimeoutMs }); + active.push(item); + + item.hub.start(); + expect(await item.hub.ensureConnected(2_000)).toBe(true); + + // Stay connected for three full idle periods: the body must never be aborted. + await delay(idleTimeoutMs * 3); + + expect(item.connectionCount()).toBe(1); + expect(item.closedCount()).toBe(0); + expect(item.hub.connected).toBe(true); + expect(await gaugeValue(item.metrics, "opencode_api_event_stream_connected")).toBe(1); + expect( + await counterValue(item.metrics, "opencode_api_event_stream_reconnects_total", { reason: "idle" }), + ).toBe(0); + }); + + it("drops an unterminated frame past the buffer cap and stays connected", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // More than the 1 MiB assembly cap without a single blank line: the partial + // frame is unusable, so it must be dropped instead of retained, and the hub + // must keep consuming the stream. + response.write(": heartbeat\n".repeat(120_000)); + // Terminate the partial line left in the buffer, then send a real frame. + response.write("\n"); + response.write(frame({ id: "e1", type: "session.text.delta", data: { sessionID: "ses_1", delta: "ok" } })); + return () => undefined; + }); + active.push(item); + + const deltas: unknown[] = []; + item.hub.subscribe("ses_1", (event) => deltas.push((event.data as { delta?: unknown }).delta)); + item.hub.start(); + + await waitFor(() => deltas.length === 1); + expect(deltas).toEqual(["ok"]); + + // The oversized partial frame is counted as malformed, the buffer was reset + // (the frame above could only parse from a clean buffer), and the connection + // survived: no reconnect, no close. + expect( + await counterValue(item.metrics, "opencode_api_event_frames_dropped_total", { reason: "malformed" }), + ).toBeGreaterThanOrEqual(1); + expect(item.connectionCount()).toBe(1); + expect(item.closedCount()).toBe(0); + expect(item.hub.connected).toBe(true); + }); + + it("keeps one event loop after stop() followed by start()", async () => { + let live = 0; + let maxLive = 0; + const item = await fixture((response, connection) => { + live += 1; + maxLive = Math.max(maxLive, live); + let released = false; + response.on("close", () => { + if (released) return; + released = true; + live -= 1; + }); + + response.write(frame({ id: `e0-${connection}`, type: "server.connected", data: {} })); + if (connection === 1) { + // End the body: the loop drops into its reconnect delay, which is exactly + // where a stale loop used to wake up next to the loop a later `start()` + // had spawned, consuming a second upstream stream in parallel. + setImmediate(() => response.end()); + return () => undefined; + } + response.write(frame({ id: "e1", type: "session.text.delta", data: { sessionID: "ses_1", delta: "once" } })); + return () => undefined; + }); + active.push(item); + + const deltas: unknown[] = []; + item.hub.subscribe("ses_1", (event) => deltas.push((event.data as { delta?: unknown }).delta)); + item.hub.start(); + + expect(await item.hub.ensureConnected(2_000)).toBe(true); + // The first connection ended, so the loop is sleeping in its 250 ms backoff. + await waitFor(() => item.closedCount() === 1); + + // Replace the loop while it is parked in that delay. Pre-fix the old loop woke + // up, observed `#running === true` again and reconnected beside the new one. + await item.hub.stop(); + item.hub.start(); + + expect(await item.hub.ensureConnected(2_000)).toBe(true); + await waitFor(() => deltas.length >= 1); + // Past the stale loop's wake-up point. + await delay(600); + + // Both loops used to read a stream and deliver the same frame, and both + // upstream connections were open at once. + expect(deltas).toEqual(["once"]); + expect(maxLive).toBe(1); + expect(item.connectionCount()).toBe(2); + }); }); async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise { From 80ab4c48fbc2db3558401e44dc356381bdc97ce7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:26 +0700 Subject: [PATCH 03/10] fix(upstream): settle failed turns and bound the metrics `prepare()` ran outside the handler, so model resolution, modality validation, session creation and `upstream_unavailable` failures never reached `completions_total`, although the docs promise an outcome for every exit. Pre-flight failures are now counted once, with the resolved model or `unknown` when resolution itself failed. The `error_code` label was also filled verbatim from upstream payloads (`record.type` / `_tag`), which prom-client never evicts: every distinct tag became a permanent time series. The label is now a closed allow-list with `other` as the fallback. When a turn fails before it settles, its sticky record is released; for a session created for that turn no record exists yet, so the eviction hook never fired and the upstream session leaked for the life of the server. The same `finally` now deletes it, best effort, on every failed fresh turn. --- src/upstream/completion.ts | 189 +++++++++++++++++++++++++------ test/completion.test.ts | 220 ++++++++++++++++++++++++++++++++++++- 2 files changed, 372 insertions(+), 37 deletions(-) diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 16f774c..2aa3333 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -36,7 +36,7 @@ import type { } from "../types/opencode.js"; import type { OpencodeClient } from "./client.js"; import type { EventHub } from "./events.js"; -import type { ModelRegistry } from "./models.js"; +import type { ModelRegistry, ResolvedModel } from "./models.js"; import { hashTools, type AcquireResult, type SessionStore } from "./sessions.js"; export interface CompletionDeps { @@ -91,9 +91,12 @@ export interface CollectedCompletion { /** * Run one completion, emitting normalised events. * - * Errors raised while preparing (unknown model, unsupported modality) are - * thrown before any output; failures after the upstream turn has started are - * emitted as an `error` event so streaming callers can report them mid-stream. + * Errors raised while preparing (unknown model, unsupported modality, session + * creation) are thrown before any output; failures after the upstream turn has + * started are emitted as an `error` event so streaming callers can report them + * mid-stream. Every pre-flight failure is counted in `completions_total` with + * the model label that is actually known: `"unknown"` when resolution itself + * failed, the resolved `provider/model` otherwise. */ export async function* runCompletion( request: InternalRequest, @@ -101,47 +104,148 @@ export async function* runCompletion( options: CompletionOptions = {}, ): AsyncGenerator { const agent = request.agent ?? deps.config.agent; - const prepared = await prepare(request, deps, agent, { forceFresh: false }); + let resolved: ResolvedModel | undefined; + let prepared: Prepared | undefined; try { - yield* execute(prepared, deps, options); - } catch (error) { - const apiError = toApiError(error, "OpenCode completion failed."); - if (prepared.reused && isStaleSession(apiError)) { - deps.log.info({ sessionId: prepared.sessionId }, "sticky session vanished upstream; replaying on a new session"); - deps.sessions.invalidate(prepared.key, "stale-session", prepared.sessionId); - // The replay is itself fallible. `execute()` releases its own record in - // `finally`, so never let a replay failure escape the generator: surface - // it as an `error` event and make sure the fresh slot is not left busy. - let fresh: Prepared | undefined; - try { - fresh = await prepare(request, deps, agent, { forceFresh: true, ...(options.signal ? { signal: options.signal } : {}) }); - yield* execute(fresh, deps, options); - } catch (replayError) { - const replayApiError = toApiError(replayError, "OpenCode completion replay failed."); - if (fresh) deps.sessions.release(fresh.key, fresh.sessionId, false); - recordCompletionFailure(deps, prepared, replayApiError); - yield { kind: "error", error: replayApiError }; + // Model resolution and the rest of the pre-flight work sit inside the same + // `try` so a failure in either is counted exactly once; `prepared` staying + // `undefined` is what distinguishes a pre-flight failure below. + resolved = await deps.models.resolve(request.model); + prepared = await prepare(resolved, request, deps, agent, { forceFresh: false }); + + try { + yield* execute(prepared, deps, options); + } catch (error) { + const apiError = toApiError(error, "OpenCode completion failed."); + if (prepared.reused && isStaleSession(apiError)) { + deps.log.info({ sessionId: prepared.sessionId }, "sticky session vanished upstream; replaying on a new session"); + deps.sessions.invalidate(prepared.key, "stale-session", prepared.sessionId); + // The replay is itself fallible. `execute()` releases its own record in + // `finally`, so never let a replay failure escape the generator: surface + // it as an `error` event and make sure the fresh slot is not left busy. + let fresh: Prepared | undefined; + try { + fresh = await prepare(resolved, request, deps, agent, { forceFresh: true, ...(options.signal ? { signal: options.signal } : {}) }); + yield* execute(fresh, deps, options); + } catch (replayError) { + const replayApiError = toApiError(replayError, "OpenCode completion replay failed."); + if (fresh) deps.sessions.release(fresh.key, fresh.sessionId, false); + recordCompletionFailure(deps, request, resolved.canonical, replayApiError); + yield { kind: "error", error: replayApiError }; + } + return; } - return; + deps.sessions.release(prepared.key, prepared.sessionId, false); + recordCompletionFailure(deps, request, prepared.resolved.canonical, apiError); + yield { kind: "error", error: apiError }; } - deps.sessions.release(prepared.key, prepared.sessionId, false); - recordCompletionFailure(deps, prepared, apiError); - yield { kind: "error", error: apiError }; + } catch (error) { + // Pre-flight failure: model resolution, modality validation or session + // creation. Before this, `prepare()` ran outside any handler, so those exits + // never reached `completions_total` at all (`docs/API.md` and + // `docs/ARCHITECTURE.md` §4.3 promise an outcome for every exit). The thrown + // error is passed through unchanged. + if (prepared !== undefined) throw error; + recordPreflightFailure(deps, request, resolved?.canonical ?? "unknown", error); + throw error; } } +/** + * Count a pre-flight failure — anything thrown before `execute()` can report + * its own outcome, including model resolution, modality validation and session + * creation. + */ +function recordPreflightFailure(deps: CompletionDeps, request: InternalRequest, model: string, error: unknown): void { + recordCompletionFailure(deps, request, model, toApiError(error, "OpenCode completion failed.")); +} + /** Count a turn that failed before `execute()` could report its own outcome. */ -function recordCompletionFailure(deps: CompletionDeps, prepared: Prepared, error: ApiError): void { +function recordCompletionFailure( + deps: CompletionDeps, + request: InternalRequest, + model: string, + error: ApiError, +): void { deps.metrics.completions.inc({ - surface: prepared.request.surface, - model: prepared.resolved.canonical, - stream: String(prepared.request.stream), + surface: request.surface, + model, + stream: String(request.stream), finish_reason: "error", - error_code: error.code, + error_code: metricErrorCode(error.code, deps.log), }); } +/** + * Closed set of `error_code` label values, so a chatty or compromised upstream + * cannot grow the prom-client registry without bound (`docs/ARCHITECTURE.md` + * §4.3 promises a bounded label). + */ +const COMPLETION_ERROR_CODES: readonly string[] = [ + // Gateway error codes (`ApiError.code`). + "invalid_request", + "unsupported_parameter", + "unsupported_file_reference", + "unsupported_modality", + "invalid_attachment", + "attachment_omitted", + "attachment_download_failed", + "attachment_too_large", + "attachment_not_found", + "attachment_path_forbidden", + "remote_media_disabled", + "local_files_disabled", + "private_media_blocked", + "model_not_found", + "model_disabled", + "rate_limit_exceeded", + "metrics_disabled", + "event_stream_unavailable", + "event_stream_lost", + "upstream_unauthorized", + "upstream_invalid_json", + "upstream_timeout", + "upstream_unreachable", + "upstream_unavailable", + // Provider codes documented in `docs/API.md` and `docs/ARCHITECTURE.md` §2. + "provider.free-limit", + "provider.rate-limit", + "provider.unavailable", + "provider.not-found", + "provider.error", + "overloaded_error", + // The `ApiError.kind` values, used whenever a caller did not set an explicit code. + "invalid_request_error", + "authentication_error", + "permission_error", + "not_found_error", + "rate_limit_error", + "upstream_error", + "timeout_error", + "internal_error", + "not_implemented_error", +]; + +const COMPLETION_ERROR_CODE_SET: ReadonlySet = new Set(COMPLETION_ERROR_CODES); +const OTHER_ERROR_CODE = "other"; +const HTTP_STATUS_CODE = /^http_\d{3}$/; + +/** + * Map an `ApiError.code` onto a bounded `error_code` label. + * + * The code is copied verbatim from upstream payloads (`record.type` / `_tag`) + * in several paths, so anything outside the allow-list becomes `"other"` and + * the raw value is logged at debug level instead of becoming a time series. + * An empty code (a successful turn) is passed through unchanged. + */ +function metricErrorCode(code: string, log: Logger): string { + if (code === "") return code; + if (COMPLETION_ERROR_CODE_SET.has(code) || HTTP_STATUS_CODE.test(code)) return code; + log.debug({ code }, "unmapped upstream error code reported as other"); + return OTHER_ERROR_CODE; +} + /** Run a completion and aggregate the events into a single response. */ export async function collectCompletion( request: InternalRequest, @@ -217,6 +321,7 @@ export async function collectCompletion( } async function prepare( + resolved: ResolvedModel, request: InternalRequest, deps: CompletionDeps, agent: string, @@ -224,7 +329,6 @@ async function prepare( ): Promise { const { client, config, models, sessions } = deps; - const resolved = await models.resolve(request.model); const modelInfo = resolved.info; const variants = models.variantsOf(modelInfo); const decision = resolveVariant({ @@ -349,7 +453,10 @@ async function* execute( model: prepared.resolved.canonical, stream: String(prepared.request.stream), finish_reason: finishReason, - error_code: errorCode, + // `errorCode` is an `ApiError.code`, which several paths copy verbatim + // from the upstream payload (`record.type` / `_tag`); the label is closed + // so a chatty upstream cannot grow the registry without bound. + error_code: metricErrorCode(errorCode, log), }); }; const recordError = (error: ApiError): void => { @@ -701,6 +808,20 @@ async function* execute( // every later request for that conversation would be forced onto a fresh // session (or, worse, blocked). if (!sessionSettled) sessions.release(key, sessionId, false); + // A session created for this turn has no record to evict yet, so `release()` + // above finds nothing and the eviction hook never fires. Without this the + // upstream session outlives the failed turn for the life of `opencode serve` + // — one orphan per failed first turn. Best-effort, after the interrupt paths + // that already ran inside the loop; reused sessions keep being deleted by the + // session-store eviction hook. + if (!sessionSettled && !prepared.reused) { + void client.deleteSession(sessionId).catch((error: unknown) => { + log.debug( + { sessionId, err: error instanceof Error ? error.message : String(error) }, + "could not delete the upstream session of a failed turn", + ); + }); + } } } diff --git a/test/completion.test.ts b/test/completion.test.ts index 2d76297..08e9e68 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -4,7 +4,12 @@ import type { AddressInfo } from "node:net"; import { createLogger } from "../src/logger.js"; import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import { ApiError } from "../src/errors.js"; -import { BRIDGE_DENIED_ACTIONS, collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; +import { + BRIDGE_DENIED_ACTIONS, + collectCompletion, + runCompletion, + type CompletionDeps, +} from "../src/upstream/completion.js"; import { EventHub, type EventListener } from "../src/upstream/events.js"; import { ModelRegistry } from "../src/upstream/models.js"; import { SessionStore, deriveKey } from "../src/upstream/sessions.js"; @@ -23,6 +28,8 @@ interface Harness { promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }>; /** Options every `prompt()` call received. */ promptOptions: Array<{ signal?: AbortSignal }>; + /** Session ids passed to `client.deleteSession()`. */ + deletedSessions: string[]; /** A promise that resolves once `prompt()` has been called at least once. */ waitForPrompt: () => Promise; } @@ -54,7 +61,12 @@ function matches(labels: Record, expected: Record OpencodeEvent[], configOverrides: Parameters[0] = {}, - options: { ensureConnected?: () => Promise; promptAbortsWithSignal?: boolean } = {}, + options: { + ensureConnected?: () => Promise; + promptAbortsWithSignal?: boolean; + /** Fail `prompt()` with this error after its first successful call. */ + failPromptsAfterFirst?: () => Error; + } = {}, ): Harness { const config = testConfig({ modelCacheTtlMs: 60_000, ...configOverrides }); const log = createLogger(config); @@ -64,6 +76,7 @@ function harness( const createSessionCalls: Array> = []; const promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }> = []; const promptOptions: Array<{ signal?: AbortSignal }> = []; + const deletedSessions: string[] = []; let markPrompted: () => void = () => undefined; const prompted = new Promise((resolve) => { markPrompted = resolve; @@ -103,6 +116,11 @@ function harness( promptCalls.push({ sessionId, text, files }); promptOptions.push(requestOptions); markPrompted(); + if (options.failPromptsAfterFirst !== undefined && promptCalls.length > 1) { + // The upstream rejects the turn after the session was created: the + // orchestrator sees a failure with a fresh (never committed) session. + throw options.failPromptsAfterFirst(); + } if (options.promptAbortsWithSignal === true) { // Never resolves on its own: only the caller's signal can settle it, // exactly like a real request against a hung upstream. @@ -125,7 +143,8 @@ function harness( async interrupt() { return undefined; }, - async deleteSession() { + async deleteSession(sessionId: string) { + deletedSessions.push(sessionId); return undefined; }, } as unknown as OpencodeClient; @@ -140,6 +159,7 @@ function harness( createSessionCalls, promptCalls, promptOptions, + deletedSessions, waitForPrompt: async () => { await prompted; }, @@ -791,6 +811,200 @@ describe("completion outcome metrics", () => { expect(series[0]?.labels["finish_reason"]).toBe("stop"); expect(series[0]?.labels["error_code"]).toBe(""); }); + + it("lands every upstream-controlled error code on the same bounded label", async () => { + // The closed `error_code` allow-list is a documented contract + // (`docs/ARCHITECTURE.md` §4.3), so these are the only values a failure may + // put in the label. Two arbitrary upstream `type` values must not each become + // a new time series in the prom-client registry. + const allowed = new Set([ + "invalid_request", + "unsupported_parameter", + "unsupported_file_reference", + "unsupported_modality", + "invalid_attachment", + "attachment_omitted", + "attachment_download_failed", + "attachment_too_large", + "attachment_not_found", + "attachment_path_forbidden", + "remote_media_disabled", + "local_files_disabled", + "private_media_blocked", + "model_not_found", + "model_disabled", + "rate_limit_exceeded", + "metrics_disabled", + "event_stream_unavailable", + "event_stream_lost", + "upstream_unauthorized", + "upstream_invalid_json", + "upstream_timeout", + "upstream_unreachable", + "upstream_unavailable", + "provider.free-limit", + "provider.rate-limit", + "provider.unavailable", + "provider.not-found", + "provider.error", + "overloaded_error", + "invalid_request_error", + "authentication_error", + "permission_error", + "not_found_error", + "rate_limit_error", + "upstream_error", + "timeout_error", + "internal_error", + "not_implemented_error", + "other", + "", + ]); + + const seen: string[] = []; + for (const upstreamType of ["made.up-1", "made.up-2", "made.up-3"]) { + const { deps, metrics } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.step.failed", { + assistantMessageID: "msg_a1", + error: { type: upstreamType, message: "upstream exploded.", status: 400 }, + }), + ]); + + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ status: 400 }); + + const failures = (await metricSeries(metrics, "opencode_api_completions_total")).filter((entry) => + matches(entry.labels, { finish_reason: "error" }), + ); + // Before the fix the label was the raw tag, so every arbitrary value made + // its own permanent series. + expect(failures).toHaveLength(1); + expect(failures[0]?.value).toBe(1); + const code = failures[0]?.labels["error_code"] ?? ""; + expect(allowed.has(code)).toBe(true); + seen.push(code); + } + // Three unrelated upstream strings share one bounded label value. + expect(new Set(seen)).toEqual(new Set(["other"])); + }); + + it("counts an unknown model exactly once with a bounded error code", async () => { + const { deps, metrics, createSessionCalls } = harness(() => simpleTurn("ok")); + + await expect(collectCompletion(request({ model: "opencode/nope" }), deps)).rejects.toMatchObject({ + status: 404, + code: "model_not_found", + }); + // The failure happens before any upstream session exists. + expect(createSessionCalls).toHaveLength(0); + + const failures = (await metricSeries(metrics, "opencode_api_completions_total")).filter((entry) => + matches(entry.labels, { finish_reason: "error" }), + ); + // Pre-fix `prepare()` ran outside the `try`, so a request that failed at + // model resolution recorded nothing at all and a gateway that failed every + // request looked idle. + expect(failures).toHaveLength(1); + expect(failures[0]?.value).toBe(1); + expect(failures[0]?.labels["model"]).toBe("unknown"); + expect(failures[0]?.labels["error_code"]).toBe("model_not_found"); + }); + + it("counts a pre-flight validation failure once with the resolved model", async () => { + const { deps, metrics, sessions } = harness(() => simpleTurn("ok")); + + await expect( + collectCompletion( + request({ + model: "opencode/big-pickle", + messages: [ + { role: "user", text: "look", attachments: [{ data: "AAAA", mime: "image/png", kind: "image", name: "a.png" }] }, + ], + }), + deps, + ), + ).rejects.toMatchObject({ status: 400, code: "unsupported_modality" }); + expect(sessions.list()).toHaveLength(0); + + const failures = (await metricSeries(metrics, "opencode_api_completions_total")).filter((entry) => + matches(entry.labels, { finish_reason: "error" }), + ); + // The model resolved, so the label names it instead of "unknown". + expect(failures).toHaveLength(1); + expect(failures[0]?.value).toBe(1); + expect(failures[0]?.labels["model"]).toBe("opencode/big-pickle"); + expect(failures[0]?.labels["error_code"]).toBe("unsupported_modality"); + }); +}); + +describe("orphaned upstream sessions", () => { + it("deletes the upstream session of a failed fresh turn exactly once", async () => { + const harnessed = harness(() => simpleTurn("unused"), {}, { + failPromptsAfterFirst: () => new ApiError(429, "rate_limit_error", "Free usage limit reached."), + }); + + // A successful first turn commits a record, so the second (failed) turn is + // the one under test and the session it uses was not created by it. + await collectCompletion(request({ conversationKey: "orphan-conv", messages: [{ role: "user", text: "Hello" }] }), harnessed.deps); + expect(harnessed.deletedSessions).toEqual([]); + + const failed = request({ + conversationKey: "orphan-fresh", + messages: [{ role: "user", text: "Hello" }], + }); + await expect(collectCompletion(failed, harnessed.deps)).rejects.toMatchObject({ status: 429 }); + + // `release()` finds no record for a session created for this turn, so the + // session-store eviction hook never fires: without the fix the upstream + // session outlived the failed turn for the life of `opencode serve`. + expect(harnessed.deletedSessions).toEqual(["ses_test"]); + expect(harnessed.sessions.list().map((record) => record.key)).not.toContain("orphan-fresh"); + }); + + it("does not delete the session of a failed reused turn", async () => { + const harnessed = harness(() => simpleTurn("Hi there"), {}, { + failPromptsAfterFirst: () => new ApiError(429, "rate_limit_error", "Free usage limit reached."), + }); + + // Turn 1 creates and commits the sticky session; turn 2 reuses it and then + // fails. A reused session is deleted by the eviction hook, not here. + await collectCompletion(request({ conversationKey: "reused-conv", messages: [{ role: "user", text: "Hello" }] }), harnessed.deps); + await expect( + collectCompletion( + request({ + conversationKey: "reused-conv", + messages: [ + { role: "user", text: "Hello" }, + { role: "assistant", text: "Hi there" }, + { role: "user", text: "again" }, + ], + }), + harnessed.deps, + ), + ).rejects.toMatchObject({ status: 429 }); + + expect(harnessed.deletedSessions).toEqual([]); + }); + + it("never deletes the session of a successful turn", async () => { + const harnessed = harness(() => simpleTurn("Hi there")); + + await collectCompletion(request({ conversationKey: "ok-conv", messages: [{ role: "user", text: "Hello" }] }), harnessed.deps); + await collectCompletion( + request({ + conversationKey: "ok-conv", + messages: [ + { role: "user", text: "Hello" }, + { role: "assistant", text: "Hi there" }, + { role: "user", text: "again" }, + ], + }), + harnessed.deps, + ); + + expect(harnessed.deletedSessions).toEqual([]); + expect(harnessed.sessions.list()).toHaveLength(1); + }); }); describe("caller abort propagation", () => { From f709421ccc3284c5957ff8352f0c0b887b84cba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:35 +0700 Subject: [PATCH 04/10] fix(upstream): bound the retained stderr tail Only completed stderr lines were capped, so an unterminated line (a child writing binary garbage, or simply never emitting a newline) grew `#partial` without bound and made every later chunk cost O(partial). The retained tail is now clamped to 8 KiB; an over-long line is diagnostic only. --- src/upstream/process.ts | 18 +++++++++++++++++- test/process.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/upstream/process.ts b/src/upstream/process.ts index d7d4d3a..d48be03 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -76,6 +76,15 @@ const VERSION_PATTERN = /opencode\s+v?(\d+\.\d+\.\d+\S*)/i; const OUTPUT_TAIL_CHARS = 4_096; /** How many recent stderr lines `status()` exposes. */ const STDERR_TAIL_LINES = 50; +/** + * How much of an unterminated stderr line is retained. + * + * Only the completed lines are bounded by the ring buffer, so an unterminated + * "line" (a child that writes binary garbage, or simply never emits a newline) + * used to grow `#partial` without limit and made every later chunk cost + * O(partial). An over-long line is diagnostic only, so only its tail is kept. + */ +const STDERR_PARTIAL_LIMIT_CHARS = 8_192; /** First failure window; doubles per consecutive failure up to the cap. */ const START_BACKOFF_BASE_MS = 1_000; const START_BACKOFF_MAX_MS = 30_000; @@ -135,7 +144,9 @@ export class StderrTail { } push(chunk: string): void { - this.#partial += chunk; + // Clamp before splitting so the buffer never grows past the cap, and each + // splice below stays O(partial) instead of O(total bytes ever written). + this.#partial = clampTail(this.#partial + chunk, STDERR_PARTIAL_LIMIT_CHARS); const parts = this.#partial.split("\n"); this.#partial = parts.pop() ?? ""; for (const part of parts) this.#append(part.replace(/\r$/, "")); @@ -161,6 +172,11 @@ export class StderrTail { } } +/** Keep at most the last `limit` characters, without copying a short string. */ +function clampTail(value: string, limit: number): string { + return value.length > limit ? value.slice(-limit) : value; +} + export class UpstreamProcess { /** * Instances that have spawned at least one child, and the single `process` diff --git a/test/process.test.ts b/test/process.test.ts index a4f5a45..32ed115 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -333,6 +333,35 @@ describe("UpstreamProcess", () => { expect(stderr.lines).toEqual(["line 6", "line 7", "line 8", "line 9"]); }); + it("clamps an unterminated stderr line and keeps the ring working", () => { + // `docs/ARCHITECTURE.md` §4.3 promises only the last ≤ 50 stderr lines; the + // partial (unterminated) line is clamped to the last 8 KiB. + const PARTIAL_CAP = 8 * 1024; + const stderr = new StderrTail(3); + + // 1 MiB with no newline used to be retained whole, and every later chunk + // cost O(partial) to concatenate and split. + stderr.push("x".repeat(1024 * 1024)); + stderr.push("tail-marker\n"); + + expect(stderr.lines).toHaveLength(1); + // Under the old code this line was ~1 MiB long. + expect(stderr.lines[0]?.length).toBeLessThanOrEqual(PARTIAL_CAP); + // The tail of the over-long line is kept, not its head. + expect(stderr.lines[0]?.endsWith("tail-marker")).toBe(true); + + // A chatty child cannot grow the partial buffer chunk by chunk either: 500 + // further chunks without a newline still produce one bounded line. + for (let index = 0; index < 500; index += 1) stderr.push("y".repeat(1024)); + stderr.push("\n"); + expect(stderr.lines).toHaveLength(2); + expect(stderr.lines[1]?.length).toBeLessThanOrEqual(PARTIAL_CAP); + + // The ring still works after the clamp. + for (let index = 0; index < 10; index += 1) stderr.push(`line ${index}\n`); + expect(stderr.lines).toEqual(["line 7", "line 8", "line 9"]); + }); + it("exposes the child's recent stderr through status()", async () => { const { process } = harness({ ready: false, stderr: "provider config invalid\ntoken missing\n" }); From 6df714ab84d046cac37f30a8402489ae9ca5fab0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:35 +0700 Subject: [PATCH 05/10] fix(models): keep the catalogue when a refresh is empty A forced refresh (`GET /v1/models?refresh=1`, `POST /admin/models/refresh`) or a TTL expiry that answered an empty model list cleared the previously good catalogue. Every later request then failed with `model_not_found` and paid the cold-start retry on each call until a non-empty answer happened to load. The previous catalogue is kept (with a refreshed timestamp) while the real, empty answer is still returned to the caller. --- src/upstream/models.ts | 31 ++++++++++++++------ test/openai-models.test.ts | 58 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/src/upstream/models.ts b/src/upstream/models.ts index 5395659..7bdd509 100644 --- a/src/upstream/models.ts +++ b/src/upstream/models.ts @@ -71,18 +71,33 @@ export class ModelRegistry { // An empty model list is never a usable catalogue: do not cache it, so the // next request picks the models up as soon as the provider registers them // (previously every request failed with `model_not_found` for the full - // cache TTL). - this.#catalog = catalog.models.length > 0 ? catalog : undefined; - if (catalog.models.length === 0) { - this.#log.warn( - { agents: catalog.agents.length }, - "OpenCode reported no models; the catalogue will be retried on the next request", - ); - } else { + // cache TTL). A single empty answer — a forced refresh + // (`GET /v1/models?refresh=1`, `POST /admin/models/refresh`) or a TTL + // expiry, both of which bypass the cache — must not discard a good + // catalogue either: keep the previous one and let the TTL decide when it + // expires, while still returning the real (empty) answer to the caller. + // One transient upstream hiccup otherwise turned every model call into + // `404 model_not_found` until a non-empty answer happened to load. + if (catalog.models.length > 0) { + this.#catalog = catalog; this.#log.debug( { models: catalog.models.length, agents: catalog.agents.length }, "refreshed model catalog", ); + } else if (this.#catalog) { + // Refresh the retained catalogue's timestamp: every request would + // otherwise see the entry as expired, re-read the empty answer and pay + // `#retryEmpty()` again while the provider is still cold. + this.#catalog = { ...this.#catalog, fetchedAt: catalog.fetchedAt }; + this.#log.warn( + { agents: catalog.agents.length, retained: this.#catalog.models.length }, + "OpenCode reported no models; keeping the previous catalogue", + ); + } else { + this.#log.warn( + { agents: catalog.agents.length }, + "OpenCode reported no models; the catalogue will be retried on the next request", + ); } return catalog; })().finally(() => { diff --git a/test/openai-models.test.ts b/test/openai-models.test.ts index fff4932..3b719e3 100644 --- a/test/openai-models.test.ts +++ b/test/openai-models.test.ts @@ -111,8 +111,8 @@ describe("GET /v1/models", () => { }); describe("ModelRegistry catalogue loading", () => { - function registry(client: Partial): ModelRegistry { - const config = testConfig({ modelCacheTtlMs: 60_000 }); + function registry(client: Partial, overrides: Partial> = {}): ModelRegistry { + const config = testConfig({ modelCacheTtlMs: 60_000, ...overrides }); return new ModelRegistry(client as unknown as OpencodeClient, config, createLogger(config)); } @@ -157,6 +157,60 @@ describe("ModelRegistry catalogue loading", () => { expect(calls).toBeGreaterThan(callsAfterFirst); }); + it("keeps the previous catalogue when a forced refresh returns no models", async () => { + const models = defaultModels(); + let current: typeof models = models; + let calls = 0; + const reg = registry({ + listModels: async () => { + calls += 1; + return current; + }, + listProviders: async () => [], + listAgents: async () => [agent], + }); + + // Warm the cache with a good catalogue. + expect((await reg.catalog()).models).toHaveLength(models.length); + expect(reg.cached?.models).toHaveLength(models.length); + + // A forced refresh (GET /v1/models?refresh=1, POST /admin/models/refresh) + // answers empty: the documented cold-start blip must not discard the good + // catalogue, but the caller still sees the real (empty) answer. + current = []; + const refreshed = await reg.catalog(true); + expect(refreshed.models).toHaveLength(0); + expect(calls).toBeGreaterThan(1); + + expect(reg.cached?.models).toHaveLength(models.length); + const resolved = await reg.resolve("opencode/big-pickle"); + expect(resolved.modelID).toBe("big-pickle"); + }); + + it("keeps the previous catalogue when an expired refresh returns no models", async () => { + const models = defaultModels(); + let current: typeof models = models; + const reg = registry( + { + listModels: async () => current, + listProviders: async () => [], + listAgents: async () => [agent], + }, + { modelCacheTtlMs: 1 }, + ); + + expect((await reg.catalog()).models).toHaveLength(models.length); + + // Let the cached entry expire and answer empty. Before the fix the refresh + // stored `undefined`, so nothing was left for the next request to fall back + // on and every model call failed with `model_not_found`. + await new Promise((resolve) => setTimeout(resolve, 10)); + current = []; + const refreshed = await reg.catalog(true); + expect(refreshed.models).toHaveLength(0); + expect(reg.cached?.models).toHaveLength(models.length); + }); + it("still retries an empty agent list", async () => { let agentCalls = 0; const reg = registry({ From 27d6660f08622640bfb43236ea1d588b81800872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:28:35 +0700 Subject: [PATCH 06/10] perf(sessions): serialise each message once per turn A turn hashes the conversation three times (acquire, commit and the root message in `deriveKey`), re-serialising every base64 media payload each time: about 40 ms of avoidable CPU and tens of MiB of transient strings per attachment-heavy turn. Per-message JSON is memoised by object identity and joined into the array form, which is byte-identical to `JSON.stringify(messages)` so persisted prefix hashes stay valid. `reusedCount` is incremented on commit as well: it was read from the record and never written, so `/admin/sessions` always reported 0. --- src/upstream/sessions.ts | 39 +++++++++++++- test/sessions.test.ts | 112 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+), 2 deletions(-) diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index 982b58e..f9276b2 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -258,7 +258,9 @@ export class SessionStore { createdAt: existing?.createdAt ?? Date.now(), lastUsedAt: Date.now(), busy: false, - reusedCount: existing?.reusedCount ?? 0, + // Reuse is the only signal that the sticky cache is working; without this + // `/admin/sessions` always reported `reusedCount: 0`. + reusedCount: existing ? existing.reusedCount + 1 : 0, }; const others = candidates.filter((candidate) => candidate.sessionId !== sessionId); @@ -598,8 +600,41 @@ export function deriveKey(input: AcquireInput): string { .slice(0, 32); } +/** + * Memoised `JSON.stringify` of one message, keyed by object identity. + * + * A turn hashes the same conversation several times: `acquire()` for every + * matching candidate, `commit()` for the record and `deriveKey()` for the root + * message. Re-serialising the whole array each time copied every base64 media + * payload again, so each message object is serialised at most once and the + * strings are reused. Weak keys let a message be collected with its hashes. + * + * Messages are built per request and never mutated after they are hashed, which + * is what makes the cached string authoritative for the object's lifetime. + */ +const messageJson = new WeakMap(); + +/** + * Serialise a message array exactly as `JSON.stringify(messages)` would. + * + * `JSON.stringify` of an array is `"[" + item,item + "]"` for every message + * shape this gateway builds, so joining the memoised per-message strings is + * byte-identical to stringifying the array. Persisted prefix hashes and session + * keys therefore stay compatible with hashes written by earlier versions. + */ +function serialiseMessages(messages: InternalMessage[]): string { + const parts = messages.map((message) => { + const cached = messageJson.get(message); + if (cached !== undefined) return cached; + const json = JSON.stringify(message); + messageJson.set(message, json); + return json; + }); + return `[${parts.join(",")}]`; +} + export function hashMessages(messages: InternalMessage[]): string { - return createHash("sha256").update(JSON.stringify(messages)).digest("hex"); + return createHash("sha256").update(serialiseMessages(messages)).digest("hex"); } /** Stable hash of tool definitions, used to keep sessions tool-set specific. */ diff --git a/test/sessions.test.ts b/test/sessions.test.ts index 92847de..a112a2c 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -116,6 +117,29 @@ describe("SessionStore", () => { expect(fourth.sessionId).toBe("ses_b"); }); + it("counts every reuse of a session on the record", () => { + const sessions = store(); + const first = sessions.acquire({ ...BASE_INPUT, key: "conversation-1", messages: [USER_1] }); + sessions.commit(first.key, "ses_1", { ...BASE_INPUT, messages: [USER_1] }); + // The record was created by the first turn: it has not been reused yet. + expect(sessions.list()[0]?.reusedCount).toBe(0); + + const turnTwo: InternalMessage[] = [USER_1, ASSISTANT_1, USER_2]; + const second = sessions.acquire({ ...BASE_INPUT, key: "conversation-1", messages: turnTwo }); + expect(second.reused).toBe(true); + sessions.commit(second.key, "ses_1", { ...BASE_INPUT, messages: turnTwo }); + expect(sessions.list()[0]?.reusedCount).toBe(1); + + const turnThree: InternalMessage[] = [...turnTwo, ASSISTANT_2, { role: "user", text: "And 3+3?" }]; + const third = sessions.acquire({ ...BASE_INPUT, key: "conversation-1", messages: turnThree }); + expect(third.reused).toBe(true); + sessions.commit(third.key, "ses_1", { ...BASE_INPUT, messages: turnThree }); + + // `/admin/sessions` reports this; the old code always answered 0. + expect(sessions.list()).toHaveLength(1); + expect(sessions.list()[0]?.reusedCount).toBe(2); + }); + it("does not reuse a session for another model or agent", () => { const sessions = store(); const first = sessions.acquire({ ...BASE_INPUT, messages: [USER_1] }); @@ -474,4 +498,92 @@ describe("hashing helpers", () => { expect(hashTools([])).toBe("none"); expect(hashTools([a])).not.toBe(hashTools([b])); }); +}); + +describe("message serialisation", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("serialises each message object at most once across one acquire() and commit() pair", () => { + const sessions = store(); + const shared: InternalMessage = { role: "user", text: "Hello" }; + const branch: InternalMessage = { role: "user", text: "What is 2+2?" }; + const assistant: InternalMessage = { role: "assistant", text: "4" }; + // The base64 payload stands in for an attachment: serialising it three times + // per turn was the cost this avoids. + const media: InternalMessage = { + role: "user", + text: "look", + attachments: [{ data: "A".repeat(200_000), mime: "image/png", kind: "image" }], + }; + + const first = sessions.acquire({ ...BASE_INPUT, messages: [shared, media] }); + sessions.commit(first.key, "ses_1", { ...BASE_INPUT, messages: [shared, media] }); + + // Turn two resends the root turn and adds one user turn. `acquire()` hashes + // the delivered prefix and `commit()` hashes the whole conversation; before + // the fix each hashed `JSON.stringify(messages)` from scratch. + const json = vi.spyOn(JSON, "stringify"); + const second = sessions.acquire({ ...BASE_INPUT, messages: [shared, media, assistant, branch] }); + expect(second.reused).toBe(true); + sessions.commit(second.key, "ses_1", { ...BASE_INPUT, messages: [shared, media, assistant, branch] }); + const observed = json.mock.calls.map((call) => call[0]); + json.mockRestore(); + + const isMessage = (value: unknown): value is InternalMessage => + typeof value === "object" && value !== null && !Array.isArray(value) && "role" in value; + + // `shared` and `media` were already serialised while turn one was committed, + // so the fixed code serialises only the two new messages of this turn, even + // though both hashes traverse the whole conversation. + const messages = observed.filter(isMessage); + expect(messages).toHaveLength(2); + expect(new Set(messages).size).toBe(messages.length); + expect(messages).toContain(branch); + expect(messages).toContain(assistant); + expect(messages).not.toContain(shared); + expect(messages).not.toContain(media); + + // The array form is assembled from the memoised parts instead of being + // stringified as a whole, so the second turn costs no array serialisation. + const arrays = observed.filter((value) => Array.isArray(value)); + expect(arrays).toHaveLength(0); + }); + + it("hashes byte-identically to the un-memoised JSON serialisation", () => { + const messages: InternalMessage[] = [ + { role: "user", text: "Hello", attachments: [{ data: "QUJD", mime: "image/png", kind: "image" }] }, + { role: "assistant", text: "Hi", toolCalls: [{ id: "call_1", name: "lookup", arguments: "{}" }] }, + ]; + const beforeFix = createHash("sha256").update(JSON.stringify(messages)).digest("hex"); + + expect(hashMessages(messages)).toBe(beforeFix); + // `deriveKey()` folds the root message into its own payload; the memoised + // serialisation must not change the key it derives. + const rootInput = { + model: "opencode/big-pickle", + agent: "build", + toolsHash: "none", + permissionProfile: "default", + messages, + }; + const rootKey = createHash("sha256") + .update( + JSON.stringify({ + model: rootInput.model, + agent: rootInput.agent, + variant: null, + tools: rootInput.toolsHash, + permissions: rootInput.permissionProfile, + root: messages[0], + }), + ) + .digest("hex") + .slice(0, 32); + expect(deriveKey(rootInput)).toBe(rootKey); + expect(hashMessages([messages[0] as InternalMessage])).toBe( + createHash("sha256").update(JSON.stringify([messages[0]])).digest("hex"), + ); + }); }); \ No newline at end of file From 92fadea66ad211aa79e68fe93be16a853e589b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:32:59 +0700 Subject: [PATCH 07/10] fix(streaming): adopt consolidated text and stable indexes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A provider that delivers its answer only in `session.text.ended` produced an empty 200 SSE response on `/v1/chat/completions`, `/v1/completions` and `/v1/messages`, while the buffered route for the same request carried the answer. Those three streamed paths now adopt a consolidated `text_end` / `reasoning_end` only when it is longer than what the deltas already produced, which is the documented rule `/v1/responses` and `collectCompletion()` already applied. `/v1/responses` now fixes an item's `output_index` when the item is announced and reuses it everywhere, so a text-then-reasoning turn no longer announces two items at index 0 or ends with an `output[]` that contradicts the stream. A step-level `reasoning_end` snapshot is adopted only when longer, and the reasoning summary is closed once per turn instead of once per step. The Anthropic stream kept the `stop_sequences` filter between it and the tool calls, so a matched sequence swallowed a call the buffered route returns; every call is reported again. Its stop-sequence filter was O(n²) in the length of the retained tail (64 KiB took about 5 s and blocked the event loop); it now uses the O(1) hold rule the chat adapter uses. The tool-envelope fence parsing is linear for the same reason. --- src/adapter/anthropic/messages.ts | 147 +++++++++++------- src/adapter/common/tools.ts | 54 ++++++- src/adapter/openai/chat.ts | 25 ++++ src/adapter/openai/completions.ts | 19 +++ src/adapter/openai/responses.ts | 169 +++++++++++++-------- test/anthropic.test.ts | 241 ++++++++++++++++++++++++++++++ test/openai-responses.test.ts | 124 ++++++++++++++- test/parity.test.ts | 117 +++++++++++++++ test/tools.test.ts | 33 ++++ 9 files changed, 805 insertions(+), 124 deletions(-) diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 44f0ee8..2135733 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -770,19 +770,28 @@ function stopReasonFor( * * Text deltas arrive in arbitrary chunks, so a sequence can straddle a delta * boundary ("hello E" + "ND world"). The filter emits everything that cannot be - * part of a sequence and withholds the longest suffix that is still a proper - * prefix of one; when a sequence completes it records the match and suppresses - * every later delta. `flush()` releases a withheld suffix that never completed, - * so text is never lost. Only assistant text is filtered: reasoning and tool - * arguments are never truncated. + * part of a sequence and holds back the longest sequence minus one character — + * the only suffix that can still become a match. When a sequence completes it + * records the match and suppresses every later delta. `flush()` releases a + * withheld suffix that never completed, so text is never lost. Only assistant + * text is filtered: reasoning and tool arguments are never truncated. + * + * The hold rule is the O(1) one `StopSequenceFilter` in + * `src/adapter/openai/chat.ts` already uses. The previous version walked every + * suffix length of `#pending` and sliced at each step, so a 64 KiB tail that + * shares a long prefix with a sequence cost ~5 s of blocked event loop (P-24). */ class StopSequenceFilter { readonly #sequences: readonly string[]; + readonly #hold: number; #pending = ""; #matched: string | undefined; constructor(sequences: readonly string[]) { this.#sequences = sequences.filter((sequence) => sequence.length > 0); + // A sequence can only be completed by a suffix that starts within the last + // `longest - 1` characters, so everything before that is safe to emit. + this.#hold = Math.max(0, this.#sequences.reduce((longest, entry) => Math.max(longest, entry.length), 0) - 1); } /** The sequence that ended the turn, once one has matched. */ @@ -803,14 +812,9 @@ class StopSequenceFilter { return safe; } - const held = this.#heldSuffixLength(); - if (held === 0) { - const safe = this.#pending; - this.#pending = ""; - return safe; - } - const safe = this.#pending.slice(0, this.#pending.length - held); - this.#pending = this.#pending.slice(this.#pending.length - held); + if (this.#pending.length <= this.#hold) return ""; + const safe = this.#pending.slice(0, this.#pending.length - this.#hold); + this.#pending = this.#pending.slice(this.#pending.length - this.#hold); return safe; } @@ -837,21 +841,6 @@ class StopSequenceFilter { } return best; } - - /** Length of the longest suffix that is a proper prefix of some sequence. */ - #heldSuffixLength(): number { - if (this.#sequences.length === 0) return 0; - let longest = 0; - for (const sequence of this.#sequences) longest = Math.max(longest, sequence.length); - const limit = Math.min(this.#pending.length, longest - 1); - for (let length = limit; length > 0; length -= 1) { - const suffix = this.#pending.slice(this.#pending.length - length); - if (this.#sequences.some((sequence) => sequence.length > length && sequence.startsWith(suffix))) { - return length; - } - } - return 0; - } } /** @@ -984,6 +973,7 @@ async function streamAnthropicMessage( const id = newMessageId(); let model = request.model; let assistantMessageId = ""; + /** Next content-block index; blocks are announced in arrival order. */ let index = 0; let openIndex = -1; let openKind: "thinking" | "text" | null = null; @@ -992,6 +982,13 @@ async function streamAnthropicMessage( let usage: Usage = { ...EMPTY_USAGE }; const calls: ToolCall[] = []; const stopFilter = new StopSequenceFilter(request.stop ?? []); + // The streamed twins of `CollectedCompletion.text` / `.reasoning`: the + // amount of each that has been adopted so far. A consolidated + // `text_end` / `reasoning_end` is adopted only when it is longer than what + // the deltas already produced (`docs/ARCHITECTURE.md` §4.3), and only the + // suffix the stream has not seen yet is emitted. + let textLength = 0; + let reasoningLength = 0; const send = (payload: string | object, event: string): void => { if (!opened) { @@ -1001,20 +998,6 @@ async function streamAnthropicMessage( writer.send(payload, event); }; - const openThinking = (): void => { - openIndex = index; - index += 1; - openKind = "thinking"; - send({ type: "content_block_start", index: openIndex, content_block: { type: "thinking", thinking: "", signature: "" } }, "content_block_start"); - }; - - const openText = (): void => { - openIndex = index; - index += 1; - openKind = "text"; - send({ type: "content_block_start", index: openIndex, content_block: { type: "text", text: "" } }, "content_block_start"); - }; - const closeOpen = (): void => { if (openKind === null) return; if (openKind === "thinking") { @@ -1036,9 +1019,13 @@ async function streamAnthropicMessage( }; /** - * Emit assistant text, opening the text block lazily. Text withheld by the - * stop-sequence filter never opens a block, so a truncated turn cannot emit - * an empty one. + * Emit assistant text, opening the text block lazily. + * + * The block takes the next free index at the moment it is announced, which is + * what the buffered route renders (`thinking`, then `text`, then `tool_use`): + * upstream emits its thinking before the answer, so the announced order and + * the buffered order agree. Text is never withheld to force that order — a + * text-only turn would stop streaming and answer in one burst. */ const sendText = (text: string): void => { if (text.length === 0) return; @@ -1052,6 +1039,46 @@ async function streamAnthropicMessage( ); }; + const openThinking = (): void => { + openIndex = index; + index += 1; + openKind = "thinking"; + send( + { type: "content_block_start", index: openIndex, content_block: { type: "thinking", thinking: "", signature: "" } }, + "content_block_start", + ); + }; + + const openText = (): void => { + openIndex = index; + index += 1; + openKind = "text"; + send({ type: "content_block_start", index: openIndex, content_block: { type: "text", text: "" } }, "content_block_start"); + }; + + /** + * Announce the thinking block. It takes the next free index — index 0 when it + * is the first block of the turn. + */ + const openReasoning = (): void => { + if (openKind === "thinking") return; + closeOpen(); + openThinking(); + }; + + const sendReasoning = (text: string): void => { + if (text.length === 0) return; + reasoningLength += text.length; + if (!reasoningEnabled) return; + if (openKind !== "thinking") { + openReasoning(); + } + send( + { type: "content_block_delta", index: openIndex, delta: { type: "thinking_delta", thinking: text } }, + "content_block_delta", + ); + }; + const stream = ctx.completion.run(request, completionDeps(ctx), { signal: runSignal }); try { @@ -1083,15 +1110,7 @@ async function streamAnthropicMessage( break; } case "reasoning_delta": { - if (!reasoningEnabled) break; - if (openKind !== "thinking") { - closeOpen(); - openThinking(); - } - send( - { type: "content_block_delta", index: openIndex, delta: { type: "thinking_delta", thinking: event.text } }, - "content_block_delta", - ); + sendReasoning(event.text); break; } case "reasoning_end": { @@ -1102,11 +1121,18 @@ async function streamAnthropicMessage( if (event.messageId !== undefined && event.messageId.length > 0) { assistantMessageId = event.messageId; } + // The provider may deliver the consolidated summary instead of (or + // in addition to) deltas; adopt it only when it is longer, exactly + // like `collectCompletion()` and the buffered route. + if (event.text.length <= reasoningLength) break; + const delta = event.text.slice(reasoningLength); + sendReasoning(delta); break; } case "text_delta": { // Only assistant text is subject to `stop_sequences`; the filter // withholds a suffix that may still grow into a sequence. + textLength += event.text.length; sendText(stopFilter.push(event.text)); break; } @@ -1118,12 +1144,19 @@ async function streamAnthropicMessage( if (event.messageId !== undefined && event.messageId.length > 0) { assistantMessageId = event.messageId; } + // A consolidated `text_end` is adopted only when it is longer than + // what the deltas produced; only its unseen suffix is streamed. + if (event.text.length <= textLength) break; + const delta = event.text.slice(textLength); + textLength = event.text.length; + sendText(stopFilter.push(delta)); break; } case "tool_calls": { - // A stop sequence ended the visible answer, so no further tool block - // is emitted; calls collected before the match still are. - if (stopFilter.matched === undefined) calls.push(...event.calls); + // Every collected call is reported, exactly like the buffered route: + // the stop sequence truncates the visible text only, so it must not + // swallow a tool request the buffered body still carries (P-23). + calls.push(...event.calls); break; } case "usage": { diff --git a/src/adapter/common/tools.ts b/src/adapter/common/tools.ts index 62cac3e..27e3901 100644 --- a/src/adapter/common/tools.ts +++ b/src/adapter/common/tools.ts @@ -275,12 +275,58 @@ export function parseAssistantText(text: string): ParsedAssistantText { return { text: forwarded + tail.text, calls: tail.calls }; } +/** Length of the ``` fence marker. */ +const FENCE = "```"; + +/** Whitespace the old fence regexes' `\s*` matched around a fence. */ +function isFenceSpace(char: string): boolean { + return char === " " || char === "\t" || char === "\r" || char === "\n" || char === "\f" || char === "\v"; +} + +/** `[a-zA-Z0-9]*`, the optional language tag the old fence regexes allowed. */ +function isFenceLabel(char: string): boolean { + return (char >= "a" && char <= "z") || (char >= "A" && char <= "Z") || (char >= "0" && char <= "9"); +} + +/** + * Strip one optional leading code fence, linear in the length of `text`. + * + * The previous `^\s*```[a-zA-Z0-9]*\s*` regex re-tried the leading `\s*` at + * every offset, so a long whitespace run cost O(n²). This walk visits every + * character at most once: `trimStart()` removes the leading whitespace, and the + * optional language tag plus its trailing whitespace are consumed by one forward + * scan. + */ +function stripOpeningFence(text: string): string { + const trimmed = text.trimStart(); + if (!trimmed.startsWith(FENCE)) return trimmed; + let index = FENCE.length; + while (index < trimmed.length && isFenceLabel(trimmed.charAt(index))) index += 1; + while (index < trimmed.length && isFenceSpace(trimmed.charAt(index))) index += 1; + return trimmed.slice(index); +} + +/** + * Strip one optional trailing code fence, linear in the length of `text`. + * + * The previous `\s*```\s*$` regex re-tried the leading `\s*` at every offset: a + * body that is a long whitespace run (model output carried across the steps of + * a turn) cost about a second at 64 KiB. Here the trailing whitespace is + * consumed backwards from a single starting point instead. + */ +function stripTrailingFence(text: string): string { + let end = text.length; + while (end > 0 && isFenceSpace(text.charAt(end - 1))) end -= 1; + const withoutTrailingSpace = text.slice(0, end); + if (!withoutTrailingSpace.endsWith(FENCE)) return withoutTrailingSpace; + let after = withoutTrailingSpace.length - FENCE.length; + while (after > 0 && isFenceSpace(withoutTrailingSpace.charAt(after - 1))) after -= 1; + return withoutTrailingSpace.slice(0, after); +} + /** Parse the JSON payload found between the envelope markers. */ export function parseToolCallBody(body: string): ToolCall[] { - const cleaned = body - .replace(/^\s*```[a-zA-Z0-9]*\s*/, "") - .replace(/\s*```\s*$/, "") - .trim(); + const cleaned = stripTrailingFence(stripOpeningFence(body)).trim(); if (cleaned === "") return []; const results: ToolCall[] = []; diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index 45de22e..ecf7eba 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -936,6 +936,10 @@ async function streamChat( let failure: ApiError | undefined; let usage: Usage = { ...EMPTY_USAGE }; let toolIndex = 0; + // Length of the visible text that was produced so far, deltas and consolidated + // end events together. It is the streamed twin of `CollectedCompletion.text` + // and gates the documented "adopt only when longer" rule below. + let textLength = 0; // Headers are sent lazily so that a failure before the first event is still // reported with a proper HTTP status instead of a 200 SSE body. @@ -962,6 +966,27 @@ async function streamChat( case "text_delta": { const text = stopFilter.push(event.text); + textLength += event.text.length; + if (text.length === 0) break; + ensure().send({ + ...base, + choices: [{ index: 0, delta: { content: text }, finish_reason: null }], + }); + break; + } + + case "text_end": { + // A provider may deliver the consolidated text instead of (or in + // addition to) deltas; the buffered route and `/v1/responses` adopt it + // only when it is longer than what the deltas produced, and the + // streamed surfaces apply the same rule independently + // (`docs/ARCHITECTURE.md` §4.3). Only the suffix that the stream has + // not seen yet is emitted, so a step-level snapshot can neither + // truncate the answer nor duplicate it. + if (event.text.length <= textLength) break; + const delta = event.text.slice(textLength); + textLength = event.text.length; + const text = stopFilter.push(delta); if (text.length === 0) break; ensure().send({ ...base, diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index ef0c7d4..2ce5a2f 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -241,6 +241,10 @@ async function streamCompletion( let finishReason: FinishReason = "stop"; let failure: ApiError | undefined; let usage: Usage = { ...EMPTY_USAGE }; + // Length of the visible text produced so far. It gates the "adopt a + // consolidated `text_end` only when it is longer" rule below, exactly like + // `collectCompletion()` and the other streamed surfaces. + let textLength = 0; // Headers are sent lazily so that a failure before the first event is still // reported with a proper HTTP status instead of a 200 SSE body. @@ -268,6 +272,21 @@ async function streamCompletion( case "text_delta": { const text = stopFilter.push(event.text); + textLength += event.text.length; + if (text.length > 0) ensure().send(chunk(text, null)); + break; + } + + case "text_end": { + // The provider delivered the consolidated text instead of (or in + // addition to) deltas. Adopt it only when it is longer than what the + // deltas accumulated — the documented rule the buffered route and + // `/v1/responses` already apply — and emit only the suffix the stream + // has not produced yet. + if (event.text.length <= textLength) break; + const delta = event.text.slice(textLength); + textLength = event.text.length; + const text = stopFilter.push(delta); if (text.length > 0) ensure().send(chunk(text, null)); break; } diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index c9f306e..9aa561b 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -992,6 +992,18 @@ interface StreamState { reasoningId: string; reasoningStarted: boolean; reasoningVisible: boolean; + /** + * `output_index` recorded when the reasoning item was first announced. + * + * The index is a property of the announcement: recomputing it from the + * current state (for example "reasoning is always 0") makes a + * text-then-reasoning turn announce two items at index 0, emit the later + * frames under the wrong index and close the stream with an `output[]` that + * contradicts the frames the client already received. + */ + reasoningIndex: number | undefined; + /** True once the summary part has been closed, so it is closed exactly once. */ + reasoningClosed: boolean; /** * Reasoning text accumulated as fragments and joined once when it is reported. * Appending to one string on every delta made a long turn quadratic. @@ -1000,6 +1012,8 @@ interface StreamState { reasoningLength: number; messageId: string; messageStarted: boolean; + /** `output_index` recorded when the message item was first announced. */ + messageIndex: number | undefined; /** Visible text fragments; joined once in `finaliseStream` / failure paths. */ textParts: string[]; textLength: number; @@ -1048,10 +1062,13 @@ async function streamResponse( reasoningId: newId("rs"), reasoningStarted: false, reasoningVisible: false, + reasoningIndex: undefined, + reasoningClosed: false, reasoningParts: [], reasoningLength: 0, messageId: newId("msg"), messageStarted: false, + messageIndex: undefined, textParts: [], textLength: 0, calls: [], @@ -1125,13 +1142,20 @@ function failedStreamResponse( state: StreamState, error: { code: string; message: string }, ): ResponseBody { - const output: ResponseOutputItem[] = []; - if (state.reasoningVisible && state.reasoningLength > 0) { - output.push(reasoningItem(state.reasoningId, streamReasoning(state), "completed")); + // Same ordering rule as `finaliseStream`: the recorded announcement index, + // not the order this function happens to rebuild the items in. + const announced: Array<{ index: number; item: ResponseOutputItem }> = []; + if (state.reasoningVisible && state.reasoningLength > 0 && state.reasoningIndex !== undefined) { + announced.push({ + index: state.reasoningIndex, + item: reasoningItem(state.reasoningId, streamReasoning(state), "completed"), + }); } - if (state.messageStarted || state.textLength > 0) { - output.push(messageItem(state.messageId, streamText(state), "completed")); + if ((state.messageStarted || state.textLength > 0) && state.messageIndex !== undefined) { + announced.push({ index: state.messageIndex, item: messageItem(state.messageId, streamText(state), "completed") }); } + announced.sort((left, right) => left.index - right.index); + const output: ResponseOutputItem[] = announced.map((entry) => entry.item); for (const call of state.calls) output.push(functionCallItem(call, "completed")); return baseResponse(prepared, { @@ -1226,20 +1250,25 @@ async function pipeEvents( state.reasoningVisible = true; if (!state.reasoningStarted) { state.reasoningStarted = true; - // Every output item is announced before its content, index 0 is the - // reasoning item: without this frame a client building `output[]` - // from the stream sees a `.done` for an index it never saw opened. + // The index is fixed here and reused by every later frame and by the + // terminal `output[]`; recomputing it would collide with the index of + // an item that was opened first. + const index = state.messageIndex === undefined ? 0 : state.messageIndex + 1; + state.reasoningIndex = index; + // Every output item is announced before its content: without this + // frame a client building `output[]` from the stream sees a `.done` + // for an index it never saw opened. emitFrame(writer, state, "response.output_item.added", (sequence) => ({ type: "response.output_item.added", sequence_number: sequence, - output_index: reasoningOutputIndex(), + output_index: index, item: reasoningItem(state.reasoningId, "", "in_progress"), })); emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ type: "response.reasoning_summary_part.added", sequence_number: sequence, item_id: state.reasoningId, - output_index: reasoningOutputIndex(), + output_index: index, summary_index: 0, part: { type: "summary_text", text: "" }, })); @@ -1250,7 +1279,7 @@ async function pipeEvents( type: "response.reasoning_summary_text.delta", sequence_number: sequence, item_id: state.reasoningId, - output_index: reasoningOutputIndex(), + output_index: state.reasoningIndex ?? 0, summary_index: 0, delta: event.text, })); @@ -1258,7 +1287,12 @@ async function pipeEvents( } case "reasoning_end": { - if (event.text.length > 0) { + // Adopt the consolidated summary only when it is longer than what the + // deltas already produced, mirroring `text_end` and + // `collectCompletion()`. Upstream emits one `reasoning.ended` per step + // carrying that step's snapshot, so adopting unconditionally truncated + // the streamed reasoning to the last (shorter) step. + if (event.text.length > state.reasoningLength) { state.reasoningParts = [event.text]; state.reasoningLength = event.text.length; } @@ -1268,56 +1302,48 @@ async function pipeEvents( if (state.reasoningLength === 0) break; state.reasoningStarted = true; state.reasoningVisible = true; + const index = state.messageIndex === undefined ? 0 : state.messageIndex + 1; + state.reasoningIndex = index; emitFrame(writer, state, "response.output_item.added", (sequence) => ({ type: "response.output_item.added", sequence_number: sequence, - output_index: reasoningOutputIndex(), + output_index: index, item: reasoningItem(state.reasoningId, "", "in_progress"), })); emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ type: "response.reasoning_summary_part.added", sequence_number: sequence, item_id: state.reasoningId, - output_index: reasoningOutputIndex(), + output_index: index, summary_index: 0, part: { type: "summary_text", text: "" }, })); } - if (!state.reasoningVisible) break; - const reasoningText = streamReasoning(state); - emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ - type: "response.reasoning_summary_text.done", - sequence_number: sequence, - item_id: state.reasoningId, - output_index: reasoningOutputIndex(), - summary_index: 0, - text: reasoningText, - })); - emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ - type: "response.reasoning_summary_part.done", - sequence_number: sequence, - item_id: state.reasoningId, - output_index: reasoningOutputIndex(), - summary_index: 0, - part: { type: "summary_text", text: reasoningText }, - })); + // The summary is closed once, by `finaliseStream`, when the turn is + // over: closing it here would emit one `.done` per step for the same + // `summary_index` and report the text accumulated so far, not the final + // reasoning of the turn. break; } case "text_delta": { if (!state.messageStarted) { state.messageStarted = true; + // The index is fixed at the announcement and reused everywhere, so a + // reasoning item that arrives afterwards cannot steal index 0. + const index = state.reasoningIndex === undefined ? 0 : state.reasoningIndex + 1; + state.messageIndex = index; emitFrame(writer, state, "response.output_item.added", (sequence) => ({ type: "response.output_item.added", sequence_number: sequence, - output_index: messageOutputIndex(state), + output_index: index, item: messageItem(state.messageId, "", "in_progress"), })); emitFrame(writer, state, "response.content_part.added", (sequence) => ({ type: "response.content_part.added", sequence_number: sequence, item_id: state.messageId, - output_index: messageOutputIndex(state), + output_index: index, content_index: 0, part: { type: "output_text", text: "", annotations: [] }, })); @@ -1328,7 +1354,7 @@ async function pipeEvents( type: "response.output_text.delta", sequence_number: sequence, item_id: state.messageId, - output_index: messageOutputIndex(state), + output_index: state.messageIndex ?? 0, content_index: 0, delta: event.text, })); @@ -1342,17 +1368,19 @@ async function pipeEvents( // final payload would carry `output_text` with an empty `output`. if (!state.messageStarted) { state.messageStarted = true; + const index = state.reasoningIndex === undefined ? 0 : state.reasoningIndex + 1; + state.messageIndex = index; emitFrame(writer, state, "response.output_item.added", (sequence) => ({ type: "response.output_item.added", sequence_number: sequence, - output_index: messageOutputIndex(state), + output_index: index, item: messageItem(state.messageId, "", "in_progress"), })); emitFrame(writer, state, "response.content_part.added", (sequence) => ({ type: "response.content_part.added", sequence_number: sequence, item_id: state.messageId, - output_index: messageOutputIndex(state), + output_index: index, content_index: 0, part: { type: "output_text", text: "", annotations: [] }, })); @@ -1401,11 +1429,10 @@ async function pipeEvents( /** Emit the closing frames plus `response.completed` / `response.incomplete` / `response.failed`. */ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamState): void { - let outputIndex = 0; // Items already announced through `response.output_item.done`; the closing - // `response.completed` payload must reuse these exact ids and shapes, not - // regenerate them, or clients cannot correlate the stream with the result. - const doneItems: ResponseOutputItem[] = []; + // `response.completed` payload must reuse these exact ids, shapes and indexes, + // not regenerate them, or clients cannot correlate the stream with the result. + const items: Array<{ index: number; item: ResponseOutputItem }> = []; const incompleteReasonForTurn = incompleteReason(state.finishReason); const failed = state.finishReason === "error"; @@ -1413,19 +1440,43 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat // An incomplete response has an incomplete message item, matching the real API. const messageStatus: MessageItem["status"] = incomplete ? "incomplete" : "completed"; - if (state.reasoningVisible) { - const item = reasoningItem(state.reasoningId, streamReasoning(state), "completed"); + if (state.reasoningVisible && state.reasoningIndex !== undefined) { + const outputIndex = state.reasoningIndex; + const reasoningText = streamReasoning(state); + // The summary is closed here rather than on every `reasoning_end`: upstream + // emits one end event per step, and closing per step emitted several `.done` + // frames for the same `summary_index`, each with a partial snapshot. + if (!state.reasoningClosed) { + state.reasoningClosed = true; + emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ + type: "response.reasoning_summary_text.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: outputIndex, + summary_index: 0, + text: reasoningText, + })); + emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ + type: "response.reasoning_summary_part.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: outputIndex, + summary_index: 0, + part: { type: "summary_text", text: reasoningText }, + })); + } + const item = reasoningItem(state.reasoningId, reasoningText, "completed"); emitFrame(writer, state, "response.output_item.done", (sequence) => ({ type: "response.output_item.done", sequence_number: sequence, output_index: outputIndex, item, })); - doneItems.push(item); - outputIndex += 1; + items.push({ index: outputIndex, item }); } - if (state.messageStarted) { + if (state.messageStarted && state.messageIndex !== undefined) { + const outputIndex = state.messageIndex; const text = streamText(state); emitFrame(writer, state, "response.output_text.done", (sequence) => ({ type: "response.output_text.done", @@ -1450,11 +1501,15 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat output_index: outputIndex, item, })); - doneItems.push(item); - outputIndex += 1; + items.push({ index: outputIndex, item }); } + // Function calls are the only items still opened at finalisation time, so they + // continue the announcement order after whatever was emitted before. + let nextIndex = items.reduce((highest, entry) => Math.max(highest, entry.index + 1), 0); for (const call of state.calls) { + const outputIndex = nextIndex; + nextIndex += 1; const item = functionCallItem(call, "in_progress"); emitFrame(writer, state, "response.output_item.added", (sequence) => ({ type: "response.output_item.added", @@ -1483,11 +1538,13 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat output_index: outputIndex, item: completedItem, })); - doneItems.push(completedItem); - outputIndex += 1; + items.push({ index: outputIndex, item: completedItem }); } - const output: ResponseOutputItem[] = doneItems; + // The terminal `output[]` follows the indexes the stream announced, not the + // order this function happens to close the items in. + items.sort((left, right) => left.index - right.index); + const output: ResponseOutputItem[] = items.map((entry) => entry.item); const final = baseResponse(prepared, { id: state.id, createdAt: state.createdAt, @@ -1513,13 +1570,3 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat const type = failed ? "response.failed" : incomplete ? "response.incomplete" : "response.completed"; emitFrame(writer, state, type, (sequence) => ({ type, sequence_number: sequence, response: final })); } - -/** Reasoning always occupies output index 0 when it is visible. */ -function reasoningOutputIndex(): number { - return 0; -} - -/** The message follows the reasoning item when one was emitted. */ -function messageOutputIndex(state: StreamState): number { - return state.reasoningVisible ? 1 : 0; -} diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index 411e60f..bda538a 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -1339,6 +1339,247 @@ describe("disable_parallel_tool_use (A9)", () => { }); }); +// -------------------------------------------------- streamed content blocks --- + +/** Canonical view of one streamed content block, keyed by its announced index. */ +interface StreamedBlock { + type: string; + content: unknown; +} + +/** + * Rebuild the `content[]` a streaming client assembles from the SSE frames: + * block starts announce each index, deltas fill it, `content_block_stop` closes + * it. Tool input is normalised the same way `renderAnthropicMessage()` does, so + * it can be compared with the buffered payload verbatim. + */ +function streamedContentBlocks(frames: StreamFrame[]): Map { + const blocks = new Map(); + const partialJson = new Map(); + for (const frame of frames) { + switch (frame.type) { + case "content_block_start": { + expect(frame.index, "every content_block_start must carry an index").toBeTypeOf("number"); + const block = frame.content_block ?? {}; + const view: StreamedBlock = { type: block.type ?? "", content: {} }; + if (block.type === "thinking") view.content = ""; + else if (block.type === "text") view.content = ""; + else if (block.type === "tool_use") { + view.content = {}; + partialJson.set(frame.index ?? 0, ""); + } + blocks.set(frame.index ?? 0, view); + break; + } + case "content_block_delta": { + const index = frame.index ?? 0; + const view = blocks.get(index); + expect(view, `content_block_delta for index ${index} must follow its content_block_start`).toBeDefined(); + if (view === undefined) break; + if (frame.delta?.type === "text_delta") view.content = `${String(view.content)}${frame.delta.text ?? ""}`; + else if (frame.delta?.type === "thinking_delta") { + view.content = `${String(view.content)}${frame.delta.thinking ?? ""}`; + } else if (frame.delta?.type === "input_json_delta" && view.type === "tool_use") { + partialJson.set(index, `${partialJson.get(index) ?? ""}${frame.delta.partial_json ?? ""}`); + } + break; + } + case "content_block_stop": { + const index = frame.index ?? 0; + const view = blocks.get(index); + if (view?.type === "tool_use") { + view.content = JSON.parse(partialJson.get(index) ?? "{}") as unknown; + } + break; + } + default: + break; + } + } + return blocks; +} + +function anthropicResponse(response: { body: string }): AnthropicResponseBody { + return JSON.parse(response.body) as AnthropicResponseBody; +} + +/** One content block in the same shape for a buffered body and a stream. */ +interface ContentBlockView { + type: string; + content: unknown; +} + +function bufferedBlockViews(body: AnthropicResponseBody): ContentBlockView[] { + return body.content.map((block) => ({ + type: String(block["type"]), + content: + block["type"] === "thinking" + ? block["thinking"] + : block["type"] === "text" + ? block["text"] + : block["input"], + })); +} + +function streamedBlockViews(blocks: Map): ContentBlockView[] { + return [...blocks.entries()] + .sort(([left], [right]) => left - right) + .map(([, block]) => ({ type: block.type, content: block.content })); +} + +describe("streamed content blocks (P-22, P-23)", () => { + it("keeps thinking before text when the provider emits its reasoning first", async () => { + // Upstream emits the thinking deltas before the answer. Both paths must + // announce the same blocks in the same order: `thinking` at index 0, `text` + // at index 1 (P-22). The indexes are fixed when a block is announced and + // never recomputed when a later block opens. + const events: CompletionEvent[] = [ + { ...START, reasoningEnabled: true }, + { kind: "reasoning_delta", text: "Let me think.", ordinal: 0 }, + { kind: "reasoning_end", text: "Let me think.", ordinal: 0 }, + { kind: "text_delta", text: "Answer ", ordinal: 0 }, + { kind: "text_delta", text: "first.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: usage(4, 6), messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "think first" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const frames = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const blocks = streamedContentBlocks(frames); + const views = streamedBlockViews(blocks); + // Announced indexes are contiguous from 0 and never reused. + expect([...blocks.keys()].sort((left, right) => left - right)).toEqual([0, 1]); + expect(views.map((view) => view.type)).toEqual(["thinking", "text"]); + + const bufferedBody = anthropicResponse(buffered); + expect(views).toEqual(bufferedBlockViews(bufferedBody)); + }); + + it("streams text as it arrives instead of withholding it for block order", async () => { + // A text-only turn on a thinking-enabled request used to hold the text back + // until the turn ended (to know whether a `thinking` block would still + // arrive), which turned a streamed answer into one burst. Each delta must + // reach the client as its own frame. + const events: CompletionEvent[] = [ + { ...START, reasoningEnabled: true }, + { kind: "text_delta", text: "Answer ", ordinal: 0 }, + { kind: "text_delta", text: "first.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: usage(4, 6), messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => events }); + const streamed = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + stream: true, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "answer" }], + }); + expect(streamed.statusCode).toBe(200); + + const frames = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const textDeltas = frames.filter( + (frame) => frame.type === "content_block_delta" && frame.delta?.type === "text_delta", + ); + expect(textDeltas.map((frame) => frame.delta?.text)).toEqual(["Answer ", "first."]); + }); + + it("reports every tool call the buffered route carries after a stop-sequence match", async () => { + // The stop sequence truncates the visible *text* only: the buffered body + // still returns the tool call the model requested after it, so the stream + // must announce it too (P-23). + const events: CompletionEvent[] = [ + START, + { kind: "text_delta", text: "hello END world", ordinal: 0 }, + { kind: "tool_calls", calls: [{ id: "toolu_after_stop", name: "lookup", arguments: '{"q":"after"}' }] }, + { kind: "usage", usage: usage(3, 6) }, + { kind: "end", finishReason: "tool_calls", usage: usage(3, 6), messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + stop_sequences: ["END"], + messages: [{ role: "user", content: "look it up" }], + tools: [{ name: "lookup", input_schema: { type: "object" } }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const bufferedBody = anthropicResponse(buffered); + const bufferedViews = bufferedBlockViews(bufferedBody); + expect(bufferedViews).toEqual([ + { type: "text", content: "hello " }, + { type: "tool_use", content: { q: "after" } }, + ]); + + const frames = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const blocks = streamedContentBlocks(frames); + // Announced indexes are contiguous from 0 and the block list matches the + // buffered `content[]` exactly. + expect([...blocks.keys()].sort((left, right) => left - right)).toEqual([0, 1]); + expect(streamedBlockViews(blocks)).toEqual(bufferedViews); + + const messageDelta = frames.find((frame) => frame.type === "message_delta"); + expect(messageDelta?.delta?.stop_reason).toBe("stop_sequence"); + expect(messageDelta?.delta?.stop_sequence).toBe("END"); + }); +}); + +describe("stop-sequence scan cost (P-24)", () => { + it("streams a 64 KiB near-match in bounded time, with linear scanned work", async () => { + // `#heldSuffixLength()` walked every suffix length of the pending text and + // sliced at each step, so a tail that shared a long prefix with a stop + // sequence cost O(n^2): 64 KiB took ~5 s of blocked event loop. The hold + // rule is now O(1) per delta (the same one `StopSequenceFilter` in + // `src/adapter/openai/chat.ts` uses), so the scan must stay linear. + const sequence = "a".repeat(64 * 1024); + const nearMatch = `${"a".repeat(64 * 1024 - 1)}b`; + const events: CompletionEvent[] = [ + START, + { kind: "text_delta", text: nearMatch, ordinal: 0 }, + { kind: "usage", usage: usage(1, 1) }, + { kind: "end", finishReason: "stop", usage: usage(1, 1), messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => events }); + + const started = performance.now(); + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + stream: true, + stop_sequences: [sequence], + messages: [{ role: "user", content: "say a lot of a" }], + }); + const elapsed = performance.now() - started; + + expect(response.statusCode).toBe(200); + const frames = parseSse(response.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const visible = frames + .filter((frame) => frame.delta?.type === "text_delta") + .map((frame) => frame.delta?.text ?? "") + .join(""); + // No match, so the held tail is released unchanged. + expect(visible).toBe(nearMatch); + // ~5 s before the fix; a quadratic implementation cannot pass this bound. + expect(elapsed).toBeLessThan(1_000); + }); +}); + describe("thinking.effort (A12)", () => { it("is no longer stripped from the thinking block", async () => { const capture: { request?: InternalRequest } = {}; diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index eff3e67..bfcdf1c 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -980,12 +980,15 @@ describe("POST /v1/responses (streaming)", () => { "response.output_item.added", "response.reasoning_summary_part.added", "response.reasoning_summary_text.delta", - "response.reasoning_summary_text.done", - "response.reasoning_summary_part.done", + // The summary closes once the turn's reasoning is final, not on each + // step-level `reasoning_end` (which upstream emits per step with a + // snapshot of that step alone). "response.output_item.added", "response.content_part.added", "response.output_text.delta", "response.output_text.delta", + "response.reasoning_summary_text.done", + "response.reasoning_summary_part.done", "response.output_item.done", "response.output_text.done", "response.content_part.done", @@ -1430,6 +1433,123 @@ describe("POST /v1/responses (streaming)", () => { ); }); + it("reuses the announced output_index when the text item is opened first", async () => { + // A text-then-reasoning turn: the message item is announced first, so it owns + // index 0 and the reasoning item that follows owns index 1. The old code + // pinned reasoning to index 0 while the message index was recomputed at emit + // time, so both `.added` frames claimed index 0, the later frames reported the + // wrong index, and the terminal `output[]` came back reasoning-first. + const app = await makeApp({ + script: (): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 4, outputTokens: 6, reasoningTokens: 5, totalTokens: 15 }; + return [ + { kind: "start", sessionId: "ses_order", messageId: "msg_order", model: "opencode/deepseek-v4.1-flash-free", agent: "build", reusedSession: false, reasoningEnabled: true }, + { kind: "text_delta", text: "Answer first.", ordinal: 0 }, + { kind: "reasoning_delta", text: "thinking", ordinal: 0 }, + { kind: "reasoning_delta", text: " harder", ordinal: 0 }, + { kind: "reasoning_end", text: "thinking harder", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_order" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "Think.", + stream: true, + reasoning: { effort: "high" }, + }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + + const addedByItem = new Map(); + for (const frame of parsed) { + if (frame.json["type"] !== "response.output_item.added") continue; + const item = frame.json["item"] as ResponseItem; + const index = frame.json["output_index"] as number; + expect(addedByItem.has(item.type), `item type '${item.type}' was announced twice`).toBe(false); + addedByItem.set(item.type, { index, id: item.id }); + } + expect(addedByItem.get("message")?.index).toBe(0); + expect(addedByItem.get("reasoning")?.index).toBe(1); + + // Every later frame for an item reuses the index its announcement recorded. + const messageFrames = parsed.filter((frame) => frame.json["item_id"] === addedByItem.get("message")?.id); + expect(messageFrames.length).toBeGreaterThan(1); + expect(messageFrames.every((frame) => frame.json["output_index"] === 0)).toBe(true); + + const reasoningFrames = parsed.filter( + (frame) => + frame.json["type"] === "response.reasoning_summary_text.delta" || + frame.json["type"] === "response.reasoning_summary_text.done", + ); + expect(reasoningFrames.length).toBeGreaterThan(1); + expect(reasoningFrames.every((frame) => frame.json["output_index"] === 1)).toBe(true); + + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + // Announcement order, not the fixed reasoning/text/calls order the old + // terminal payload used, and the same full text the frames streamed. + expect(final.output.map((item) => item.type)).toEqual(["message", "reasoning"]); + expect(final.output[0]?.content?.[0]?.text).toBe("Answer first."); + expect(final.output[1]?.summary).toEqual([{ type: "summary_text", text: "thinking harder" }]); + expect(final.output_text).toBe("Answer first."); + }); + + it("adopts a step-level reasoning_end only when it is longer than the streamed deltas", async () => { + // A multi-step turn snapshots its reasoning per step. The short snapshot must + // not overwrite the longer text already streamed, and each summary_index must + // be closed exactly once. + const app = await makeApp({ + script: (): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 4, outputTokens: 6, reasoningTokens: 9, totalTokens: 19 }; + return [ + { kind: "start", sessionId: "ses_multi", messageId: "msg_multi", model: "opencode/deepseek-v4.1-flash-free", agent: "build", reusedSession: false, reasoningEnabled: true }, + { kind: "reasoning_delta", text: "first step ", ordinal: 0 }, + { kind: "reasoning_end", text: "first step", ordinal: 0 }, + { kind: "reasoning_delta", text: "second step", ordinal: 1 }, + { kind: "reasoning_end", text: "second step", ordinal: 1 }, + { kind: "text_delta", text: "Done.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_multi" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "Think in two steps.", + stream: true, + reasoning: { effort: "high" }, + }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const summaryDone = parsed.filter((frame) => frame.json["type"] === "response.reasoning_summary_text.done"); + // One `.done` per `summary_index`: the first `reasoning_end` carried a + // truncated snapshot (`"first step"`, 10 chars, vs 11 streamed) and the old + // code still emitted a second `.done` for it. + expect(summaryDone).toHaveLength(1); + expect(summaryDone[0]?.json["summary_index"]).toBe(0); + // The concatenated deltas survive: the step snapshot never truncates them. + expect(summaryDone[0]?.json["text"]).toBe("first step second step"); + + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + expect(final.output.find((item) => item.type === "reasoning")?.summary).toEqual([ + { type: "summary_text", text: "first step second step" }, + ]); + expect(final.output_text).toBe("Done."); + }); + it("awaits writer drain under backpressure and still closes the stream", async () => { // Force the first `raw.write()` to report a full socket buffer, then emit // `drain` asynchronously. The loop only resumes producing after it has diff --git a/test/parity.test.ts b/test/parity.test.ts index 1460213..46b76a4 100644 --- a/test/parity.test.ts +++ b/test/parity.test.ts @@ -602,6 +602,123 @@ describe.each(SURFACE_CASES)("streamed/buffered parity — $name", (surface) => ]); } + expect(streamedTurn).toEqual(bufferedTurn); + } finally { + await app.close(); + } + }); +}); + +// ------------------------------------------------------- consolidated text --- + +/** + * The turn a provider delivers without any `text_delta`: the whole answer + * arrives in the step-scoped `text_end` event. + * + * `docs/ARCHITECTURE.md` §4.3 requires every surface — streamed and buffered — + * to adopt a consolidated end event only when it is longer than what the deltas + * produced. A surface that ignores it answers an empty 200, while the buffered + * body of the very same request carries the answer (P-21). + */ +const TEXT_END_ONLY = "The whole answer arrived at once."; + +function textEndScript(request: InternalRequest): CompletionEvent[] { + return [ + { + kind: "start", + sessionId: UPSTREAM_SESSION_ID, + messageId: UPSTREAM_MESSAGE_ID, + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_end", text: TEXT_END_ONLY, ordinal: 0, messageId: UPSTREAM_MESSAGE_ID }, + { kind: "usage", usage: USAGE }, + { kind: "end", finishReason: "stop", usage: USAGE, messageId: UPSTREAM_MESSAGE_ID }, + ]; +} + +describe.each(SURFACE_CASES)("consolidated text_end parity — $name", (surface) => { + it("returns the buffered answer on the streamed path too", async () => { + const ctx = createTestContext({ script: textEndScript }); + const app = await buildServer(ctx); + try { + const buffered = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(false), + }); + expect(buffered.statusCode, buffered.body).toBe(200); + + const streamed = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(true), + }); + expect(streamed.statusCode, streamed.body).toBe(200); + expect(streamed.headers["content-type"]).toContain("text/event-stream"); + + const bufferedTurn = surface.buffered(buffered.json() as Record); + const streamedTurn = surface.streamed(streamed.body); + + // The buffered path is the reference: the scripted turn has exactly one + // place the answer can come from. + expect(bufferedTurn.text).toBe(TEXT_END_ONLY); + expect(streamedTurn.text).toBe(TEXT_END_ONLY); + expect(streamedTurn).toEqual(bufferedTurn); + } finally { + await app.close(); + } + }); + + it("does not duplicate or reorder text the deltas already delivered", async () => { + // A step that streamed its deltas and then reports the same text in + // `text_end` must not emit it twice, and a *shorter* consolidated snapshot + // (an intermediate step of a multi-step turn) must not truncate the answer. + const script = (request: InternalRequest): CompletionEvent[] => [ + { + kind: "start", + sessionId: UPSTREAM_SESSION_ID, + messageId: UPSTREAM_MESSAGE_ID, + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Hello ", ordinal: 0 }, + { kind: "text_delta", text: "world", ordinal: 0 }, + { kind: "text_end", text: "Hello world", ordinal: 0, messageId: UPSTREAM_MESSAGE_ID }, + { kind: "text_delta", text: " again", ordinal: 0 }, + { kind: "text_end", text: "Hello world", ordinal: 0, messageId: UPSTREAM_MESSAGE_ID }, + { kind: "usage", usage: USAGE }, + { kind: "end", finishReason: "stop", usage: USAGE, messageId: UPSTREAM_MESSAGE_ID }, + ]; + const ctx = createTestContext({ script }); + const app = await buildServer(ctx); + try { + const buffered = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(false), + }); + expect(buffered.statusCode, buffered.body).toBe(200); + const streamed = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(true), + }); + expect(streamed.statusCode, streamed.body).toBe(200); + + const bufferedTurn = surface.buffered(buffered.json() as Record); + const streamedTurn = surface.streamed(streamed.body); + + expect(bufferedTurn.text).toBe("Hello world again"); + expect(streamedTurn.text).toBe("Hello world again"); expect(streamedTurn).toEqual(bufferedTurn); } finally { await app.close(); diff --git a/test/tools.test.ts b/test/tools.test.ts index e3750b3..a6018c7 100644 --- a/test/tools.test.ts +++ b/test/tools.test.ts @@ -185,6 +185,39 @@ describe("parseToolCallBody", () => { expect(parsed.calls.map((call) => call.name)).toEqual(["a", "b"]); expect(parsed.text).toBe(""); }); + + it("keeps stripping a fence around a real payload", () => { + // The rewrite replaced two regexes with linear string walks; the wire shape + // for genuine envelopes (language tag, newline, surrounding blank lines) + // must not change. + expect(parseToolCallBody('```json\n{"name":"a","arguments":{"x":1}}\n```')[0]?.arguments).toBe('{"x":1}'); + expect(parseToolCallBody('\n\n```\n{"name":"a","arguments":{}}\n```\n\n')[0]?.name).toBe("a"); + const indented = parseToolCallBody(' ```JSON5 \n {"name":"a","arguments":{}} \n``` '); + expect(indented[0]?.name).toBe("a"); + // No fence: the payload is parsed as before. + expect(parseToolCallBody(' {"name":"a","arguments":{}} ')[0]?.name).toBe("a"); + }); + + it("keeps a real envelope intact when the payload carries a long whitespace run", () => { + // Only a body that is *entirely* whitespace collapses to no calls; a long + // whitespace argument value must still be parsed and preserved. + const whitespace = " ".repeat(64 * 1024); + const calls = parseToolCallBody(`{"name":"a","arguments":{"text":"${whitespace}"}}`); + expect(calls.map((call) => call.name)).toEqual(["a"]); + expect(JSON.parse(calls[0]?.arguments ?? "null")).toEqual({ text: whitespace }); + }); + + it("parses a 64 KiB whitespace body in linear time", () => { + // `.replace(/\s*```\s*$/, "")` re-tried the leading `\s*` at every offset, so + // this body cost about a second of blocked event loop per parse. A generous + // wall-clock bound is enough to tell linear from quadratic at this size (the + // old code took ~1 s, the linear walk takes well under a millisecond). + const body = " ".repeat(64 * 1024); + expect(parseToolCallBody(body)).toEqual([]); + const startedAt = performance.now(); + expect(parseToolCallBody(body)).toEqual([]); + expect(performance.now() - startedAt).toBeLessThan(250); + }); }); describe("normaliseArguments", () => { From 63fd76196452655617fe53b2a27a1473600e0383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:32:59 +0700 Subject: [PATCH 08/10] docs: document every route and metric label `GET /` and `docs/API.md` omitted five registered routes (`/healthz`, the model refresh, the two session routes and the upstream restart). The metrics reference gave `upstream_request_duration_seconds` an `outcome` label it does not have, README listed ten of the thirteen exported series, and `/metrics` was missing from the rate-limit exemptions. The verification addendum had stale counts and line references. The docs-consistency test now also compares the documented `GET /` index against the routes `src/` registers, and every metric series against both documents, so the next addition cannot drift unnoticed. --- README.md | 6 +- docs/API.md | 16 +++-- docs/ARCHITECTURE.md | 37 +++++++++-- docs/VERIFICATION.md | 71 ++++++++++++++++++++- test/docs-consistency.test.ts | 113 +++++++++++++++++++++++++++++++++- 5 files changed, 227 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 46722d5..cd98d54 100644 --- a/README.md +++ b/README.md @@ -515,8 +515,10 @@ Every variable, with types, defaults and security notes: `opencode_api_`: `http_requests_total`, `http_request_duration_seconds`, `upstream_requests_total`, `upstream_request_duration_seconds`, `tokens_total`, `completions_total`, `active_streams`, `upstream_restarts_total`, - `session_cache_entries`, `event_stream_connected`, plus process defaults. Requires a key unless - `OPENCODE_METRICS_PUBLIC=true`. + `session_cache_entries`, `event_stream_connected`, `event_stream_reconnects_total`, + `event_frames_dropped_total`, `rate_limit_rejections_total`, plus process + defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true`. `/metrics` is + never rate limited, so a local scraper cannot be throttled by its own traffic. * **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog counts, session count), `/admin/config` (effective configuration with API keys and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions` diff --git a/docs/API.md b/docs/API.md index f678a3c..d6d5644 100644 --- a/docs/API.md +++ b/docs/API.md @@ -896,6 +896,7 @@ Unknown ids return `404`: "service": "opencode-api", "version": "1.0.0", "endpoints": [ + "GET /", "POST /v1/chat/completions", "POST /v1/responses", "POST /v1/completions", @@ -903,12 +904,18 @@ Unknown ids return `404`: "POST /v1/messages/count_tokens", "GET /v1/models", "GET /v1/models/{id}", + "GET /v1/models/*", "POST /v1/embeddings", "GET /health", "GET /ready", + "GET /healthz", "GET /metrics", "GET /admin/status", - "GET /admin/config" + "GET /admin/config", + "POST /admin/models/refresh", + "GET /admin/sessions", + "DELETE /admin/sessions", + "POST /admin/upstream/restart" ] } ``` @@ -933,8 +940,8 @@ These are not model surfaces; they report or control gateway state. When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charged against a per-key token bucket (with a separate bucket for `/admin/*`). A rejected request answers `429` with `error.code: "rate_limit_exceeded"` and a -`retry-after` header in seconds. `/health`, `/ready`, `/healthz` and `/` are never -rate limited. +`retry-after` header in seconds. `/health`, `/ready`, `/healthz`, `/metrics` and `/` +are never rate limited. ### Metrics @@ -944,7 +951,8 @@ rate limited. | Series | Type | Labels | | --- | --- | --- | | `http_requests_total`, `http_request_duration_seconds` | counter, histogram | `method`, `route`, `status` | -| `upstream_requests_total`, `upstream_request_duration_seconds` | counter, histogram | `operation`, `outcome` | +| `upstream_requests_total` | counter | `operation`, `outcome` | +| `upstream_request_duration_seconds` | histogram | `operation` | | `tokens_total` | counter | `model`, `direction` | | `completions_total` | counter | `surface`, `model`, `stream`, `finish_reason`, `error_code` | | `active_streams` | gauge | `surface` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 28c4811..7c92bb4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -147,12 +147,22 @@ interrupts the session and fails the turn with `503 event_stream_lost` instead o returning a silently truncated answer. A half-open socket never rejects `read()`, so every read is bounded by an idle watchdog (three documented heartbeats, overridable through `EventHubOptions.idleTimeoutMs` in -tests); the connection attempt itself is bounded by the same watchdog, so an -upstream that accepts the socket and never writes a response head cannot park the -hub indefinitely. Expiry fails the connection so the loop reconnects. `stop()` and +tests); the connect phase alone is bounded by the same watchdog, so an upstream +that accepts the socket and never writes a response head cannot park the hub +indefinitely. That connect timer is cleared as soon as the response head arrives: +the deadline must never fire against a stream that is actively sending +heartbeats. Expiry fails the connection so the loop reconnects. Half-received +frame text is assembled in a buffer capped at 1 MiB; a chunk that crosses the cap +without a blank line drops the partial frame (unusable either way), increments +`event_frames_dropped_total{reason="malformed"}` and starts the next frame from a +clean buffer, so a re-framing proxy or a dialect mismatch cannot grow the buffer +without bound or turn every chunk into an O(buffer) scan. `stop()` and every other exit cancel the response body reader and zero the `event_stream_connected` gauge, and `#controller` is cleared when a connection -attempt returns. The reconnect delay is reset only after a connection has actually +attempt returns. Each loop is stamped with a generation that `stop()` retires, so +a `start()` racing an old loop that is still parked in `read()` cannot leave two +loops consuming the same upstream stream. The reconnect delay is reset only after +a connection has actually delivered `server.connected`, so an accept-then-close upstream backs off instead of being polled four times a second. @@ -271,6 +281,15 @@ timeout (`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than t candidates while keeping the conversation key, so a stale-session replay caches its replacement where the next turn of that conversation will find it. +`execute()`'s `finally` settles the sticky record on every exit. When the turn did +not complete it releases the record; a session that was **created for that turn** +(`!prepared.reused`) has no record yet, so the release finds nothing and the +eviction hook never fires — the upstream session would then outlive the failed +turn for the life of `opencode serve`. In that case the same `finally` also issues +a best-effort `deleteSession()`, so a first turn that fails (429, timeout, +disconnect, `event_stream_lost`) leaves no orphan. Reused sessions keep being +deleted by the session-store eviction hook. + `stop()` is deliberately **non-terminal**: `POST /admin/upstream/restart` and the retry paths call `stop()`/`invalidate()` and then `resolve()` again, and `test/process.test.ts` pins that. `shutdown()` is the terminal variant, used only @@ -302,7 +321,15 @@ answer. The streamed surfaces apply the same rule independently. `finish_reason` stays within the documented `FinishReason` values and a failure adds a bounded `error_code` label (the gateway's own `ApiError.code`), so a lost event stream is counted as `finish_reason="error", error_code="event_stream_lost"` -rather than as its own finish reason. `upstream_restarts_total{reason}` is +rather than as its own finish reason. The label is filtered through a closed +allow-list built from the gateway's own codes, the provider codes documented in +§2 and `http_`, with `"other"` as the fallback — several paths copy the +code verbatim from an upstream `record.type` / `_tag`, and prom-client never +evicts a label set, so an unfiltered value would become a permanent time series. +Pre-flight exits count too: model resolution, modality validation and session +creation fail before `execute()` can report its own outcome, so they are recorded +in the same counter with the model label that is actually known (`"unknown"` when +resolution itself failed). `upstream_restarts_total{reason}` is classified once per published server (`initial`, `stale`, `invalidated`, `restart`). diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 793a8a1..161be8f 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -126,7 +126,7 @@ leak with operational impact) / **minor** (incorrect behaviour in an edge case o ### Not reported (checked and found correct) -* Auth: every non-public route is behind the global `preHandler`; `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. A disallowed origin receives the same 204 without any `access-control-*` header, so the browser blocks the response and never sends the real request. An allowed origin additionally receives `access-control-allow-headers` covering the official OpenAI and Anthropic SDK headers and `access-control-expose-headers: x-request-id`. +* Auth: every non-public route is behind the global `onRequest` hook (so an anonymous caller is rejected before Fastify buffers or parses the body); `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. A disallowed origin receives the same 204 without any `access-control-*` header, so the browser blocks the response and never sends the real request. An allowed origin additionally receives `access-control-allow-headers` covering the official OpenAI and Anthropic SDK headers and `access-control-expose-headers: x-request-id`. * Constant-time comparison is used for keys (`timingSafeEqual` with a length guard). * Local paths: `realpath` is applied **before** the `allowedFileRoots` check, and only the OpenAI `document` part exposes a path field — symlink escape and traversal are correctly blocked. The file is now read through one handle (`fsp.open` with `O_NOFOLLOW` where the platform has it, then `fstat` and `read`), so a final-component swap after the check cannot redirect the read, and an unreadable or vanished file returns 400 `invalid_attachment` / `attachment_not_found` instead of a 500. Residual risks, not closed by `realpath` + `O_NOFOLLOW`: hard links created inside an allowed root, a swapped parent directory, and Windows reparse points (Node exposes no `openat2`/`RESOLVE_BENEATH`). * Attachment caps: `OPENCODE_MAX_ATTACHMENTS` and `OPENCODE_MAX_ATTACHMENT_BYTES` are enforced while media is resolved, not only when it is forwarded. One budget per request covers every message and every nested `tool_result` block, the count slot is claimed before the first `await`, downloads run in a bounded pool, and the first hard failure aborts the in-flight siblings instead of letting them run to the fetch timeout. @@ -134,8 +134,8 @@ leak with operational impact) / **minor** (incorrect behaviour in an edge case o * SSE framing: `[DONE]` is emitted only by `/v1/chat/completions`; Anthropic block indexes are contiguous `0,1,2…` with matching `content_block_start/stop`; Responses `sequence_number` is strictly increasing and unique (verified: `[0..15]`, strictly increasing `true`); in-stream error frames were observed on all three surfaces. * `content: null` is emitted by the chat adapter exactly when a tool call exists and no text was produced; `finish_reason`/`stop_reason` mapping matches the documented tables (`length`→`max_tokens`, `content_filter`→`refusal`, bridged calls→`tool_calls`/`tool_use`). * `OPENCODE_AGENT_PERMISSIONS` / `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` deny rules are merged correctly (`bash, webfetch, websearch, edit, write, patch, task, skill`). -* Every environment variable in `src/config.ts` (46) appears in `.env.example` (46) and in `docs/CONFIGURATION.md` (46) — exact match, no extras either way. -* No `TODO`/`FIXME`/`XXX`/stub markers anywhere in `src/`; no `any` annotations (three widening casts exist: `as never` twice in `src/upstream/completion.ts:229,433` and `as unknown as FastifyInstance` in `src/server.ts:34`, all narrowing-free and none of which was observed to hide a runtime defect); all sources, tests, comments and docs are English (CJK/Cyrillic scan: none). +* Every environment variable in `src/config.ts` (49) appears in `.env.example` (49) and in `docs/CONFIGURATION.md` (49) — exact match, no extras either way. +* No `TODO`/`FIXME`/`XXX`/stub markers anywhere in `src/`; no `any` annotations (three widening casts exist: `as never` twice in `src/upstream/completion.ts:382,685` and `as unknown as FastifyInstance` in `src/server.ts:65`, all narrowing-free and none of which was observed to hide a runtime defect); all sources, tests, comments and docs are English (CJK/Cyrillic scan: none). * Requirements 1–9 are all implemented; `src/` contains TypeScript only (`scripts/smoke.mjs` is an operator script, not a source module). ## 4. Docker review @@ -257,3 +257,68 @@ is in the git history; the entries that touch the findings above are: * `stop` is now honoured on `/v1/chat/completions` and `/v1/completions`, and the generation knobs the gateway cannot apply are named in `x_opencode.unapplied` instead of being silently dropped (`docs/API.md`). + +### Addendum — remediation pass of 2026-12-03 (P-01 … P-25) + +Recorded so the counts and line references above are read against the current +tree. **The revision these statements describe is the `87d10db` base plus the +remediation changes carried by the accompanying commit on the review branch** +(the pass was verified in the working tree before it was committed, and the +branch carries the same `docs/API.md`, `docs/ARCHITECTURE.md` and `src/` state). + +What changed in the numbers this document quotes: + +* `src/config.ts` now reads **49** environment variables, all 49 documented in + `.env.example` and `docs/CONFIGURATION.md` (§3, second-to-last bullet). +* the widening casts moved: `as never` is at `src/upstream/completion.ts:382,685` + and the Fastify cast at `src/server.ts:65` (both refreshed above). +* `test/docs-consistency.test.ts` now enforces three lists that had already + drifted once: the environment variables (unchanged), the `GET /` endpoint index + in `docs/API.md` against the routes `src/` registers (19 entries, including + `GET /`, `GET /healthz`, `GET /v1/models/*` and the four `/admin/*` routes the + index had omitted), and every metric series declared in + `src/metrics/registry.ts` against `docs/API.md` and `README.md`. + +What the pass changed, beyond the pre-remediation findings above: + +* **Authentication and rate limiting run `onRequest`** (`src/server.ts`), before + Fastify buffers and parses the body; an unauthenticated caller can no longer + spend `bodyLimitBytes` per connection. The limiter buckets credential-less + callers by `request.ip` and its bucket map is bounded, the public-path check is + canonicalised, and the `GET /` index now matches the registered routes. +* **The upstream event hub** clears its connect-phase watchdog once the response + head arrives, caps the frame-assembly buffer at 1 MiB, and stamps each loop + with a generation `stop()` retires, so a healthy stream is no longer aborted + every 45 s and a `stop()`/`start()` race cannot run two consumers. +* **The model catalogue survives an empty refresh**, `completions_total` counts + pre-flight failures with a closed `error_code` label, a failed first turn + deletes the upstream session it created, `reusedCount` is incremented, the + partial stderr line is bounded, and each message is serialised once per turn. +* **The streamed OpenAI surfaces adopt a consolidated `text_end`** like + `/v1/responses` and the buffered path already did; `/v1/responses` fixes its + `output_index` at announcement time and adopts a step-level `reasoning_end` + only when it is longer; `/v1/messages` keeps every tool call the buffered route + returns and its stop-sequence filter is O(1) instead of O(n²). The Anthropic + stream announces blocks in arrival order rather than withholding text until a + possible thinking block is known — withholding was prototyped and rejected + because it turned a text-only streamed answer into a single burst. +* **`/v1/messages` stop-sequence scanning** and the tool-envelope fence parsing + are now linear (a 64 KiB near-match dropped from ~5 s to under 2 ms). + +What was re-verified for the pass: + +| Command | Result | +| --- | --- | +| `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | +| `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0 | +| `pnpm test` | **PASS** — 24 files, **542 passed**, 4 skipped | +| `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0` | +| `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — `Test Files 1 passed (1)`, `Tests 11 passed (11)` | +| `docker build --tag opencode-api:ci .` | **PASS** — image built from the current tree | +| `docker run --detach … -e OPENCODE_AUTOSTART=false -e OPENCODE_API_KEYS=… opencode-api:ci` + `GET /health` | **PASS** — `200 {"status":"ok",…,"upstream":{"ready":false,"source":null}}` after ~2 s, container still `running`; the same sequence is the new `Docker image` CI step | +| `cp .env.example .env && docker compose config --quiet` | **PASS** — exit 0 after the `.dockerignore` change (temporary `.env` removed afterwards) | + +Still unresolved at the time of writing: none of the P-01 … P-25 items were left +open; the P-14/P-15/P-16/P-17/P-19 documentation, Docker and CI items and the +P-18 image smoke test are covered above, and the remaining source-level items are +covered by the regression tests named in the proposals file. diff --git a/test/docs-consistency.test.ts b/test/docs-consistency.test.ts index 792f9ba..fb6c4f5 100644 --- a/test/docs-consistency.test.ts +++ b/test/docs-consistency.test.ts @@ -8,11 +8,17 @@ * variable could be added to the code, or deleted from a document, with CI * still green. * + * The same idea is applied to the two other reference lists that had drifted + * once already: the `GET /` endpoint index in `docs/API.md` must name exactly + * the routes the server registers (P-14), and every metric series in + * `src/metrics/registry.ts` must be documented in `docs/API.md` (P-15). + * * The sources are read as text on purpose. Importing `src/config.ts` would * execute the module, and the guard must observe the call sites rather than a - * loaded configuration. + * loaded configuration; the route and metric inventories are likewise read from + * their declaring modules. */ -import { readFileSync } from "node:fs"; +import { readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; @@ -108,3 +114,106 @@ describe("environment-variable documentation", () => { expect(missing(documentedVariables(configurationSummary(README_TEXT)), CODE_VARIABLES)).toEqual([]); }); }); + +// ------------------------------------------------------------------- P-14 --- + +/** The `GET /` endpoint index in `docs/API.md`, as `METHOD /path` strings. */ +function documentedIndex(markdown: string): string[] { + const heading = markdown.indexOf("## Gateway root"); + if (heading < 0) throw new Error("docs/API.md has no '## Gateway root' section"); + const fence = markdown.indexOf("```json", heading); + const end = markdown.indexOf("```", fence + 7); + if (fence < 0 || end < 0) throw new Error("docs/API.md 'Gateway root' has no JSON block"); + const body = markdown.slice(fence + 7, end); + const entries: string[] = []; + for (const match of body.matchAll(/"((?:GET|POST|DELETE|PUT|PATCH)\s+\/[^"]*)"/g)) { + const value = match[1]; + if (value !== undefined) entries.push(value.replace(/\s+/g, " ").trim()); + } + return entries; +} + +/** Every route `src/` registers, as `METHOD /path` strings. */ +function registeredRoutes(): string[] { + const files: string[] = []; + const walk = (directory: string): void => { + for (const entry of readdirSync(path.join(repoRoot, directory), { withFileTypes: true })) { + const relative = `${directory}/${entry.name}`; + if (entry.isDirectory()) walk(relative); + else if (entry.name.endsWith(".ts")) files.push(relative); + } + }; + walk("src"); + + const routes = new Set(); + // `app.get<{ Params: ... }>("...")` declares a generic before the path, so the + // typed registrations have to match too. + const pattern = /\bapp\.(get|post|delete|put|patch)(?:<[^>]*>)?\(\s*"([^"]+)"/g; + for (const file of files) { + for (const match of readFileSync(path.join(repoRoot, file), "utf8").matchAll(pattern)) { + const method = match[1]; + const routePath = match[2]; + if (method === undefined || routePath === undefined) continue; + // Fastify spells a parameter `:id`; the documented index spells it `{id}`. + routes.add(`${method.toUpperCase()} ${routePath.replace(/:([A-Za-z0-9_]+)/g, "{$1}")}`); + } + } + return [...routes].sort(); +} + +describe("the GET / endpoint index (docs/API.md)", () => { + it("parses an index out of the documentation", () => { + // A broken extraction must not turn the comparison below into a no-op. + expect(documentedIndex(read("docs/API.md")).length).toBeGreaterThanOrEqual(18); + }); + + it("lists exactly the routes src/ registers", () => { + expect([...documentedIndex(read("docs/API.md"))].sort()).toEqual(registeredRoutes()); + }); + + it("spells every entry as 'METHOD /path' with one space", () => { + for (const entry of documentedIndex(read("docs/API.md"))) { + expect(entry, `the index entry "${entry}" is not canonical`).toMatch(/^[A-Z]+ \/\S*$/); + } + }); +}); + +// ------------------------------------------------------------------- P-15 --- + +/** + * The application metric names declared in `src/metrics/registry.ts`. + * + * Every collector is declared as `` `${prefix}` ``, so the literal after + * the prefix is the name `GET /metrics` exposes under `opencode_api_`. + */ +function metricNames(): string[] { + const names = new Set(); + const source = read("src/metrics/registry.ts"); + for (const match of source.matchAll(/name:\s*`\$\{prefix\}([a-z0-9_]+)`/g)) { + const name = match[1]; + if (name !== undefined) names.add(name); + } + return [...names].sort(); +} + +describe("the metric documentation (docs/API.md)", () => { + it("finds the metric names src/metrics/registry.ts declares", () => { + // A broken extraction must not turn the check below into a silent no-op. + expect(metricNames().length).toBeGreaterThanOrEqual(13); + for (const name of ["http_requests_total", "upstream_request_duration_seconds", "completions_total"]) { + expect(metricNames(), `${name} was not parsed out of src/metrics/registry.ts`).toContain(name); + } + }); + + it("mentions every metric series in docs/API.md", () => { + const documentation = read("docs/API.md"); + const undocumented = metricNames().filter((name) => !documentation.includes(name)); + expect(undocumented).toEqual([]); + }); + + it("mentions every metric series in README.md", () => { + const readme = read("README.md"); + const undocumented = metricNames().filter((name) => !readme.includes(name)); + expect(undocumented).toEqual([]); + }); +}); From 989694101f6a7680047652407c1c5707c220c4c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:32:59 +0700 Subject: [PATCH 09/10] ci: smoke the built image and track its base image The docker job only built the image and validated the compose file, so `pnpm prune --prod`, the copied file set and the HEALTHCHECK were never exercised. It now starts the image with `OPENCODE_AUTOSTART=false` and a test key, polls `/health` on a Docker-assigned port and fails when the container exits. Dependabot gains the `docker` ecosystem so a base-image security release arrives as a pull request, and `.dockerignore` excludes `.env` so a real key file never enters the build context. --- .dockerignore | 7 ++++++ .github/dependabot.yml | 11 +++++++++ .github/workflows/ci.yml | 53 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/.dockerignore b/.dockerignore index fd37662..e3f3aeb 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,3 +6,10 @@ workspace test .recon *.log + +# Never upload a real key file into the build context, and never let a future +# `COPY . .` bake it into a layer. `.env.example` carries no secret and is the +# file the docs tell operators to copy, so it stays. +.env +.env.* +!.env.example diff --git a/.github/dependabot.yml b/.github/dependabot.yml index fbd4559..26049cd 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -31,3 +31,14 @@ updates: open-pull-requests-limit: 10 commit-message: prefix: "ci(deps)" + + # The base images pinned in Dockerfile (`node:22-bookworm-slim`, both stages), + # so a security release of the Node image arrives as a pull request instead of + # ageing silently. + - package-ecosystem: docker + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + commit-message: + prefix: "build(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 598ce0b..a33b248 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -180,7 +180,9 @@ jobs: run: pnpm test # The README documents a Docker deployment; nothing verified the Dockerfile - # until this job existed, so a broken image could merge unnoticed. + # until this job existed, so a broken image could merge unnoticed. Building is + # not enough: the image is started and probed so `pnpm prune --prod`, the + # copied file set and the runtime entry point are exercised too. docker: name: Docker image runs-on: ubuntu-latest @@ -201,3 +203,52 @@ jobs: run: | cp .env.example .env docker compose config --quiet + + # The image does not contain the OpenCode CLI, so the container is started + # with OPENCODE_AUTOSTART=false: /health must answer without any upstream + # being reachable. `-p 127.0.0.1:0:20123` lets Docker choose a free host + # port, which is then read back with `docker port`, so this never + # conflicts with a gateway already listening on the runner. + - name: Run the image and probe /health + run: | + set -euo pipefail + + container_id="$(docker run --detach --rm \ + --name opencode-api-ci \ + -p 127.0.0.1:0:20123 \ + --env OPENCODE_AUTOSTART=false \ + --env OPENCODE_API_KEYS=ci-docker-smoke-key \ + opencode-api:ci)" + + # Always stop and remove the container, also when the probe fails. + cleanup() { + docker stop "$container_id" >/dev/null 2>&1 || true + docker rm --force "$container_id" >/dev/null 2>&1 || true + } + trap cleanup EXIT + + probing="$(docker port "$container_id" 20123/tcp)" + port="${probing##*:}" + echo "Probing http://127.0.0.1:${port}/health" + + healthy="false" + for _ in $(seq 1 30); do + if [ "$(docker inspect --format '{{.State.Running}}' "$container_id")" != "true" ]; then + echo "::error::the gateway container exited before answering /health" + docker logs "$container_id" || true + exit 1 + fi + if curl --fail --silent --show-error --max-time 2 \ + "http://127.0.0.1:${port}/health" >/dev/null; then + healthy="true" + break + fi + sleep 1 + done + + if [ "$healthy" != "true" ]; then + echo "::error::/health did not answer within 30 s" + docker logs "$container_id" || true + exit 1 + fi + echo "The image answers /health." From 44b5d390fa2c7170b87104db215f21b1305260a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 13:32:59 +0700 Subject: [PATCH 10/10] fix(server): exit non-zero when shutdown rejects `shuttingDown` is set before `performShutdown()` is awaited and later signals are ignored, so a rejecting shutdown left the process alive with the HTTP server closed and no exit code for the supervisor. The rejection is logged and the process exits with status 1. --- src/index.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9f174a0..a4bac73 100644 --- a/src/index.ts +++ b/src/index.ts @@ -135,7 +135,17 @@ async function main(): Promise { for (const signal of ["SIGINT", "SIGTERM"] as const) { process.on(signal, () => { - void shutdown(signal); + // A failed shutdown has already closed the HTTP server and set + // `shuttingDown`, so any later signal is ignored: without an exit code the + // supervisor sees a process that is half-alive. Log it and leave with a + // failure code instead. + void shutdown(signal).catch((error: unknown) => { + log.error( + { err: error instanceof Error ? error.message : String(error), signal }, + "shutdown failed; exiting", + ); + process.exit(1); + }); }); }