Skip to content

Commit d2f924a

Browse files
fix(workspace): arm the abort through the body, read config before the status gate, cancel the losing timer
Codex round 12. Three findings, all verified, all follow-ups on last round's fixes. **The abort now stays armed until the response body is read.** fetch resolves on headers, so clearing the timer there left a server that sends headers and then stalls mid-body hanging indefinitely, holding its socket. The bound added last round covered the wrong half of the request. Two sibling functions in the same client share this shape. They are pre-existing and untouched here rather than swept in silently; noted for a follow-up. **Config is read before the MCP status gate, not after.** MCP.status() reads the same cached config as everything else, so an entry added directly by an IDE or a user after the cache was warmed is absent from status. The entry check then never ran and the managed entry was persisted straight over the externally authored one. Reading the entry first is what refreshes that cache, so the status gate becomes trustworthy rather than merely fresh-looking. That is the fourth route by which this cache has produced a wrong answer, and the first where the stale read was inside MCP rather than here — the freshConfig accessor fixed this module's own reads but could not fix a gate that consults the cache independently. **The losing allowlist timer is cancelled.** Racing does not cancel the loser, so a lookup that succeeded in well under the bound still fired its timeout later and warned that it had timed out — on every normal attach and reuse. A fix whose only symptom was misleading logs, which is the kind that survives longest. 1 test pinning the ordering: the config read must precede the status gate, and it fails with the two swapped. The timer cancellation is verified by inspection — its only observable effect is a log line, and manufacturing a seam to assert on a log would be worse than the bug.
1 parent 4e3e28a commit d2f924a

3 files changed

Lines changed: 74 additions & 27 deletions

File tree

‎packages/opencode/src/altimate/api/client.ts‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -238,20 +238,27 @@ export namespace AltimateApi {
238238
const controller = new AbortController()
239239
const timeout = setTimeout(() => controller.abort(), 15_000)
240240
// altimate_change end
241-
const res = await fetch(url, {
242-
signal: controller.signal,
243-
method,
244-
headers: {
245-
"Content-Type": "application/json",
246-
Authorization: `Bearer ${creds.altimateApiKey}`,
247-
"x-tenant": creds.altimateInstanceName,
248-
},
249-
...(body ? { body: JSON.stringify(body) } : {}),
250-
}).finally(() => clearTimeout(timeout))
251-
if (!res.ok) {
252-
throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`)
241+
try {
242+
const res = await fetch(url, {
243+
signal: controller.signal,
244+
method,
245+
headers: {
246+
"Content-Type": "application/json",
247+
Authorization: `Bearer ${creds.altimateApiKey}`,
248+
"x-tenant": creds.altimateInstanceName,
249+
},
250+
...(body ? { body: JSON.stringify(body) } : {}),
251+
})
252+
if (!res.ok) {
253+
throw new Error(`API ${method} ${endpoint} failed with status ${res.status}`)
254+
}
255+
// The abort stays armed until the BODY is read. `fetch` resolves on
256+
// headers, so clearing it here would leave a server that sends headers and
257+
// then stalls mid-body hanging indefinitely — with the socket held open.
258+
return await res.json()
259+
} finally {
260+
clearTimeout(timeout)
253261
}
254-
return res.json()
255262
}
256263

257264
export async function listDatamates() {

‎packages/opencode/src/altimate/workspace/engine-sync.ts‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -423,19 +423,26 @@ async function announceToolsChanged(): Promise<void> {
423423
* signal), so a stalled server releases its socket instead of accumulating
424424
* pending fetches across repair retries. */
425425
async function declaredBounded(workspaceId: string): Promise<Declared | null> {
426-
return Promise.race([
427-
declared(workspaceId),
428-
new Promise<null>((resolve) => {
429-
const timer = setTimeout(() => {
430-
log.warn("workspace allowlist lookup timed out; continuing without the declared-vs-delivered report", {
431-
workspaceId,
432-
timeoutMs: DECLARED_TIMEOUT_MS,
433-
})
434-
resolve(null)
435-
}, DECLARED_TIMEOUT_MS)
436-
timer.unref?.()
437-
}),
438-
])
426+
let timer: ReturnType<typeof setTimeout> | undefined
427+
try {
428+
return await Promise.race([
429+
declared(workspaceId),
430+
new Promise<null>((resolve) => {
431+
timer = setTimeout(() => {
432+
log.warn("workspace allowlist lookup timed out; continuing without the declared-vs-delivered report", {
433+
workspaceId,
434+
timeoutMs: DECLARED_TIMEOUT_MS,
435+
})
436+
resolve(null)
437+
}, DECLARED_TIMEOUT_MS)
438+
timer.unref?.()
439+
}),
440+
])
441+
} finally {
442+
// Racing does not cancel the loser: left running, the timer fires later and
443+
// warns about a lookup that had already succeeded, on every normal attach.
444+
if (timer) clearTimeout(timer)
445+
}
439446
}
440447

441448
async function notify(toast: Toast): Promise<void> {
@@ -566,10 +573,15 @@ async function run(): Promise<Outcome> {
566573
log.warn("could not detach the rejected engine entry", { err: String(err), ...why })
567574
})
568575
}
576+
// Read the entry BEFORE asking for status. `existingEntry` refreshes the config
577+
// cache and `MCP.status()` reads that same cache — so an entry an IDE or user
578+
// added after the cache was warmed is missing from status entirely, `existing`
579+
// is undefined, rule 1 never runs, and we persist our managed entry straight
580+
// over theirs. Refreshing first is what makes the status gate trustworthy.
581+
const entry = await existingEntry(DATAMATE_KEY)
569582
const before = await client.status()
570583
const existing = before[DATAMATE_KEY]
571584
if (existing) {
572-
const entry = await existingEntry(DATAMATE_KEY)
573585
let connected = existing.status === "connected"
574586

575587
if (!connected) {

‎packages/opencode/test/altimate/workspace/engine-sync.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,3 +1207,31 @@ describe("ensure — round 11", () => {
12071207
expect(h.added).toHaveLength(0)
12081208
})
12091209
})
1210+
1211+
describe("ensure — round 12", () => {
1212+
test("an externally added entry is seen even when MCP status has not caught up", async () => {
1213+
// MCP.status() reads the same cached config as everything else, so an entry
1214+
// an IDE adds after the cache is warm is absent from status. Without a fresh
1215+
// read first, rule 1 never runs and we persist over the user's entry.
1216+
const h = install({
1217+
statuses: [{}, { datamate: { status: "connected" } }], // status omits it
1218+
existing: { type: "local", command: ["datamate", "start-stdio", "--datamate", "42"] }, // but config has it
1219+
tools: { datamate_dbt_build_model: 1 },
1220+
})
1221+
let readBeforeStatus = false
1222+
let statusCalls = 0
1223+
const realStatus = syncInternals.mcp!.status
1224+
syncInternals.mcp!.status = async () => {
1225+
statusCalls += 1
1226+
return realStatus()
1227+
}
1228+
syncInternals.existingEntry = async () => {
1229+
if (statusCalls === 0) readBeforeStatus = true
1230+
return { type: "local", command: ["datamate", "start-stdio", "--datamate", "42"] }
1231+
}
1232+
await ensure("s1")
1233+
// The ordering is the fix: the config refresh must precede the status gate.
1234+
expect(readBeforeStatus).toBe(true)
1235+
expect(h).toBeDefined()
1236+
})
1237+
})

0 commit comments

Comments
 (0)