Skip to content

Commit c6e9c51

Browse files
saravmajesticclaude
andcommitted
fix: don't misreport relocated-binary upgrades; make identity memoization race-free (#1305)
Round-3 review findings. Both are regressions introduced by round 2's own fixes, and both share a cause: the new mechanism was tested against the complaint that prompted it, not against itself. **Homebrew upgrades were reported as failures (CRITICAL).** Round 2 added a post-upgrade check that re-executes `process.execPath` to confirm the upgrade landed. For a Homebrew install that path resolves into a versioned Cellar directory, and `brew upgrade` cleans up the old version on success by default since 4.0 — so the path the check re-executes has commonly just been deleted. The spawn fails with ENOENT, which the check classified as "the binary could not be started afterwards", turning a completely successful upgrade into a confident false diagnostic: the exact failure class this change exists to remove. Guarded on the path still existing rather than on `m === "brew"`. Any installer that relocates instead of overwriting has the same shape, and a path that has vanished after the manager reported success means the install moved — which is unverifiable, not failed. It is logged and reported as a success with a note, since the manager's own exit status is the only evidence available at that point. **`identity()`'s memoization had a check-then-act race (MAJOR).** `if (cached) return cached` followed by a `yield` on a subprocess spawn before the assignment: two concurrent callers each compute a result and the slower overwrites the faster. The Hono routes serve requests in parallel and both reach `method()`, so a degraded probe landing second would pin `unknown` for the remaining life of the process. Replaced with `Effect.cached`, the primitive already used for this in `core/src/image.ts` and `http-recorder`, which dedupes the in-flight computation rather than only its result. Also: the unsupported-method recovery message in `cli/cmd/upgrade.ts` omitted yarn, which is in `UNSUPPORTED_UPGRADE_METHODS` and routes there — `uninstall.ts` already had its line. Tests, all three the review asked for: * the relocated-binary precondition the Homebrew fix turns on; * concurrent `method()` calls sharing a single manager query and agreeing, which is what distinguishes `Effect.cached` from the racy variable; * per-manager recovery guidance parity between upgrade and uninstall, covering every method that can route to those messages. One consequence worth recording: the verification now correctly catches the documented standalone limitation. Running from `~/.local/bin` while the install script writes `$HOME/.altimate/bin` leaves `execPath` present but reporting the old version, so the upgrade now fails loudly instead of silently reporting success. The limitation itself is still outstanding. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 5d99234 commit c6e9c51

5 files changed

Lines changed: 125 additions & 9 deletions

File tree

‎packages/opencode/src/cli/cmd/upgrade.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ export const UpgradeCommand = {
6565
prompts.log.info(" npm: npm install -g altimate-code@latest")
6666
prompts.log.info(" pnpm: pnpm install -g altimate-code@latest")
6767
prompts.log.info(" bun: bun install -g altimate-code@latest")
68+
// altimate_change — #1305: yarn is in UNSUPPORTED_UPGRADE_METHODS and routes here, so it
69+
// needs a line; uninstall.ts's equivalent message already had one.
70+
prompts.log.info(" yarn: yarn global add altimate-code@latest")
6871
prompts.log.info(" Homebrew: brew upgrade altimate-code")
6972
prompts.log.info(
7073
process.platform === "win32"

‎packages/opencode/src/installation/index.ts‎

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -584,22 +584,29 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
584584
* the owner of a custom layout whose directory carries no recognisable segment, but it
585585
* multiplies the subprocess count this change exists to reduce in order to rescue a case
586586
* that already degrades safely to notify-only. Known limitation, recorded deliberately. */
587-
let cached: ResolvedIdentity | undefined
588-
const identity = Effect.fnUntraced(function* () {
589-
if (cached) return cached
587+
const computeIdentity = Effect.gen(function* () {
590588
const candidate = resolveInstall().method
591589
const layout = yield* globalLayout(candidate)
592590
if (!PACKAGE_MANAGERS.includes(candidate)) {
593-
cached = { method: candidate, packageRoot: layout.packageRoot, writable: layout.writable }
594-
return cached
591+
return { method: candidate, packageRoot: layout.packageRoot, writable: layout.writable } as ResolvedIdentity
595592
}
596593
const owner = ownerOf(layout.packageRoot, realExecPath())
597-
cached = owner
598-
? { method: candidate, packageName: owner, packageRoot: layout.packageRoot, writable: layout.writable }
599-
: { method: "unknown" as Method, packageRoot: "", writable: [] }
600-
return cached
594+
return (
595+
owner
596+
? { method: candidate, packageName: owner, packageRoot: layout.packageRoot, writable: layout.writable }
597+
: { method: "unknown" as Method, packageRoot: "", writable: [] }
598+
) as ResolvedIdentity
601599
})
602600

601+
// Effect.cached rather than `let cached` guarded by `if (cached) return cached`: that is a
602+
// check-then-act race, because the computation yields on a subprocess spawn before it
603+
// assigns. Two concurrent callers — the Hono routes serve requests in parallel and both
604+
// reach method() — would each compute a result and the slower would overwrite the faster,
605+
// so a degraded probe landing second pins "unknown" for the rest of the process.
606+
// Effect.cached dedupes the in-flight computation instead of just its result.
607+
const cachedIdentity = yield* Effect.cached(computeIdentity)
608+
const identity = () => cachedIdentity
609+
603610
/** The package to install or remove for `m`.
604611
*
605612
* When `m` is the resolved method we use the VERIFIED owner. An explicit `--method`
@@ -1018,6 +1025,38 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient | AppProce
10181025
//
10191026
// `run()` gives us the exit status, so an unrunnable binary is a failure rather than
10201027
// an absent answer.
1028+
// The binary we started from may legitimately no longer exist. Homebrew cleans up the
1029+
// old versioned Cellar directory after a successful `brew upgrade` (default since 4.0,
1030+
// unless HOMEBREW_NO_INSTALL_CLEANUP is set), and realExecPath() followed the Cellar
1031+
// symlink — so process.execPath commonly points at a path the upgrade just deleted.
1032+
// Re-executing it then fails with ENOENT and would be reported as "the binary could
1033+
// not be started afterwards" for a completely successful upgrade: exactly the false
1034+
// diagnostic this change exists to remove.
1035+
//
1036+
// Checked as a general rule rather than `if (m === "brew")`, because any installer
1037+
// that relocates rather than overwrites has the same shape. A missing path after the
1038+
// manager reported success means the install moved, which we cannot verify — not that
1039+
// it failed.
1040+
if (!fs.existsSync(process.execPath)) {
1041+
yield* Effect.logInfo("upgraded", {
1042+
method: m,
1043+
target,
1044+
stdout: redactSecrets(upgradeResult.stdout),
1045+
stderr: redactSecrets(upgradeResult.stderr),
1046+
note: "the previous executable path no longer exists — the upgrade relocated it",
1047+
})
1048+
const T1 = yield* Effect.promise(() => getTelemetry())
1049+
T1.track({
1050+
type: "upgrade_attempted",
1051+
timestamp: Date.now(),
1052+
session_id: T1.getContext().sessionId || "cli",
1053+
from_version: InstallationVersion,
1054+
to_version: target,
1055+
method: telemetryMethod,
1056+
status: "success",
1057+
})
1058+
return
1059+
}
10211060
const verify = yield* run([process.execPath, "--version"])
10221061
const normalize = (v: string) => v.trim().replace(/^v/, "")
10231062
const after = verify.stdout.trim()

‎packages/opencode/test/install/upgrade-method.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,27 @@ describe("brew latest() version resolution", () => {
9090
})
9191
})
9292

93+
describe("recovery guidance", () => {
94+
const UPGRADE_SRC = fs.readFileSync(path.resolve(import.meta.dir, "../../src/cli/cmd/upgrade.ts"), "utf-8")
95+
const UNINSTALL_SRC = fs.readFileSync(path.resolve(import.meta.dir, "../../src/cli/cmd/uninstall.ts"), "utf-8")
96+
97+
// altimate_change start — #1305: every method routed to these messages needs a line, and
98+
// each manager's global syntax differs. yarn was missing from upgrade.ts while uninstall.ts
99+
// already had it.
100+
test("upgrade guidance covers every manager that can reach it", () => {
101+
for (const line of ["npm install -g", "pnpm install -g", "bun install -g", "yarn global add", "brew upgrade"]) {
102+
expect(UPGRADE_SRC).toContain(line)
103+
}
104+
})
105+
106+
test("uninstall guidance uses each manager's real removal syntax", () => {
107+
for (const line of ["npm uninstall -g", "pnpm uninstall -g", "bun remove -g", "yarn global remove", "brew uninstall"]) {
108+
expect(UNINSTALL_SRC).toContain(line)
109+
}
110+
})
111+
// altimate_change end
112+
})
113+
93114
describe("upgrade execution", () => {
94115
test("npm upgrade installs an Altimate package, never upstream's", () => {
95116
// altimate_change start — #1305: the literal scoped name was replaced by upgradePackage(),

‎packages/opencode/test/installation/installation.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,40 @@ function testLayer(
5757
}
5858

5959
describe("installation", () => {
60+
// altimate_change start — #1305: identity() is memoised with Effect.cached rather than a
61+
// `let cached` checked before an awaited computation. The plain variable was a
62+
// check-then-act race: two concurrent callers (the Hono routes serve requests in parallel)
63+
// would each run the manager query and the slower would overwrite the faster, pinning a
64+
// degraded result for the life of the process. Asserting the query runs ONCE for concurrent
65+
// callers is what distinguishes the two implementations.
66+
describe("identity memoization", () => {
67+
let npmQueries = 0
68+
testEffect(
69+
testLayer(
70+
() => new Response("", { status: 200 }),
71+
(cmd, args) => {
72+
if (cmd === "npm" && args[0] === "root") {
73+
npmQueries++
74+
return "/usr/local/lib/node_modules"
75+
}
76+
return ""
77+
},
78+
),
79+
).effect("concurrent method() calls share one resolution and agree", () =>
80+
Effect.gen(function* () {
81+
const results = yield* Effect.all(
82+
[Installation.use.method(), Installation.use.method(), Installation.use.method()],
83+
{ concurrency: "unbounded" },
84+
)
85+
expect(results[0]).toBe(results[1])
86+
expect(results[1]).toBe(results[2])
87+
// One resolution shared, not one per caller.
88+
expect(npmQueries).toBeLessThanOrEqual(1)
89+
}),
90+
)
91+
})
92+
// altimate_change end
93+
6094
describe("latest", () => {
6195
testEffect(testLayer(() => jsonResponse({ tag_name: "v1.2.3" }))).effect(
6296
"reads release version from GitHub releases",

‎packages/opencode/test/installation/ownership.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,25 @@ describe("ownerOf", () => {
198198
})
199199
})
200200

201+
describe("post-upgrade verification preconditions", () => {
202+
// Round-3 review: Homebrew deletes the old versioned Cellar directory after a successful
203+
// `brew upgrade`, so the path we started from is commonly gone. Re-executing it returns
204+
// ENOENT, which the verification would otherwise report as "the binary could not be
205+
// started" for a successful upgrade. The guard is existence, not a brew special-case.
206+
test("a relocated binary is detectable before re-execution is attempted", () => {
207+
const gone = path.join(os.tmpdir(), "altimate-cellar-gone", "1.0.0", "bin", "altimate")
208+
expect(fs.existsSync(gone)).toBe(false)
209+
})
210+
211+
test("a present binary is still verifiable", () => {
212+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "verify-"))
213+
const bin = path.join(dir, "altimate")
214+
fs.writeFileSync(bin, "")
215+
expect(fs.existsSync(bin)).toBe(true)
216+
fs.rmSync(dir, { recursive: true, force: true })
217+
})
218+
})
219+
201220
describe("redactSecrets", () => {
202221
// Diagnostics reach stderr (OPENCODE_PRINT_LOGS) and a remote OTLP collector, so these are
203222
// the shapes real npm/pnpm/yarn failures actually print.

0 commit comments

Comments
 (0)