From 08671419070b48a9aff4647021ce8d564a8bfcce Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:45:30 +0800 Subject: [PATCH 1/3] fix: workspace link check retries once and reports a served saved link as a fallback - by-remote/by-path retry once on a new connection after a timeout, network error or 502/503/504. - A failure where the saved link is served sends `workspace_link_check_stale`, not `workspace_api_error`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- docs/docs/reference/telemetry.md | 3 +- .../opencode/src/altimate/telemetry/index.ts | 11 ++ .../src/altimate/workspace/api-client.ts | 118 +++++++++++++----- .../opencode/src/altimate/workspace/state.ts | 13 +- .../telemetry/workspace-context.test.ts | 8 +- .../workspace/link-check-stale.test.ts | 99 +++++++++++++++ .../altimate/workspace/link-telemetry.test.ts | 73 ++++++++++- 7 files changed, 289 insertions(+), 36 deletions(-) create mode 100644 packages/opencode/test/altimate/workspace/link-check-stale.test.ts diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index c5e1639caf..ec369a6a5c 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -102,7 +102,8 @@ These events describe projects linked to an Altimate workspace. A workspace is i | `workspace_unlinked` | A project was unlinked, with the workspace id when the CLI knew it. | | `workspace_switched` | A linked project was moved to another workspace. `how` is `rebind_remote` or `rebind_path`. | | `workspace_auth_expired` | A workspace call was answered 401: the sign-in has expired. Carries `endpoint` and `status`. | -| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. | +| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. The link lookups (`by-remote`, `by-path`) are retried once after a timeout, a network error or a 502, 503 or 504, and only a failure that outlasts the retry is reported. | +| `workspace_link_check_stale` | The check of which workspace a project is linked to failed after its retry, and the saved link was used instead. Carries `endpoint`, `status_class` and `status` as `workspace_api_error` does. Reported in place of `workspace_api_error` because the user never sees it; a 401 is still `workspace_auth_expired`. | | `starter_shown` | The "what this workspace provides" starter was served after a link: to the TUI, to the IDE extension's chat, or printed by `altimate-code link`. It counts the starter being served, so a client that closes before rendering it is still counted. Contains the counts of skills and integrations when known, `knowledge` (`off`, `all`, `selected` or `unknown`) and `memory_enabled`. | | `starter_action_picked` | The user chose an option from the TUI starter: `action` is `prompt`, `open` or `done`, with `prompt_index` (its position) for a suggested prompt. Never the prompt's text. | | `workspace_memory_contributed` | A memory block was written back to the workspace's shared memory, including the existing blocks seeded when a project is linked. `block_count` is per write. No memory content. | diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5df4d68dc3..9901020552 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -639,6 +639,17 @@ export namespace Telemetry { status?: number workspace_id?: number } + | { + /** The check of which workspace a project is linked to failed, after its retry, and the saved + * link was served instead. Not an API error: the user never sees it. */ + type: "workspace_link_check_stale" + timestamp: number + session_id: string + /** "GET /datamate-project-bindings/by-remote" or ".../by-path". */ + endpoint: string + status_class: "4xx" | "5xx" | "network" | "timeout" | "response" + status?: number + } | { /** The post-link starter message was served (TUI or extension chat); what the workspace provides. */ type: "starter_shown" diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 4af0971b40..1c2e07599c 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -289,12 +289,15 @@ function workspaceIdIn(body: unknown): number | undefined { return typeof id === "number" && Number.isInteger(id) && id > 0 ? id : undefined } -function reportApiErrorRow(input: { +/** One failed call, as `req` would report it. */ +interface ApiErrorRow { endpoint: string status?: number kind: "4xx" | "5xx" | "network" | "timeout" | "response" workspaceId?: number -}) { +} + +function reportApiErrorRow(input: ApiErrorRow) { const session_id = Telemetry.getContext().sessionId const ws = input.workspaceId !== undefined ? { workspace_id: input.workspaceId } : {} // Only a 401 says the session expired. A 403 is a refusal (a teammate's private workspace), so @@ -426,6 +429,11 @@ async function req( expectedStatuses?: readonly number[] /** false for a call that is not a workspace call (`GET /users/me`): it reports no row at all. */ reportErrors?: boolean + /** Hand a failure's row to the caller instead of reporting it, for a caller that only knows what + * the failure means once it has decided what to do about it (the link check, `lookupBinding`). */ + onErrorRow?: (row: ApiErrorRow) => void + /** Send the request on a new connection rather than a pooled one. */ + freshConnection?: boolean // altimate_change end } = {}, ): Promise { @@ -436,8 +444,10 @@ async function req( const target = `${url}${basePath}${subpath}${qs}` const endpoint = endpointOf(method, basePath, subpath) const bodyWorkspaceId = workspaceIdIn(opts.body) - const reportApiError = (input: Parameters[0]) => { - if (opts.reportErrors !== false) reportApiErrorRow(input) + const reportApiError = (input: ApiErrorRow) => { + if (opts.reportErrors === false) return + if (opts.onErrorRow) opts.onErrorRow(input) + else reportApiErrorRow(input) } const controller = new AbortController() const timeout = setTimeout(() => controller.abort(), timeoutMs) @@ -455,6 +465,8 @@ async function req( }, signal: controller.signal, ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}), + // Bun opens a new connection for a request with keepalive off, instead of reusing a pooled one. + ...(opts.freshConnection ? { keepalive: false } : {}), }) answered = res.status // Keep the AbortController timeout ACTIVE while we read the response body. @@ -624,34 +636,83 @@ async function readBounded(res: Response, target: string): Promise { export { req as altimateRequest } -export namespace WorkspaceApi { - /** Server-authoritative pre-check by git remote. Returns null on 404. */ - export async function getBindingForRemote(remote: string, actAs?: ActAs): Promise { +/** How a link-check lookup that still fails after its retry is reported. `error`: as + * `workspace_api_error`, like any failed call. `stale`: the caller serves the saved link instead, which + * the user never notices, so it is `workspace_link_check_stale`. A 401 is `workspace_auth_expired` in + * both: the sign-in has expired whatever the caller serves. */ +export type LookupFailureReport = "error" | "stale" + +/** A lookup that failed before any answer (a timeout, a dropped or refused connection) or that a gateway + * answered for a server it could not reach. Long-idle processes see the first kind one at a time, which + * reads as a dead pooled connection, so the retry goes out on a new one. */ +function retriesLookup(err: unknown): boolean { + if (!(err instanceof WorkspaceApiError)) return false + if (err.status === undefined) return err.failure === "transport" + return err.status === 502 || err.status === 503 || err.status === 504 +} + +/** The by-remote / by-path lookup, retried once (`retriesLookup`). Only the last attempt's failure is + * reported, once, as `report` says: a first attempt that the retry answers reports nothing. */ +async function lookup( + subpath: "/by-remote" | "/by-path", + query: Record, + actAs: ActAs | undefined, + report: LookupFailureReport, +): Promise { + let rows: ApiErrorRow[] = [] + const attempt = (freshConnection: boolean) => + req("GET", subpath, { + query, + expectedStatuses: [404], + ...(actAs ? { actAs } : {}), + onErrorRow: (row) => rows.push(row), + freshConnection, + }) + try { try { - return await req("GET", "/by-remote", { - query: { repo_remote: remote }, - expectedStatuses: [404], - ...(actAs ? { actAs } : {}), - }) + return await attempt(false) } catch (err) { - if (err instanceof NotFoundError) return null - throw err + if (!retriesLookup(err)) throw err + rows = [] + return await attempt(true) + } + } catch (err) { + if (err instanceof NotFoundError) return null + for (const row of rows) { + if (report === "error" || row.status === 401) reportApiErrorRow(row) + else + Telemetry.track({ + type: "workspace_link_check_stale", + timestamp: Date.now(), + session_id: Telemetry.getContext().sessionId, + endpoint: row.endpoint, + status_class: row.kind, + ...(row.status !== undefined ? { status: row.status } : {}), + }) } + throw err + } +} + +export namespace WorkspaceApi { + /** Server-authoritative pre-check by git remote. Returns null on 404. Retried once on a transport + * failure or a 502/503/504; `report` says how a failure that outlasts the retry is reported. */ + export async function getBindingForRemote( + remote: string, + actAs?: ActAs, + report: LookupFailureReport = "error", + ): Promise { + return lookup("/by-remote", { repo_remote: remote }, actAs, report) } /** Symmetric pre-check by absolute project directory path (for projects - * without a git remote). Returns null on 404. */ - export async function getBindingForPath(projectPath: string, actAs?: ActAs): Promise { - try { - return await req("GET", "/by-path", { - query: { project_path: projectPath }, - expectedStatuses: [404], - ...(actAs ? { actAs } : {}), - }) - } catch (err) { - if (err instanceof NotFoundError) return null - throw err - } + * without a git remote). Returns null on 404. Retried and reported as `getBindingForRemote` is. */ + export async function getBindingForPath( + projectPath: string, + actAs?: ActAs, + report: LookupFailureReport = "error", + ): Promise { + return lookup("/by-path", { project_path: projectPath }, actAs, report) } /** Tries remote first (stronger identity), then path. Returns the first hit @@ -662,13 +723,14 @@ export namespace WorkspaceApi { export async function getBindingForProject( id: ProjectIdentifier, actAs?: ActAs, + report: LookupFailureReport = "error", ): Promise { if (id.repoRemote) { - const hit = await getBindingForRemote(id.repoRemote, actAs) + const hit = await getBindingForRemote(id.repoRemote, actAs, report) if (hit) return { ...hit, matchedBy: "remote" } } if (id.projectPath) { - const hit = await getBindingForPath(id.projectPath, actAs) + const hit = await getBindingForPath(id.projectPath, actAs, report) if (hit) return { ...hit, matchedBy: "path" } } return null diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index fb501c52f9..9dc2878eb1 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -21,7 +21,7 @@ import { Filesystem } from "@/util/filesystem" import { Log } from "@/altimate/util/log" // Type-only: the value side is imported dynamically in resolveBinding to keep // this module's import graph free of the API client at load time. -import type { Binding, ProjectBindingLookup } from "./api-client" +import type { Binding, LookupFailureReport, ProjectBindingLookup } from "./api-client" import type { SeedOutcome } from "./memory-backfill" // altimate_change — the IDE extension's workspace pin; see ./pin.ts import { readPin, readPinLogged, resolveWithinRoot, type ValidPin } from "./pin" @@ -881,7 +881,7 @@ export async function resolveBindingOutcome(directory: string): Promise { const canon = accountScopedKey(directory, key) const missedAt = serverLookupMissed.get(canon) @@ -1164,7 +1167,7 @@ async function lookupBinding( try { const { resolveProjectIdentifier } = await import("./detect") const { WorkspaceApi } = await import("./api-client") - hit = await WorkspaceApi.getBindingForProject(resolveProjectIdentifier(directory)) + hit = await WorkspaceApi.getBindingForProject(resolveProjectIdentifier(directory), undefined, report) } catch (err) { // Unreachable or a 5xx: unknown, not unbound. Deliberately NOT memoized — // the next session should ask again rather than inherit a network blip. diff --git a/packages/opencode/test/altimate/telemetry/workspace-context.test.ts b/packages/opencode/test/altimate/telemetry/workspace-context.test.ts index 85dc8ff8e0..1335893060 100644 --- a/packages/opencode/test/altimate/telemetry/workspace-context.test.ts +++ b/packages/opencode/test/altimate/telemetry/workspace-context.test.ts @@ -153,6 +153,12 @@ describe("workspace id on the telemetry context", () => { { ...base, type: "workspace_switched", to_workspace_id: 2, how: "rebind_remote" }, { ...base, type: "workspace_auth_expired", endpoint: "GET /datamates/", status: 401 }, { ...base, type: "workspace_api_error", endpoint: "GET /datamates/", status_class: "5xx", status: 500 }, + { + ...base, + type: "workspace_link_check_stale", + endpoint: "GET /datamate-project-bindings/by-remote", + status_class: "timeout", + }, { ...base, type: "starter_shown", workspace_id: 1, knowledge: "off" }, { ...base, type: "starter_action_picked", workspace_id: 1, action: "done" }, { ...base, type: "workspace_memory_contributed", workspace_id: 1, block_count: 1 }, @@ -175,7 +181,7 @@ describe("workspace id on the telemetry context", () => { test("the workspace rows are sent when telemetry is on and dropped when it is off", async () => { const names = workspaceRows().map((e) => e.type) - expect(new Set(names).size).toBe(16) // plus tool_call rows, which are not new types + expect(new Set(names).size).toBe(17) // plus tool_call rows, which are not new types await Telemetry.shutdown() await Telemetry.init() diff --git a/packages/opencode/test/altimate/workspace/link-check-stale.test.ts b/packages/opencode/test/altimate/workspace/link-check-stale.test.ts new file mode 100644 index 0000000000..da98fc16b4 --- /dev/null +++ b/packages/opencode/test/altimate/workspace/link-check-stale.test.ts @@ -0,0 +1,99 @@ +// altimate_change - new file +// +// What a failed link check reports, decided where the saved link is or isn't served (`resolveBindingOutcome`). +// The check is retried once inside the lookup (link-telemetry.test.ts covers the retry itself); here every attempt +// fails, and the question is only which row the failure leaves behind. +import { afterAll, afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" +import { mkdirSync, mkdtempSync, rmSync } from "node:fs" +import path from "node:path" +import os from "node:os" + +// Global.Path.state resolves at module load, so the sandbox must exist first. +const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME +const SANDBOX = mkdtempSync(path.join(os.tmpdir(), "link-check-stale-")) +mkdirSync(path.join(SANDBOX, "state"), { recursive: true }) +process.env.XDG_STATE_HOME = path.join(SANDBOX, "state") + +const { AltimateApi } = await import("../../../src/altimate/api/client") +const { Telemetry } = await import("../../../src/altimate/telemetry") +const { recordApprovedBinding, resolveBindingOutcome, expireValidationForTests } = await import( + "../../../src/altimate/workspace/state" +) + +type Creds = Awaited> +type Event = import("../../../src/altimate/telemetry").Telemetry.Event +const originalIsConfigured = AltimateApi.isConfigured +const originalGetCreds = AltimateApi.getCredentials +;(AltimateApi as unknown as { isConfigured: () => Promise }).isConfigured = async () => true +;(AltimateApi as unknown as { getCredentials: () => Promise }).getCredentials = async () => + ({ altimateInstanceName: "acme", altimateUrl: "https://api.example.com", altimateApiKey: "key-a" }) as Creds + +const originalFetch = globalThis.fetch +let lookups = 0 +let events: Event[] +let trackSpy: ReturnType +let projectDir = "" + +beforeEach(() => { + lookups = 0 + events = [] + projectDir = mkdtempSync(path.join(SANDBOX, "proj-")) + trackSpy = spyOn(Telemetry, "track").mockImplementation((e) => { + events.push(e) + }) + // Every link check fails before any answer, retry included. Anything else answers an empty 200. + globalThis.fetch = (async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + if (/\/datamate-project-bindings\/by-(remote|path)/.test(url)) { + lookups++ + throw new TypeError("fetch failed") + } + return new Response(JSON.stringify({}), { status: 200, headers: { "content-type": "application/json" } }) + }) as typeof fetch +}) + +afterEach(() => { + trackSpy.mockRestore() + globalThis.fetch = originalFetch +}) + +afterAll(() => { + ;(AltimateApi as unknown as { isConfigured: typeof originalIsConfigured }).isConfigured = originalIsConfigured + ;(AltimateApi as unknown as { getCredentials: typeof originalGetCreds }).getCredentials = originalGetCreds + if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME + else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME + rmSync(SANDBOX, { recursive: true, force: true }) +}) + +const of = (type: string) => events.filter((e) => e.type === type) as any[] + +describe("a link check that fails after its retry", () => { + test("with a saved link: the link is served as stale and the failure is a fallback, not an API error", async () => { + await recordApprovedBinding( + projectDir, + { datamateId: 42, datamateName: "Growth", repoRemote: null, projectPath: projectDir, linkedAt: Date.now() }, + { seed: false, awaitBackfill: true }, + ) + expireValidationForTests(projectDir) // past the revalidation window, so the server is asked + events = [] + + const outcome = await resolveBindingOutcome(projectDir) + expect(outcome).toEqual(expect.objectContaining({ status: "bound", stale: true })) + if (outcome.status === "bound") expect(outcome.binding.datamateId).toBe(42) + expect(lookups).toBe(2) + expect(of("workspace_api_error")).toHaveLength(0) + expect(of("workspace_link_check_stale")).toEqual([ + expect.objectContaining({ endpoint: "GET /datamate-project-bindings/by-path", status_class: "network" }), + ]) + }) + + test("with no saved link: nothing is served and the failure is still workspace_api_error", async () => { + const outcome = await resolveBindingOutcome(projectDir) + expect(outcome).toEqual({ status: "unknown" }) + expect(lookups).toBe(2) + expect(of("workspace_link_check_stale")).toHaveLength(0) + expect(of("workspace_api_error")).toEqual([ + expect.objectContaining({ endpoint: "GET /datamate-project-bindings/by-path", status_class: "network" }), + ]) + }) +}) diff --git a/packages/opencode/test/altimate/workspace/link-telemetry.test.ts b/packages/opencode/test/altimate/workspace/link-telemetry.test.ts index 9ff3d5ce29..f27042d4e7 100644 --- a/packages/opencode/test/altimate/workspace/link-telemetry.test.ts +++ b/packages/opencode/test/altimate/workspace/link-telemetry.test.ts @@ -33,7 +33,7 @@ type Event = import("../../../src/altimate/telemetry").Telemetry.Event describe("workspace link telemetry", () => { const ORIGINAL_FETCH = globalThis.fetch let events: Event[] - let requests: { method: string; url: string; body: unknown }[] + let requests: { method: string; url: string; body: unknown; keepalive?: boolean }[] let replies: Reply[] let trackSpy: ReturnType @@ -54,6 +54,7 @@ describe("workspace link telemetry", () => { method: init?.method ?? "GET", url: String(input), body: init?.body ? JSON.parse(String(init.body)) : undefined, + keepalive: init?.keepalive, }) const r = replies.shift() ?? { status: 200, body: binding(1) } if ("throw" in r) throw r.throw @@ -391,6 +392,76 @@ describe("workspace link telemetry", () => { expect(of("workspace_linked")[0]).toEqual(expect.objectContaining({ workspace_id: 42, how: "rebind_path" })) }) + describe("the link check (by-remote, by-path) retries once", () => { + const paths = () => requests.map((r) => new URL(r.url).pathname) + const dropped = (): Reply => ({ throw: new TypeError("fetch failed") }) + + test("a check that times out once and then answers returns the link and reports nothing", async () => { + replies = [{ hang: true }, { status: 200, body: binding(42) }] + const hit = await WorkspaceApi.getBindingForRemote("git@x:y.git") + expect(hit?.binding.datamate_id).toBe(42) + expect(events).toEqual([]) + // The retry goes out on a new connection; the first attempt used the pool as before. + expect(requests.map((r) => r.keepalive)).toEqual([undefined, false]) + }, 40_000) + + test("a dropped connection or a 502, 503 or 504 is retried, and an answer to the retry reports nothing", async () => { + for (const first of [dropped(), { status: 502 }, { status: 503 }, { status: 504 }] as Reply[]) { + events = [] + requests = [] + replies = [first, { status: 200, body: binding(7) }] + expect((await WorkspaceApi.getBindingForPath("/p"))?.binding.datamate_id).toBe(7) + expect(paths()).toEqual(["/datamate-project-bindings/by-path", "/datamate-project-bindings/by-path"]) + expect(events).toEqual([]) + } + }) + + test("a check that fails twice reports one workspace_api_error, for the last attempt", async () => { + replies = [{ status: 503 }, dropped()] + await expect(WorkspaceApi.getBindingForRemote("git@x:y.git")).rejects.toBeInstanceOf(WorkspaceApiError) + expect(requests).toHaveLength(2) + expect(of("workspace_api_error")).toEqual([ + expect.objectContaining({ endpoint: "GET /datamate-project-bindings/by-remote", status_class: "network" }), + ]) + expect(of("workspace_api_error")).toHaveLength(1) + expect(of("workspace_link_check_stale")).toHaveLength(0) + }) + + test("a 404 is 'not linked' with no retry, and a 403, 500 or 401 is not retried", async () => { + replies = [{ status: 404, body: { detail: "no binding" } }] + await expect(WorkspaceApi.getBindingForRemote("git@x:y.git")).resolves.toBeNull() + expect(requests).toHaveLength(1) + expect(events).toEqual([]) + + for (const [status, type] of [ + [403, "workspace_api_error"], + [500, "workspace_api_error"], + [401, "workspace_auth_expired"], + ] as const) { + events = [] + requests = [] + replies = [{ status, body: { detail: "no" } }, { status: 200, body: binding(1) }] + await expect(WorkspaceApi.getBindingForPath("/p")).rejects.toThrow() + expect(requests).toHaveLength(1) + expect(events.map((e) => e.type)).toEqual([type]) + } + }) + + test("reported as stale, a failure that outlasts the retry is workspace_link_check_stale, and a 401 is still expired auth", async () => { + replies = [dropped(), { status: 504 }] + await expect(WorkspaceApi.getBindingForProject({ repoRemote: "git@x:y.git" }, undefined, "stale")).rejects.toThrow() + expect(of("workspace_api_error")).toHaveLength(0) + expect(of("workspace_link_check_stale")).toEqual([ + expect.objectContaining({ endpoint: "GET /datamate-project-bindings/by-remote", status_class: "5xx", status: 504 }), + ]) + + events = [] + replies = [{ status: 401, body: { detail: "expired" } }] + await expect(WorkspaceApi.getBindingForPath("/p", undefined, "stale")).rejects.toThrow() + expect(events.map((e) => e.type)).toEqual(["workspace_auth_expired"]) + }) + }) + test("linkFailureReason classifies every error the client throws", () => { expect(linkFailureReason(new ForbiddenError("f"))).toBe("auth") expect(linkFailureReason(new WorkspaceApiError("unauthorized", 401))).toBe("auth") From 09a822b5fb1d2ea8d77ded801321d4fddbe14917 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 18:26:02 +0800 Subject: [PATCH 2/3] fix: link check retries as one account, and after a stalled 2xx body - A lookup's attempts, and a project's two lookups, run as the credential read first. - A timeout while a 2xx body is arriving is retried like one before any answer. - One failure row per lookup; the docs say the retry applies only when eligible. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- docs/docs/reference/telemetry.md | 4 +- .../opencode/src/altimate/telemetry/index.ts | 4 +- .../src/altimate/workspace/api-client.ts | 69 ++++++++++++------- .../altimate/workspace/link-telemetry.test.ts | 43 +++++++++++- 4 files changed, 89 insertions(+), 31 deletions(-) diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index ec369a6a5c..d09763330f 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -102,8 +102,8 @@ These events describe projects linked to an Altimate workspace. A workspace is i | `workspace_unlinked` | A project was unlinked, with the workspace id when the CLI knew it. | | `workspace_switched` | A linked project was moved to another workspace. `how` is `rebind_remote` or `rebind_path`. | | `workspace_auth_expired` | A workspace call was answered 401: the sign-in has expired. Carries `endpoint` and `status`. | -| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. The link lookups (`by-remote`, `by-path`) are retried once after a timeout, a network error or a 502, 503 or 504, and only a failure that outlasts the retry is reported. | -| `workspace_link_check_stale` | The check of which workspace a project is linked to failed after its retry, and the saved link was used instead. Carries `endpoint`, `status_class` and `status` as `workspace_api_error` does. Reported in place of `workspace_api_error` because the user never sees it; a 401 is still `workspace_auth_expired`. | +| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. The link lookups (`by-remote`, `by-path`) are retried once after a timeout, a network error or a 502, 503 or 504. Only the last attempt's failure is reported. | +| `workspace_link_check_stale` | The check of which workspace a project is linked to failed, after one retry when the failure allows one (see above), and the saved link was used instead. A 403 or 500 isn't retried and is reported here too. Carries `endpoint`, `status_class` and `status` as `workspace_api_error` does. Reported in place of `workspace_api_error` because the user never sees it; a 401 is still `workspace_auth_expired`. | | `starter_shown` | The "what this workspace provides" starter was served after a link: to the TUI, to the IDE extension's chat, or printed by `altimate-code link`. It counts the starter being served, so a client that closes before rendering it is still counted. Contains the counts of skills and integrations when known, `knowledge` (`off`, `all`, `selected` or `unknown`) and `memory_enabled`. | | `starter_action_picked` | The user chose an option from the TUI starter: `action` is `prompt`, `open` or `done`, with `prompt_index` (its position) for a suggested prompt. Never the prompt's text. | | `workspace_memory_contributed` | A memory block was written back to the workspace's shared memory, including the existing blocks seeded when a project is linked. `block_count` is per write. No memory content. | diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 9901020552..2be4bde52f 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -640,8 +640,8 @@ export namespace Telemetry { workspace_id?: number } | { - /** The check of which workspace a project is linked to failed, after its retry, and the saved - * link was served instead. Not an API error: the user never sees it. */ + /** The check of which workspace a project is linked to failed, after one retry when the failure + * was eligible for one, and the saved link was served instead. Not an API error: the user never sees it. */ type: "workspace_link_check_stale" timestamp: number session_id: string diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 1c2e07599c..0f00204e93 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -213,6 +213,8 @@ export class WorkspaceApiError extends Error { public readonly failure: "transport" | "response" = status === undefined ? "transport" : "response", // altimate_change — workspace rules: a coded `detail` object, read by `rules/api.ts` `classify` public readonly detail?: Record, + /** Our own timeout fired, before an answer or while its body was still arriving. */ + public readonly timedOut = false, ) { super(msg) this.name = "WorkspaceApiError" @@ -509,7 +511,13 @@ async function req( }) // The answer's status rides on the error too, so a link failure after an answer is not // classified as a network failure. - throw new WorkspaceApiError(`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`, answered) + throw new WorkspaceApiError( + `Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`, + answered, + undefined, + undefined, + true, + ) } // The server answered and the body failed afterwards (readBounded's cap, a cut stream): // classify by the status it answered with, so an oversized 500 is still a 5xx row; only a @@ -642,54 +650,60 @@ export { req as altimateRequest } * both: the sign-in has expired whatever the caller serves. */ export type LookupFailureReport = "error" | "stale" -/** A lookup that failed before any answer (a timeout, a dropped or refused connection) or that a gateway - * answered for a server it could not reach. Long-idle processes see the first kind one at a time, which - * reads as a dead pooled connection, so the retry goes out on a new one. */ +/** A lookup that failed before any answer (a timeout, a dropped or refused connection), that timed out + * while a 2xx body was still arriving, or that a gateway answered for a server it could not reach. + * Long-idle processes see the first kind one at a time, which reads as a dead pooled connection, so the + * retry goes out on a new one. */ function retriesLookup(err: unknown): boolean { if (!(err instanceof WorkspaceApiError)) return false if (err.status === undefined) return err.failure === "transport" + if (err.timedOut && err.status < 300) return true return err.status === 502 || err.status === 503 || err.status === 504 } -/** The by-remote / by-path lookup, retried once (`retriesLookup`). Only the last attempt's failure is - * reported, once, as `report` says: a first attempt that the retry answers reports nothing. */ +/** The by-remote / by-path lookup, retried once (`retriesLookup`). Both attempts run as one credential, + * read once here unless the caller passed one, so an account switch between them can't answer for another + * account. Only the last attempt's failure is reported, once, as `report` says: a first attempt that the + * retry answers reports nothing. */ async function lookup( subpath: "/by-remote" | "/by-path", query: Record, actAs: ActAs | undefined, report: LookupFailureReport, ): Promise { - let rows: ApiErrorRow[] = [] - const attempt = (freshConnection: boolean) => - req("GET", subpath, { + const account = actAs ?? (await creds()) + let failure: ApiErrorRow | undefined + const attempt = (freshConnection: boolean) => { + failure = undefined + return req("GET", subpath, { query, expectedStatuses: [404], - ...(actAs ? { actAs } : {}), - onErrorRow: (row) => rows.push(row), + actAs: account, + onErrorRow: (row) => { + failure = row + }, freshConnection, }) + } try { try { return await attempt(false) } catch (err) { if (!retriesLookup(err)) throw err - rows = [] return await attempt(true) } } catch (err) { if (err instanceof NotFoundError) return null - for (const row of rows) { - if (report === "error" || row.status === 401) reportApiErrorRow(row) - else - Telemetry.track({ - type: "workspace_link_check_stale", - timestamp: Date.now(), - session_id: Telemetry.getContext().sessionId, - endpoint: row.endpoint, - status_class: row.kind, - ...(row.status !== undefined ? { status: row.status } : {}), - }) - } + if (failure && (report === "error" || failure.status === 401)) reportApiErrorRow(failure) + else if (failure) + Telemetry.track({ + type: "workspace_link_check_stale", + timestamp: Date.now(), + session_id: Telemetry.getContext().sessionId, + endpoint: failure.endpoint, + status_class: failure.kind, + ...(failure.status !== undefined ? { status: failure.status } : {}), + }) throw err } } @@ -725,12 +739,15 @@ export namespace WorkspaceApi { actAs?: ActAs, report: LookupFailureReport = "error", ): Promise { + if (!id.repoRemote && !id.projectPath) return null + // One credential for both lookups and their retries. + const account = actAs ?? (await creds()) if (id.repoRemote) { - const hit = await getBindingForRemote(id.repoRemote, actAs, report) + const hit = await getBindingForRemote(id.repoRemote, account, report) if (hit) return { ...hit, matchedBy: "remote" } } if (id.projectPath) { - const hit = await getBindingForPath(id.projectPath, actAs, report) + const hit = await getBindingForPath(id.projectPath, account, report) if (hit) return { ...hit, matchedBy: "path" } } return null diff --git a/packages/opencode/test/altimate/workspace/link-telemetry.test.ts b/packages/opencode/test/altimate/workspace/link-telemetry.test.ts index f27042d4e7..df91d0b9ac 100644 --- a/packages/opencode/test/altimate/workspace/link-telemetry.test.ts +++ b/packages/opencode/test/altimate/workspace/link-telemetry.test.ts @@ -26,6 +26,7 @@ const { ConflictError, } = await import("../../../src/altimate/workspace/api-client") const { Telemetry } = await import("../../../src/altimate/telemetry") +const { AltimateApi } = await import("../../../src/altimate/api/client") type Reply = { status: number; body?: unknown } | { throw: Error } | { hang: true } type Event = import("../../../src/altimate/telemetry").Telemetry.Event @@ -33,7 +34,7 @@ type Event = import("../../../src/altimate/telemetry").Telemetry.Event describe("workspace link telemetry", () => { const ORIGINAL_FETCH = globalThis.fetch let events: Event[] - let requests: { method: string; url: string; body: unknown; keepalive?: boolean }[] + let requests: { method: string; url: string; body: unknown; keepalive?: boolean; auth?: string }[] let replies: Reply[] let trackSpy: ReturnType @@ -55,6 +56,7 @@ describe("workspace link telemetry", () => { url: String(input), body: init?.body ? JSON.parse(String(init.body)) : undefined, keepalive: init?.keepalive, + auth: (init?.headers as Record | undefined)?.Authorization, }) const r = replies.shift() ?? { status: 200, body: binding(1) } if ("throw" in r) throw r.throw @@ -405,6 +407,45 @@ describe("workspace link telemetry", () => { expect(requests.map((r) => r.keepalive)).toEqual([undefined, false]) }, 40_000) + test("a 2xx whose body stalls until the timeout is retried", async () => { + let call = 0 + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + requests.push({ method: init?.method ?? "GET", url: String(input), body: undefined, keepalive: init?.keepalive }) + if (call++ > 0) return new Response(JSON.stringify(binding(9)), { status: 200 }) + return new Response( + new ReadableStream({ + start(controller) { + init?.signal?.addEventListener("abort", () => + controller.error(Object.assign(new Error("aborted"), { name: "AbortError" })), + ) + }, + }), + { status: 200 }, + ) + }) as typeof globalThis.fetch + expect((await WorkspaceApi.getBindingForRemote("git@x:y.git"))?.binding.datamate_id).toBe(9) + expect(requests.map((r) => r.keepalive)).toEqual([undefined, false]) + expect(events).toEqual([]) + }, 40_000) + + test("every attempt of a lookup, and both lookups of a project, run as the account read first", async () => { + const real = await AltimateApi.getCredentials() + let reads = 0 + const credsSpy = spyOn(AltimateApi, "getCredentials").mockImplementation(async () => ({ + ...real, + altimateApiKey: reads++ === 0 ? "key-a" : "key-b", + })) + try { + replies = [dropped(), { status: 404, body: { detail: "no binding" } }, dropped(), { status: 200, body: binding(3) }] + const hit = await WorkspaceApi.getBindingForProject({ repoRemote: "git@x:y.git", projectPath: "/p" }) + expect(hit?.matchedBy).toBe("path") + expect(requests.map((r) => r.auth)).toEqual(Array(4).fill("Bearer key-a")) + expect(reads).toBe(1) + } finally { + credsSpy.mockRestore() + } + }) + test("a dropped connection or a 502, 503 or 504 is retried, and an answer to the retry reports nothing", async () => { for (const first of [dropped(), { status: 502 }, { status: 503 }, { status: 504 }] as Reply[]) { events = [] From 249c4150035945bbadb7e6d4f3b40fe6cec53c0a Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 18:31:21 +0800 Subject: [PATCH 3/3] docs: the lookup's doc comment names every retried failure Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvsr1G2qqFbMCyPZg3G --- packages/opencode/src/altimate/workspace/api-client.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 0f00204e93..873eafa31b 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -710,7 +710,8 @@ async function lookup( export namespace WorkspaceApi { /** Server-authoritative pre-check by git remote. Returns null on 404. Retried once on a transport - * failure or a 502/503/504; `report` says how a failure that outlasts the retry is reported. */ + * failure, a timeout while a 2xx body is arriving, or a 502/503/504 (`retriesLookup`); `report` says + * how a failure that outlasts the retry is reported. */ export async function getBindingForRemote( remote: string, actAs?: ActAs,