Skip to content

Commit a719eb5

Browse files
fix(workspace): stop inferring user intent and ownership from MCP state
Codex round 5 on a84e7c3. Three findings, all verified; each new test was confirmed to fail with its fix reverted. **A removed entry is no longer mistaken for a user disable.** `MCP.remove` deletes the runtime status, and `MCP.status()` reports any *configured* entry with no status as `disabled`. So every rejection teardown made the following turn look like an explicit user disable, and the session returned `entry-disabled` for good — silently undoing the repairable-retry fix from the previous round for its most likely path: reject an unattributable engine, fail to replace it, install the engine, and never recover. Intent is now read from the config's actual `enabled: false`, which is the only place a user expresses it; the synthesized status is treated as the absence of information it is. **An unbound project no longer tears down an entry it cannot prove it owns.** Ownership was inferred from argv shape, but argv carries no provenance: a hand-authored `datamate start-stdio --datamate <id>` is byte-identical to what this feature writes, so the teardown took the user's own server offline on every first prompt — the opposite of the guarantee its comment claimed. This module's thesis is that you do not act on what you cannot attribute, and that has to apply to the module itself, so it now reports and leaves the entry alone. Doing better needs an explicit ownership marker written at persist time; that is a separate change and is recorded in the PR body rather than guessed at here. **The session and attach-chain maps are bounded.** They are module-level and a long-running `serve` process creates sessions indefinitely, so they grew for the life of the process with only a test-only reset to clear them. Sessions are now capped with oldest-first eviction; an evicted session simply re-attaches on its next turn, which is correct if not free. Storing this in `InstanceState` would be the thorough fix and is noted for later. 4 further tests: a removed entry recovering through install on a later turn, a genuinely disabled entry still respected, a pinned entry left alone in an unbound project, and the session map staying within its cap. The round-2 test that asserted the unbound teardown is reversed deliberately, and the round-4 disabled test now sets `enabled: false` rather than relying on the synthesized status.
1 parent a84e7c3 commit a719eb5

2 files changed

Lines changed: 115 additions & 24 deletions

File tree

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

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ export type LocalMcpConfig = { type: "local"; command: string[]; enabled: boolea
105105
* `command: string[]` argv, or the `{ command, args }` split an IDE writes and
106106
* `datamate-transport` normalises. Read defensively — this is merged config
107107
* written by other clients. */
108-
export type ExistingEntry = { type?: string; url?: string; command?: string[] | string; args?: string[] }
108+
export type ExistingEntry = { type?: string; url?: string; command?: string[] | string; args?: string[]; enabled?: boolean }
109109

110110
type Toast = { title: string; message: string; variant: "info" | "success" | "warning" | "error" }
111111

@@ -322,14 +322,6 @@ export function pinnedWorkspace(entry: ExistingEntry | null): string | null {
322322
return null
323323
}
324324

325-
/** Did WE write this entry? Only an entry matching the exact command we persist
326-
* is ours to tear down; an IDE-written or hand-edited entry belongs to the user
327-
* and is left alone even when it is the wrong one for this project. */
328-
function isManagedEntry(entry: ExistingEntry | null): boolean {
329-
const argv = commandArgv(entry)
330-
return argv.length === 4 && argv[0] === ENGINE_BINARY && argv[1] === "start-stdio" && argv[2] === PIN_FLAG && !!argv[3]
331-
}
332-
333325
/** Short, printable identity of an entry, for saying what was replaced. */
334326
function describeEntry(entry: ExistingEntry | null): string {
335327
if (isUrlEntry(entry)) return entry.url
@@ -388,18 +380,23 @@ async function run(): Promise<Outcome> {
388380

389381
const binding = await resolveBinding()
390382
if (!binding) {
391-
// An entry WE persisted for a binding that no longer exists is still started
392-
// by MCP bootstrap on every launch, and would serve the OLD workspace's tools
393-
// in a project that is no longer linked to it. Detach it — runtime only, the
394-
// config entry is left in place — so an unlinked project does not silently
395-
// keep another workspace's tools. Only our own managed entry qualifies.
383+
// An entry left over from a binding that no longer exists still gets started
384+
// by MCP bootstrap and can serve the OLD workspace's tools here. Tempting to
385+
// tear it down — but we cannot prove we wrote it. argv shape is not
386+
// provenance: a hand-authored `datamate start-stdio --datamate <id>` is
387+
// byte-identical to ours, and removing it would take the user's own server
388+
// offline on every first prompt. This module's whole thesis is that you do
389+
// not act on something you cannot attribute, so it applies to itself here:
390+
// report it and leave it alone. Attributing this properly needs an explicit
391+
// ownership marker written at persist time, which is a separate change.
396392
const present = (await client.status())[DATAMATE_KEY]
397393
if (present) {
398394
const stale = await existingEntry(DATAMATE_KEY)
399-
if (isManagedEntry(stale)) {
400-
log.info("detaching a managed engine entry in an unbound project", { entry: describeEntry(stale) })
401-
await client.remove(DATAMATE_KEY).catch((err) => {
402-
log.warn("could not detach the managed engine entry", { err: String(err) })
395+
const pin = pinnedWorkspace(stale)
396+
if (pin) {
397+
log.info("unbound project has an engine entry pinned to a workspace; leaving it alone", {
398+
pinnedTo: pin,
399+
entry: describeEntry(stale),
403400
})
404401
}
405402
}
@@ -447,7 +444,11 @@ async function run(): Promise<Outcome> {
447444
let connected = existing.status === "connected"
448445

449446
if (!connected) {
450-
if (existing.status === "disabled") {
447+
// `MCP.status()` synthesizes "disabled" for any CONFIGURED entry that has
448+
// no runtime status, and `MCP.remove` deletes the status — so every
449+
// rejection teardown makes the next turn look like a user disable. Read the
450+
// config's actual flag instead; only that is user intent.
451+
if (existing.status === "disabled" && entry?.enabled === false) {
451452
// The user turned this entry off deliberately. Do NOT call `MCP.connect`
452453
// to "retry" it: that persists `enabled: true` into whichever config
453454
// owns the entry, so for a global `datamate` the first prompt in any
@@ -679,8 +680,33 @@ function isRepairable(outcome: Outcome | undefined): boolean {
679680
return !!outcome && REPAIRABLE.has(outcome.kind)
680681
}
681682

683+
/** Cap on remembered sessions.
684+
*
685+
* These maps are module-level and a long-running `serve` process creates
686+
* sessions indefinitely, so without a bound they grow for the life of the
687+
* process. Evicting the oldest is safe: a session whose memo is dropped simply
688+
* re-attaches on its next turn, which is correct, just not free. */
689+
export const MAX_TRACKED_SESSIONS = 256
690+
682691
const sessions = new Map<string, SessionAttach>()
683692

693+
/** Insertion-ordered eviction — `Map` preserves insertion order, so the first
694+
* key is the least recently STARTED attach. */
695+
function rememberSession(sessionID: string, entry: SessionAttach): void {
696+
sessions.delete(sessionID)
697+
sessions.set(sessionID, entry)
698+
while (sessions.size > MAX_TRACKED_SESSIONS) {
699+
const oldest = sessions.keys().next()
700+
if (oldest.done) break
701+
sessions.delete(oldest.value)
702+
}
703+
}
704+
705+
/** Test seam — how many sessions are currently remembered. */
706+
export function trackedSessionsForTests(): number {
707+
return sessions.size
708+
}
709+
684710
/** What a memoised attach is valid FOR.
685711
*
686712
* Memoising on the session id alone was wrong: the binding can change while a
@@ -737,7 +763,7 @@ export function ensure(sessionID: string): Promise<Outcome> {
737763
},
738764
() => {},
739765
)
740-
sessions.set(sessionID, entry)
766+
rememberSession(sessionID, entry)
741767
return entry.task
742768
}
743769

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

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ import {
1515
ATTACH_WAIT_MS,
1616
INSTALL_HINT,
1717
MIN_ENGINE_VERSION,
18+
MAX_TRACKED_SESSIONS,
19+
trackedSessionsForTests,
1820
type LocalMcpConfig,
1921
} from "../../../src/altimate/workspace/engine-sync"
2022
import type { CachedBinding } from "../../../src/altimate/workspace/state"
@@ -45,7 +47,7 @@ function install(opts: {
4547
declared?: { keys: string[]; extensionKeys: string[] } | null
4648
statuses?: Harness["statusQueue"]
4749
tools?: Record<string, unknown>
48-
existing?: { type?: string; url?: string; command?: string[] | string; args?: string[] } | null
50+
existing?: { type?: string; url?: string; command?: string[] | string; args?: string[]; enabled?: boolean } | null
4951
}): Harness {
5052
const h: Harness = {
5153
added: [],
@@ -644,14 +646,16 @@ describe("ensure — reuse reports the declared-vs-delivered gap (rule 5)", () =
644646
})
645647

646648
describe("ensure — an unbound project does not keep a stale MANAGED entry", () => {
647-
test("our own pinned entry is detached when the binding is gone", async () => {
649+
test("a pinned entry is LEFT ALONE when the binding is gone — argv is not provenance", async () => {
650+
// Reversed deliberately in round 5: a hand-authored entry is byte-identical
651+
// to one we wrote, so tearing it down would take the user's server offline.
648652
const h = install({
649653
binding: null,
650654
existing: { type: "local", command: ["datamate", "start-stdio", "--datamate", "5"] },
651655
statuses: [{ datamate: { status: "connected" } }],
652656
})
653657
expect(await ensure("s1")).toEqual({ kind: "unbound" })
654-
expect(h.removes).toEqual(["datamate"])
658+
expect(h.removes).toHaveLength(0)
655659
})
656660

657661
test("an IDE-written entry is LEFT ALONE — it is the user's, not ours", async () => {
@@ -807,7 +811,9 @@ describe("ensure — round 4", () => {
807811
// so retrying a DISABLED entry would undo a deliberate global disable for
808812
// every other project.
809813
const h = install({
810-
existing: { type: "local", command: ["datamate", "start-stdio"] },
814+
// A real user disable is `enabled: false` in the config. The runtime
815+
// status alone is not evidence of intent — see the round-5 test below.
816+
existing: { type: "local", command: ["datamate", "start-stdio"], enabled: false },
811817
statuses: [{ datamate: { status: "disabled" } }],
812818
})
813819
expect(await ensure("s1")).toEqual({ kind: "entry-disabled" })
@@ -853,3 +859,62 @@ describe("ensure — round 4", () => {
853859
expect(peak).toBe(1) // 2 without project-scoped serialization
854860
})
855861
})
862+
863+
describe("ensure — round 5", () => {
864+
test("a REMOVED entry is not mistaken for a user disable — repair still works", async () => {
865+
// MCP.remove deletes s.status[name], and MCP.status() reports a configured
866+
// entry with no status as "disabled". Reading that as user intent made every
867+
// turn after a rejection teardown return entry-disabled, permanently —
868+
// silently undoing the repairable-retry fix from the previous round.
869+
let onPath: string | null = null
870+
const h = install({
871+
existing: { type: "local", command: ["datamate", "start-stdio"] }, // unpinned -> rejected
872+
statuses: [
873+
{ datamate: { status: "connected" } },
874+
{ datamate: { status: "disabled" } }, // synthesized after remove
875+
{ datamate: { status: "connected" } },
876+
{ datamate: { status: "connected" } },
877+
],
878+
tools: { datamate_dbt_build_model: 1, datamate_dbt_compile_model: 1 },
879+
})
880+
syncInternals.which = () => onPath
881+
882+
// Turn 1: rejected and torn down, and no engine to replace it with.
883+
expect(await ensure("s1")).toEqual({ kind: "engine-missing", declared: 2 })
884+
expect(h.removes).toEqual(["datamate"])
885+
886+
// The user installs the engine and takes another turn.
887+
onPath = "/usr/local/bin/datamate"
888+
const second = await ensure("s1")
889+
expect(second).not.toEqual({ kind: "entry-disabled" })
890+
expect(second).toMatchObject({ kind: "attached" })
891+
expect(h.added[h.added.length - 1].cfg.command).toEqual(["datamate", "start-stdio", "--datamate", "42"])
892+
})
893+
894+
test("a genuinely disabled entry (enabled:false in config) is still respected", async () => {
895+
const h = install({
896+
existing: { type: "local", command: ["datamate", "start-stdio"], enabled: false },
897+
statuses: [{ datamate: { status: "disabled" } }],
898+
})
899+
expect(await ensure("s1")).toEqual({ kind: "entry-disabled" })
900+
expect(h.connects).toHaveLength(0)
901+
expect(h.persisted).toHaveLength(0)
902+
})
903+
904+
test("an unbound project does NOT tear down an entry it cannot prove it owns", async () => {
905+
// argv shape is not provenance: a hand-authored entry looks identical to ours.
906+
const h = install({
907+
binding: null,
908+
existing: { type: "local", command: ["datamate", "start-stdio", "--datamate", "5"] },
909+
statuses: [{ datamate: { status: "connected" } }],
910+
})
911+
expect(await ensure("s1")).toEqual({ kind: "unbound" })
912+
expect(h.removes).toHaveLength(0) // the user's server stays up
913+
})
914+
915+
test("the session map does not grow without bound", async () => {
916+
install({ binding: null })
917+
for (let i = 0; i < MAX_TRACKED_SESSIONS + 25; i++) await ensure(`s${i}`)
918+
expect(trackedSessionsForTests()).toBeLessThanOrEqual(MAX_TRACKED_SESSIONS)
919+
})
920+
})

0 commit comments

Comments
 (0)