Skip to content

Commit 18ada3e

Browse files
fix(workspace): revalidate the binding before mutating MCP state
Codex round 6. run() snapshots the binding at the top, but reaching a mutation costs seconds: a status call, one or two process spawns for --version, and the workspace allowlist over the network. A re-link inside that window left the attach acting for a workspace the project had already left. Per-project serialization did not help, and made one case worse. It orders the writes, so a stale attach installs FIRST and the replacement queues behind it; the waiting session's bounded first-turn wait is spent in that queue, so its tool list could be resolved while the stale workspace's engine was the one attached. Everything that mutates MCP state now revalidates the binding immediately before doing so and abandons instead: the spawn returns `superseded` without persisting or adding, and a teardown decided for a workspace we have left is skipped rather than executed. The check is a local cache read, cheap enough to repeat before each mutation. `superseded` is repairable, so the next turn attaches the workspace the project actually holds. Residual, deliberately not addressed here: a superseded attach still occupies the project queue until it reaches its guard, so a session waiting behind it can still spend part of its wait on work that will be discarded. Cancelling in-flight attaches rather than letting them reach the guard is a larger change. 2 tests: a re-link during the slow phase abandons without installing the old workspace, and an unchanged binding still attaches. The first fails with the guard reverted.
1 parent a719eb5 commit 18ada3e

2 files changed

Lines changed: 68 additions & 1 deletion

File tree

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

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export type Outcome =
9898
| { kind: "engine-too-old"; found: string }
9999
| { kind: "connect-failed"; error: string }
100100
| { kind: "entry-disabled" }
101+
| { kind: "superseded" }
101102

102103
export type LocalMcpConfig = { type: "local"; command: string[]; enabled: boolean }
103104

@@ -419,6 +420,23 @@ async function run(): Promise<Outcome> {
419420
let replaced: string | undefined
420421
let replacedNote = ""
421422

423+
/** Is this attach still the one this project wants?
424+
*
425+
* The binding is snapshotted at the top of `run()`, but reaching a mutation
426+
* costs seconds — a status call, one or two process spawns for `--version`,
427+
* and the workspace allowlist over the network. A re-link inside that window
428+
* leaves this attach acting for a workspace the project has already left, and
429+
* per-project serialization does not help: it orders the writes, so the stale
430+
* attach simply installs FIRST and the replacement queues behind it. Anything
431+
* that mutates MCP state re-checks here and abandons instead.
432+
*
433+
* Cheap enough to call before every mutation — the binding is a local cache
434+
* read, not a network one. */
435+
const stillCurrent = async (): Promise<boolean> => {
436+
const now = await resolveBinding().catch(() => null)
437+
return !!now && String(now.datamateId) === workspaceId
438+
}
439+
422440
/** Stop serving an entry we have judged untrustworthy for this workspace.
423441
*
424442
* Runtime-only (`MCP.remove`): closes the client and drops it from the tool
@@ -433,6 +451,10 @@ async function run(): Promise<Outcome> {
433451
* tools we just decided it must not have. It also closes the client `MCP.add`
434452
* would otherwise overwrite without closing, which orphans a second engine. */
435453
const detachRejected = async (why: Record<string, unknown>): Promise<void> => {
454+
if (!(await stillCurrent())) {
455+
log.info("skipping teardown; the binding changed while this attach was deciding", { workspaceId, ...why })
456+
return
457+
}
436458
await client.remove(DATAMATE_KEY).catch((err) => {
437459
log.warn("could not detach the rejected engine entry", { err: String(err), ...why })
438460
})
@@ -620,6 +642,12 @@ async function run(): Promise<Outcome> {
620642
command: [ENGINE_BINARY, "start-stdio", "--datamate", workspaceId],
621643
enabled: true,
622644
}
645+
if (!(await stillCurrent())) {
646+
// Re-linked while we were probing. Installing now would attach the workspace
647+
// this session has already left, and would win by arriving first.
648+
log.info("abandoning attach; the binding changed before the engine was installed", { workspaceId })
649+
return { kind: "superseded" }
650+
}
623651
await persist(DATAMATE_KEY, cfg)
624652
await client.add(DATAMATE_KEY, cfg)
625653

@@ -674,7 +702,13 @@ type SessionAttach = { key?: string; task: Promise<Outcome>; waitTimedOut?: bool
674702
* it, fix a broken entry. Caching these for the life of the session means the
675703
* hint we just printed ("install it with …") can be followed and nothing
676704
* happens until a new session — so they are re-probed on the next turn. */
677-
const REPAIRABLE = new Set<Outcome["kind"]>(["engine-missing", "engine-too-old", "connect-failed", "entry-disabled"])
705+
const REPAIRABLE = new Set<Outcome["kind"]>([
706+
"engine-missing",
707+
"engine-too-old",
708+
"connect-failed",
709+
"entry-disabled",
710+
"superseded",
711+
])
678712

679713
function isRepairable(outcome: Outcome | undefined): boolean {
680714
return !!outcome && REPAIRABLE.has(outcome.kind)

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -918,3 +918,36 @@ describe("ensure — round 5", () => {
918918
expect(trackedSessionsForTests()).toBeLessThanOrEqual(MAX_TRACKED_SESSIONS)
919919
})
920920
})
921+
922+
describe("ensure — round 6: a stale binding must not be installed", () => {
923+
test("a re-link DURING an attach abandons it instead of installing the old workspace", async () => {
924+
// run() snapshots the binding, then spends seconds in status, version and
925+
// API work before persisting. A re-link inside that window used to install
926+
// the workspace the session had already left.
927+
let current: CachedBinding | null = binding // 42
928+
const h = install({
929+
statuses: [{}, { datamate: { status: "connected" } }],
930+
tools: { datamate_dbt_build_model: 1 },
931+
})
932+
syncInternals.resolveBinding = async () => current
933+
// The re-link lands while the attach is in its slow phase.
934+
syncInternals.declared = async () => {
935+
current = { ...binding, datamateId: 99, datamateName: "other" } as CachedBinding
936+
return { keys: ["dbt_build_model", "dbt_compile_model"], extensionKeys: [] }
937+
}
938+
939+
expect(await ensure("s1")).toEqual({ kind: "superseded" })
940+
// The decisive assertion: workspace 42's engine is never installed.
941+
expect(h.added).toHaveLength(0)
942+
expect(h.persisted).toHaveLength(0)
943+
})
944+
945+
test("an unchanged binding still attaches normally", async () => {
946+
const h = install({
947+
statuses: [{}, { datamate: { status: "connected" } }],
948+
tools: { datamate_dbt_build_model: 1, datamate_dbt_compile_model: 1 },
949+
})
950+
expect(await ensure("s1")).toMatchObject({ kind: "attached" })
951+
expect(h.added[0].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "42"])
952+
})
953+
})

0 commit comments

Comments
 (0)