Skip to content

Commit e526f9c

Browse files
sahrizviclaude
andcommitted
fix(workspace): no notification on a failed cache write, no re-queued ticks, no double resolve
Ralph's review of #1279, both blocking items and the notes. - `forgetBinding` notifies only when something on disk changed. Notifying on a failed write too made a hot loop when the state directory could not be written: the sidebar answers a notification with a resolve, the resolve hears the memoized miss and re-enters `forgetBinding`, the write fails again, it notifies again. A read-only state directory now costs one poll interval of staleness. Reproduced as a test: forty notifications before, zero after. - The sidebar queues a re-run only for a binding-change notification; a tick that lands mid-refresh is dropped. During an outage each refresh outlasted the tick, so the interval re-queued the next one back to back. - `Manage.status` takes the binding the sidebar already resolved instead of resolving it again — two unmemoized requests per pass during an outage. - Adoption in `lookupBinding` notifies, so a `/workspace` open that adopts wakes the tile; the row is stamped validated first, so the answering resolve does not come back. - `lastSuccessfulSyncAt`'s docstring describes the marker, not the map. Verified: 547 pass across the workspace + plugin suites, typecheck clean. Mutation-checked: notifying regardless, and ignoring the handed binding, each fail a test. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent 64cb237 commit e526f9c

5 files changed

Lines changed: 107 additions & 29 deletions

File tree

‎packages/opencode/src/altimate/workspace/manage.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ export async function status(
115115
* cache alone and reported as unknown (`null`) if not held, and a cached
116116
* row is taken as it is. `sync` does the live check. */
117117
poll?: boolean
118+
/** A binding the caller has already resolved this pass. The sidebar
119+
* resolves before it asks for status; resolving again here doubled the
120+
* requests during an outage, when neither answer is memoized. */
121+
binding?: CachedBinding | null
118122
} = {},
119123
): Promise<StatusReport> {
120124
// The cached row first, and the resolver only when there is none — for the
@@ -124,9 +128,13 @@ export async function status(
124128
// resolver revalidates a cached row too, and on the first call of a process
125129
// nothing has been validated yet: the menu then sat on the API's full
126130
// timeout when the service was unreachable.
127-
const binding = opts.poll
128-
? await resolveBinding(directory).catch(() => null)
129-
: ((await readLocalBinding(directory).catch(() => null)) ?? (await resolveBinding(directory).catch(() => null)))
131+
const binding =
132+
opts.binding !== undefined
133+
? opts.binding
134+
: opts.poll
135+
? await resolveBinding(directory).catch(() => null)
136+
: ((await readLocalBinding(directory).catch(() => null)) ??
137+
(await resolveBinding(directory).catch(() => null)))
130138
return {
131139
binding,
132140
memory: await memoryCounts(directory, binding, opts.poll === true),

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -255,14 +255,14 @@ export async function flushPendingSyncs(timeoutMs = 30_000): Promise<void> {
255255
}
256256
}
257257

258-
/** When this project's workspace skills last synced successfully, or null if
259-
* they never have in this process.
258+
/** When this project's workspace skills were last brought up to date by a
259+
* CLEAN sync, or null when there is no snapshot, no marker, or the snapshot is
260+
* another binding's.
260261
*
261262
* Exposed for the sidebar. `recentlySynced` answers a boolean against the poll
262263
* interval, which cannot say "6 minutes ago" — and a status line whose whole job
263-
* is to make staleness visible needs the age, not a threshold. Reads the
264-
* process-global store, so the TUI plugin realm sees the same map the sync
265-
* writes (see `STORE_KEY` above). */
264+
* is to make staleness visible needs the age, not a threshold. Read from the
265+
* marker on disk, which every thread and module realm sees alike. */
266266
export async function lastSuccessfulSyncAt(
267267
directory: string,
268268
/** The binding the age is being reported under. A marker beside a manifest

‎packages/opencode/src/altimate/workspace/state.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,7 @@ function forgetBinding(
546546
expect?: ExpectedRow,
547547
before?: UnscopedRow | null,
548548
): boolean {
549+
let dropped = false
549550
try {
550551
const cache = readCache()
551552
if (!cache) return true
@@ -577,6 +578,7 @@ function forgetBinding(
577578
}
578579
for (const k of keys) delete cache.bindings[k]
579580
writeCache(cache)
581+
dropped = true
580582
} catch (err) {
581583
log.warn("could not drop a binding the server no longer recognises", { err: String(err) })
582584
}
@@ -585,17 +587,15 @@ function forgetBinding(
585587
// subscriber as "could not drop a binding" — a misleading line about a write
586588
// that had already succeeded.
587589
//
588-
// Notified even when the write FAILED, which is not obvious. The server-side
589-
// unlink has already happened by the time we get here, and the resolve path
590-
// does not depend on this file having been rewritten: `clearLocalBinding`
591-
// drops the revalidation stamp and records a lookup miss, so the next resolve
592-
// asks the server, hears "unbound", and the tile updates. Skipping the
593-
// notification on a failed write left the pane naming a workspace this
594-
// project is no longer bound to until the next poll — the exact lag the
595-
// notifier exists to remove, in the case where something is already wrong.
596-
// (An earlier version guarded this on whether the write succeeded, and
597-
// called the difference unobservable. It was not.)
598-
notifyBindingChanged()
590+
// Only when something on disk changed. Notifying on a failed write too was
591+
// tried, so the tile would not name an unlinked workspace until the next
592+
// poll — and it made a hot loop: the sidebar answers a notification with a
593+
// resolve, the resolve hears the memoized miss and re-enters here, the
594+
// write fails again, and it notifies again, forty times in as many
595+
// milliseconds for as long as the state directory stays unwritable. A
596+
// read-only state directory now costs one poll interval of staleness
597+
// instead, which is the right trade. (Ralph, review of #1279.)
598+
if (dropped) notifyBindingChanged()
599599
return true
600600
}
601601

@@ -646,6 +646,7 @@ async function lookupBinding(
646646
projectPath: row.project_path ?? null,
647647
linkedAt: Date.now(),
648648
}
649+
let adoptedNow = false
649650
try {
650651
const existing = readCache()
651652
const cache: CacheFile =
@@ -661,6 +662,7 @@ async function lookupBinding(
661662
? { ...adopted, adopted: prior.adopted, seededAt: prior.seededAt, linkedAt: prior.linkedAt }
662663
: adopted
663664
writeCache(cache)
665+
adoptedNow = !prior || prior.datamateId !== adopted.datamateId
664666
} catch (err) {
665667
// The binding still stands for this call; only the cache write failed, so
666668
// the next process looks it up again. Same reasoning as recordApprovedBinding.
@@ -670,6 +672,11 @@ async function lookupBinding(
670672
log.info("adopted the workspace binding this project already has on the server", {
671673
datamateId: adopted.datamateId,
672674
})
675+
// An adoption is a binding change this process made to its cache, and the
676+
// sidebar is not always the caller — a `/workspace` open that adopts left
677+
// the tile to the next poll. Stamped as validated above, so the sidebar's
678+
// answering resolve trusts the row and does not come back here.
679+
if (adoptedNow) notifyBindingChanged()
673680
return { status: "bound", binding: adopted }
674681
}
675682

‎packages/opencode/src/plugin/tui/altimate/workspace-sidebar.tsx‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,17 @@ function View(props: { api: TuiPluginApi }) {
9494
return null
9595
}
9696
}
97-
const refresh = async () => {
98-
// Coalesce rather than drop. A binding-change notification can land while a
99-
// poll is mid-flight, and that pass may already have read the old binding —
100-
// returning early would leave the tile stale until the next tick, which is
101-
// exactly the lag the listener exists to remove. One queued re-run is
102-
// enough however many notifications arrive while we are busy.
97+
const refresh = async (why: "poll" | "notify" = "poll") => {
98+
// A notification that lands mid-refresh is queued, not dropped: that pass
99+
// may already have read the old binding, and returning early would leave
100+
// the tile stale until the next tick — the lag the listener exists to
101+
// remove. A TICK that lands mid-refresh is dropped: it carries no news,
102+
// and queuing it meant that while the service was unreachable — three
103+
// calls on a 15s budget each, longer than the 30s tick — the next refresh
104+
// started the moment the last one ended, back to back for as long as the
105+
// outage lasted. (Ralph, review of #1279.)
103106
if (refreshInFlight) {
104-
refreshQueued = true
107+
if (why === "notify") refreshQueued = true
105108
return
106109
}
107110
refreshInFlight = true
@@ -171,7 +174,10 @@ function View(props: { api: TuiPluginApi }) {
171174
// what left these counts blank until something else happened to warm the
172175
// cache. The `/workspace` menu, by contrast, is cache-only, because it is
173176
// awaited before the dialog can open. See `Manage.status`.
174-
setDetail(await Manage.status(dir, { poll: true }).catch(() => null))
177+
// Handed the binding this pass resolved, so `status` does not resolve it
178+
// again — during an outage neither answer is memoized, and that was two
179+
// requests where one was already too many.
180+
setDetail(await Manage.status(dir, { poll: true, binding: b }).catch(() => null))
175181
// altimate_change end
176182
} finally {
177183
refreshInFlight = false
@@ -197,7 +203,7 @@ function View(props: { api: TuiPluginApi }) {
197203
// to POLL_MS — the UI contradicting itself, with the stale half looking
198204
// authoritative. The interval stays: it is what catches a change made by
199205
// another process, which no in-process listener can see.
200-
const unsubscribe = onBindingChanged(() => void refresh())
206+
const unsubscribe = onBindingChanged(() => void refresh("notify"))
201207
onCleanup(() => {
202208
disposed = true
203209
clearInterval(timer)

‎packages/opencode/test/altimate/workspace/manage.test.ts‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
// issued — method, path, query — and the binding cache is a real file in a real
1515
// sandbox directory.
1616
import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"
17-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"
17+
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"
1818
import { execFileSync } from "node:child_process"
1919
import path from "node:path"
2020
import os from "node:os"
@@ -1035,6 +1035,63 @@ describe("the poller does not drip", () => {
10351035
})
10361036
})
10371037

1038+
describe("a state directory that cannot be written", () => {
1039+
test("does not turn the notify → resolve chain into a hot loop", async () => {
1040+
// Ralph's reproduction on #1279: a row on disk, the server answering
1041+
// unbound, the state directory read-only, and a subscriber that resolves
1042+
// the way the sidebar's queued refresh does. Notifying on a failed write
1043+
// made every resolve re-enter `forgetBinding`, which notified, which the
1044+
// subscriber answered with another resolve — forty times in 24ms.
1045+
await bind(projectDir)
1046+
expireValidationForTests(projectDir)
1047+
const originalFetch3 = globalThis.fetch
1048+
globalThis.fetch = (async (input: any, init?: any) => {
1049+
const url = typeof input === "string" ? input : input.url
1050+
const method = (init?.method ?? "GET").toUpperCase()
1051+
requests.push({ method, url })
1052+
if (method === "GET" && url.includes("/datamate-project-bindings/by-"))
1053+
return new Response(JSON.stringify({ detail: "gone" }), {
1054+
status: 404,
1055+
headers: { "content-type": "application/json" },
1056+
})
1057+
return originalFetch3(input, init)
1058+
}) as typeof fetch
1059+
let notifications = 0
1060+
let resolves = 0
1061+
const unsubscribe = onBindingChanged(() => {
1062+
notifications++
1063+
if (notifications < 50) void resolveBindingOutcome(projectDir).then(() => resolves++)
1064+
})
1065+
const stateDir = path.dirname(cachePath())
1066+
chmodSync(stateDir, 0o555)
1067+
try {
1068+
const outcome = await resolveBindingOutcome(projectDir)
1069+
expect(outcome.status).toBe("unbound")
1070+
await new Promise((r) => setTimeout(r, 100))
1071+
} finally {
1072+
chmodSync(stateDir, 0o755)
1073+
unsubscribe()
1074+
globalThis.fetch = originalFetch3
1075+
}
1076+
// Nothing on disk changed, so nobody was told; the row stays until the
1077+
// next poll, which is one interval of staleness rather than a loop.
1078+
expect(notifications).toBe(0)
1079+
expect(resolves).toBe(0)
1080+
})
1081+
})
1082+
1083+
describe("status reuses a binding the caller resolved", () => {
1084+
test("makes no binding request of its own when handed one", async () => {
1085+
await bind(projectDir)
1086+
expireValidationForTests(projectDir)
1087+
const b = (await readLocalBinding(projectDir))!
1088+
requests = []
1089+
const report = await status(projectDir, { poll: true, binding: b })
1090+
expect(report.binding?.datamateId).toBe(42)
1091+
expect(requests.filter((r) => r.url.includes("/datamate-project-bindings/"))).toHaveLength(0)
1092+
})
1093+
})
1094+
10381095
describe("the poller coalesces overlapping misses", () => {
10391096
test("two refreshes on a cold memo put one request on the wire", async () => {
10401097
// A remount while a slow refresh is still out started a second one; both

0 commit comments

Comments
 (0)