Skip to content

Commit 09dc7bc

Browse files
sahrizviclaude
andcommitted
fix(workspace): the sync marker carries its identity; the poller sits on an unknown; renames wake the tile
- `.synced-at` is JSON carrying the workspace id, tenant and API URL it was written for, and `lastSuccessfulSyncAt` validates against the binding it reports under from the marker alone. Checking the manifest beside it was a second read, and another process could swap the tree between the two. Writing it is best-effort in the staged tree, so a failed marker write cannot cost a complete snapshot its publish. - The poller memoizes "unknown" for one tick. Not memoizing it meant every tick during an outage asked, and a queued re-run after a self-adoption asked twice in one tick. - A same-id adoption that changes the name or identifiers notifies, and the resolver's same-workspace answer carries the server's current name rather than the row as read before the write. - The sidebar clears what it rendered when the scope moved under the resolve (rather than only dropping the outcome), and re-checks the scope before committing the manage URL and the status, each of which takes a credentials read of its own. Verified: 550 pass across the workspace + plugin suites, typecheck clean. Mutation-checked: not memoizing unknown, not notifying on a rename, returning the stale name, and skipping the marker's identity check each fail a test. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent e925a55 commit 09dc7bc

5 files changed

Lines changed: 194 additions & 42 deletions

File tree

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

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -682,12 +682,17 @@ async function runQueue<T>(
682682
* back to the network on every other tick — a steady drip of `/datamates`
683683
* requests for the life of the session. (cubic P2 on #1279.) */
684684
const POLL_TTL_MS = 5 * 60 * 1000
685+
/** How long the poller sits on an "unknown" before asking again. Not
686+
* memoizing it at all meant every tick during an outage asked — and a queued
687+
* re-run after a self-adoption asked twice in one tick. One poll interval:
688+
* the tile shows no counts until the next tick either way. */
689+
const POLL_UNKNOWN_TTL_MS = 30 * 1000
685690

686691
/** Keyed by tenant and API URL as well as workspace id. Workspace ids are
687692
* tenant-local, so a bare id let a same-numbered workspace in a NEWLY switched
688693
* account inherit the previous tenant's answer and hide its unsynced count for
689694
* the whole TTL. (cubic P2 on #1279.) */
690-
const pollMemo = new Map<string, { at: number; status: "enabled" | "disabled" }>()
695+
const pollMemo = new Map<string, { at: number; status: "enabled" | "disabled" | "unknown" }>()
691696
const pollInFlight = new Map<string, Promise<"enabled" | "disabled" | "unknown">>()
692697

693698
async function pollMemoKey(binding: CachedBinding): Promise<string> {
@@ -725,7 +730,8 @@ export async function memoryEnabledForPoller(
725730
// minutes per tenant is the price, and `memoryStatus` still warms both.
726731
const key = await pollMemoKey(binding)
727732
const memo = pollMemo.get(key)
728-
if (memo && Date.now() - memo.at < POLL_TTL_MS) return memo.status
733+
if (memo && Date.now() - memo.at < (memo.status === "unknown" ? POLL_UNKNOWN_TTL_MS : POLL_TTL_MS))
734+
return memo.status
729735
// The in-flight ask is memoized too, not only the settled answer. Two
730736
// refreshes overlapping on a cold memo — a remount while a slow one is
731737
// still out — both saw it empty and both put a request on the wire.
@@ -734,9 +740,9 @@ export async function memoryEnabledForPoller(
734740
const ask = (async () => {
735741
try {
736742
const status = await memoryStatus(binding, { fresh: true })
737-
if (status === "error") return "unknown" as const
738-
pollMemo.set(key, { at: Date.now(), status })
739-
return status
743+
const answer = status === "error" ? ("unknown" as const) : status
744+
pollMemo.set(key, { at: Date.now(), status: answer })
745+
return answer
740746
} finally {
741747
pollInFlight.delete(key)
742748
}

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

Lines changed: 53 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -265,23 +265,14 @@ export async function flushPendingSyncs(timeoutMs = 30_000): Promise<void> {
265265
* marker on disk, which every thread and module realm sees alike. */
266266
export async function lastSuccessfulSyncAt(
267267
directory: string,
268-
/** The binding the age is being reported under. A marker beside a manifest
269-
* for another workspace or account is not this binding's sync: after a
270-
* rebind the sidebar can refresh before the detached sync has replaced the
271-
* previous workspace's snapshot, and would otherwise show A's age under
272-
* B's name. */
268+
/** The binding the age is being reported under. A marker for another
269+
* workspace or account is not this binding's sync: after a rebind the
270+
* sidebar can refresh before the detached sync has replaced the previous
271+
* workspace's snapshot, and would otherwise show A's age under B's name.
272+
* The marker carries its own identity — checking the manifest beside it was
273+
* a second read, and another process could swap the tree between the two. */
273274
binding?: { datamateId: number; tenant: string; apiUrl: string },
274275
): Promise<number | null> {
275-
if (binding) {
276-
const manifest = await readManifest(directory)
277-
if (
278-
!manifest ||
279-
manifest.datamateId !== binding.datamateId ||
280-
manifest.tenant !== binding.tenant ||
281-
manifest.apiUrl !== binding.apiUrl
282-
)
283-
return null
284-
}
285276
// From disk, not from the map. The map is on `globalThis`, which is shared
286277
// across module realms but NOT across threads — and the per-message sync
287278
// that does most of the stamping runs in the server worker, while the TUI
@@ -291,12 +282,17 @@ export async function lastSuccessfulSyncAt(
291282
// agree; the manifest's mtime did not — a partial run publishes one, and a
292283
// clean up-to-date run publishes nothing.
293284
try {
294-
// Validated, not coerced: `Number("")` is 0, and a truncated marker would
295-
// otherwise render as a sync from 1970.
296-
const raw = (await fs.readFile(path.join(managedRoot(directory), SYNCED_MARKER), "utf8")).trim()
297-
if (!/^\d+$/.test(raw)) return null
298-
const at = Number(raw)
299-
return Number.isSafeInteger(at) && at > 0 ? at : null
285+
// Validated, not coerced: a truncated or hand-edited marker reads as
286+
// unknown, never as a sync from 1970 or as another workspace's.
287+
const raw = await fs.readFile(path.join(managedRoot(directory), SYNCED_MARKER), "utf8")
288+
const marker = parseMarker(raw)
289+
if (!marker) return null
290+
if (
291+
binding &&
292+
(marker.datamateId !== binding.datamateId || marker.tenant !== binding.tenant || marker.apiUrl !== binding.apiUrl)
293+
)
294+
return null
295+
return marker.at
300296
} catch (err) {
301297
// No snapshot is no sync: after an unlink, a rebind, or an empty
302298
// workspace, an in-memory stamp from before would report a sync that no
@@ -307,6 +303,31 @@ export async function lastSuccessfulSyncAt(
307303
}
308304
}
309305

306+
/** What a clean sync leaves at the managed root: when, and for which binding. */
307+
interface SyncMarker {
308+
at: number
309+
datamateId: number
310+
tenant: string
311+
apiUrl: string
312+
}
313+
314+
function parseMarker(raw: string): SyncMarker | null {
315+
try {
316+
const m = JSON.parse(raw) as Partial<SyncMarker> | null
317+
if (!m || typeof m !== "object") return null
318+
if (typeof m.at !== "number" || !Number.isSafeInteger(m.at) || m.at <= 0) return null
319+
if (typeof m.datamateId !== "number") return null
320+
if (typeof m.tenant !== "string" || typeof m.apiUrl !== "string") return null
321+
return { at: m.at, datamateId: m.datamateId, tenant: m.tenant, apiUrl: m.apiUrl }
322+
} catch {
323+
return null
324+
}
325+
}
326+
327+
function markerFor(manifest: Pick<Manifest, "datamateId" | "tenant" | "apiUrl">, at: number): string {
328+
return JSON.stringify({ at, datamateId: manifest.datamateId, tenant: manifest.tenant, apiUrl: manifest.apiUrl })
329+
}
330+
310331
/** Has this project's snapshot been checked within the poll interval? Callers
311332
* on a per-message path use this to skip the network entirely. */
312333
export async function recentlySynced(directory: string): Promise<boolean> {
@@ -996,7 +1017,12 @@ export async function syncSkills(directory: string): Promise<{ changed: boolean
9961017
// marker and B was reported with A's sync age. `failed` is settled by
9971018
// now — every skill has been fetched or skipped — so a partial publish
9981019
// carries no marker, and the previous one went with the retired tree.
999-
if (!failed) await fs.writeFile(path.join(staging, SYNCED_MARKER), String(Date.now()))
1020+
// Best-effort: the marker is status metadata, and a failure to write it
1021+
// must not cost a complete staged snapshot its publish.
1022+
if (!failed)
1023+
await fs.writeFile(path.join(staging, SYNCED_MARKER), markerFor(next, Date.now())).catch((err) => {
1024+
log.warn("could not write the workspace skill sync marker", { err: String(err) })
1025+
})
10001026
// Move the live tree aside rather than deleting it first. `rm` then
10011027
// `rename` leaves a window with no snapshot at all — a crash or a reader
10021028
// inside it sees the skills vanish. The retired tree is removed only
@@ -1048,7 +1074,11 @@ export async function syncSkills(directory: string): Promise<{ changed: boolean
10481074
// nothing: the manifest on disk is unchanged, so stamping beside it
10491075
// cannot pair it with another workspace. Only where a snapshot exists —
10501076
// a clean run against an empty workspace removed the root.
1051-
if (!changed) await fs.writeFile(path.join(managedRoot(canon), SYNCED_MARKER), String(now)).catch(() => {})
1077+
if (!changed) {
1078+
const current = await readManifest(canon)
1079+
if (current)
1080+
await fs.writeFile(path.join(managedRoot(canon), SYNCED_MARKER), markerFor(current, now)).catch(() => {})
1081+
}
10521082
}
10531083
return { changed }
10541084
})()

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,19 @@ export async function resolveBindingOutcome(directory: string): Promise<BindingO
400400
lastValidatedAt.set(accountScopedKey(directory, key), Date.now())
401401
// Rebound elsewhere: adopt the server's answer, replacing the cached row.
402402
if (fresh.binding.datamateId !== local.datamateId) return fresh
403-
return { status: "bound", binding: local }
403+
// Same workspace: the local row's provenance (explicit link, seed marker)
404+
// with the server's current name and identifiers, which `lookupBinding`
405+
// just wrote to the cache — returning `local` as read handed the caller
406+
// the name from before a rename.
407+
return {
408+
status: "bound",
409+
binding: {
410+
...local,
411+
datamateName: fresh.binding.datamateName,
412+
repoRemote: fresh.binding.repoRemote,
413+
projectPath: fresh.binding.projectPath,
414+
},
415+
}
404416
}
405417
return await lookupBinding(directory, key)
406418
}
@@ -662,7 +674,15 @@ async function lookupBinding(
662674
? { ...adopted, adopted: prior.adopted, seededAt: prior.seededAt, linkedAt: prior.linkedAt }
663675
: adopted
664676
writeCache(cache)
665-
adoptedNow = !prior || prior.datamateId !== adopted.datamateId
677+
// Anything the tile renders or the delete identifies by: a rename, or a
678+
// remote/path the server now holds differently, is a change worth waking
679+
// the sidebar for, even under the same id.
680+
adoptedNow =
681+
!prior ||
682+
prior.datamateId !== adopted.datamateId ||
683+
prior.datamateName !== adopted.datamateName ||
684+
prior.repoRemote !== adopted.repoRemote ||
685+
prior.projectPath !== adopted.projectPath
666686
} catch (err) {
667687
// The binding still stands for this call; only the cache write failed, so
668688
// the next process looks it up again. Same reasoning as recordApprovedBinding.

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

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,21 +134,31 @@ function View(props: { api: TuiPluginApi }) {
134134
// different account": a transient read failure must not blank a tile
135135
// the resolver would have preserved. Only a scope that READS as another
136136
// one clears.
137-
const scopeBefore = await currentScope()
138-
if (boundScope !== null && scopeBefore !== null && scopeBefore !== boundScope) {
137+
const clearRendered = () => {
139138
setDetail(null)
140139
setManageUrl(null)
141140
setBinding(undefined)
142141
boundScope = null
143142
}
143+
const scopeBefore = await currentScope()
144+
if (boundScope !== null && scopeBefore !== null && scopeBefore !== boundScope) clearRendered()
144145
const outcome = await resolveBindingOutcome(dir).catch(() => ({ status: "unknown" }) as const)
145146
// Read again after the resolve. The credentials can change between the
146147
// two reads, and the resolver runs under whatever they were when it
147148
// ran; a scope that moved underneath it means this outcome cannot be
148-
// trusted against the scope read first. Drop it: the next tick reads a
149-
// settled pair.
149+
// trusted against the scope read first. What WAS rendered belonged to
150+
// the old scope and goes now; the outcome is dropped, and the next tick
151+
// reads a settled pair.
150152
const scope = await currentScope()
151-
if (scope !== scopeBefore) return
153+
if (scope !== scopeBefore) {
154+
if (scope !== null) clearRendered()
155+
return
156+
}
157+
// Every later commit in this pass checks the scope again first: the
158+
// manage base and the status each take a credentials read of their own,
159+
// and a switch during either would otherwise pair one account's binding
160+
// with another's URL or counts.
161+
const stillThisScope = async () => (await currentScope()) === scope
152162
if (outcome.status === "bound") {
153163
// Counts and the manage URL belong to a SPECIFIC workspace. On a rebind
154164
// they would otherwise keep describing the old one until the new status
@@ -176,6 +186,10 @@ function View(props: { api: TuiPluginApi }) {
176186
// cleared the manage URL, or never set one.
177187
if (!b) return
178188
const base = await resolveManageBase()
189+
if (!(await stillThisScope())) {
190+
clearRendered()
191+
return
192+
}
179193
setManageUrl(base ? buildManageUrl(base, b.datamateId) : null)
180194
// altimate_change start - status lines
181195
// `poll: true` marks this as the POLLER path: `status` then resolves the
@@ -188,7 +202,12 @@ function View(props: { api: TuiPluginApi }) {
188202
// Handed the binding this pass resolved, so `status` does not resolve it
189203
// again — during an outage neither answer is memoized, and that was two
190204
// requests where one was already too many.
191-
setDetail(await Manage.status(dir, { poll: true, binding: b }).catch(() => null))
205+
const detail = await Manage.status(dir, { poll: true, binding: b }).catch(() => null)
206+
if (!(await stillThisScope())) {
207+
clearRendered()
208+
return
209+
}
210+
setDetail(detail)
192211
// altimate_change end
193212
} finally {
194213
refreshInFlight = false

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

Lines changed: 83 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -941,6 +941,8 @@ describe("what /workspace status may cost and claim (review round 2)", () => {
941941

942942
const manifestFor = (datamateId: number) =>
943943
JSON.stringify({ version: 1, tenant: "acme", apiUrl: "https://api.example.com", datamateId, skills: {} })
944+
const markerFor = (datamateId: number, at: number) =>
945+
JSON.stringify({ at, datamateId, tenant: "acme", apiUrl: "https://api.example.com" })
944946

945947
describe("the sidebar's skills-synced age", () => {
946948
test("comes from the snapshot on disk, not a per-thread map", async () => {
@@ -953,22 +955,23 @@ describe("the sidebar's skills-synced age", () => {
953955
mkdirSync(managed, { recursive: true })
954956
writeFileSync(path.join(managed, ".manifest.json"), manifestFor(42))
955957
const before = Date.now() - 5 * 60_000
956-
writeFileSync(path.join(managed, ".synced-at"), String(before))
958+
writeFileSync(path.join(managed, ".synced-at"), markerFor(42, before))
957959

958960
const report = await status(projectDir)
959961

960962
expect(report.skillsSyncedAt).toBe(before)
961963
})
962964

963-
test("is nothing when the snapshot beside the marker belongs to another workspace", async () => {
965+
test("is nothing when the marker belongs to another workspace", async () => {
964966
// After a rebind the sidebar can refresh before the detached sync has
965967
// replaced the previous workspace's snapshot, and would otherwise render
966-
// A's age under B's name.
968+
// A's age under B's name. The marker carries its own identity, so this
969+
// holds without a second read of the manifest beside it.
967970
await bind(projectDir)
968971
const managed = path.join(projectDir, ".altimate-code", "skill", "_workspace")
969972
mkdirSync(managed, { recursive: true })
970-
writeFileSync(path.join(managed, ".manifest.json"), manifestFor(7))
971-
writeFileSync(path.join(managed, ".synced-at"), String(Date.now() - 60_000))
973+
writeFileSync(path.join(managed, ".manifest.json"), manifestFor(42))
974+
writeFileSync(path.join(managed, ".synced-at"), markerFor(7, Date.now() - 60_000))
972975

973976
expect((await status(projectDir)).skillsSyncedAt).toBeNull()
974977
})
@@ -979,7 +982,7 @@ describe("the sidebar's skills-synced age", () => {
979982
const managed = path.join(projectDir, ".altimate-code", "skill", "_workspace")
980983
mkdirSync(managed, { recursive: true })
981984
writeFileSync(path.join(managed, ".manifest.json"), manifestFor(42))
982-
for (const junk of ["", " \n", "soon", "12abc"]) {
985+
for (const junk of ["", " \n", "soon", "12abc", "1700000000000", '{"at":0,"datamateId":42}', "{not json"]) {
983986
writeFileSync(path.join(managed, ".synced-at"), junk)
984987
expect((await status(projectDir)).skillsSyncedAt).toBeNull()
985988
}
@@ -1092,6 +1095,80 @@ describe("status reuses a binding the caller resolved", () => {
10921095
})
10931096
})
10941097

1098+
describe("the poller during an outage", () => {
1099+
test("sits on an unknown for a tick rather than asking again at once", async () => {
1100+
// Not memoizing "unknown" at all meant every tick during an outage asked,
1101+
// and a queued re-run after a self-adoption asked twice in one tick.
1102+
await bind(projectDir)
1103+
resetPollMemoForTests()
1104+
const originalFetch3 = globalThis.fetch
1105+
globalThis.fetch = (async (input: any, init?: any) => {
1106+
const url = typeof input === "string" ? input : input.url
1107+
const method = (init?.method ?? "GET").toUpperCase()
1108+
requests.push({ method, url })
1109+
if (method === "GET" && url.endsWith("/datamates/"))
1110+
return new Response(JSON.stringify({ detail: "down" }), {
1111+
status: 503,
1112+
headers: { "content-type": "application/json" },
1113+
})
1114+
return originalFetch3(input, init)
1115+
}) as typeof fetch
1116+
try {
1117+
requests = []
1118+
const b = (await readLocalBinding(projectDir))!
1119+
expect(await memoryEnabledForPoller(b)).toBe("unknown")
1120+
expect(await memoryEnabledForPoller(b)).toBe("unknown")
1121+
expect(requests.filter((r) => r.method === "GET" && r.url.endsWith("/datamates/"))).toHaveLength(1)
1122+
} finally {
1123+
globalThis.fetch = originalFetch3
1124+
}
1125+
})
1126+
})
1127+
1128+
describe("a rename on the server", () => {
1129+
test("reaches the resolver's answer and wakes the sidebar", async () => {
1130+
// The same workspace, renamed in the SaaS. `lookupBinding` wrote the new
1131+
// name to the cache but the resolver handed back the row it had read
1132+
// before, and nothing woke the tile — so the old name stood.
1133+
await bind(projectDir)
1134+
expireValidationForTests(projectDir)
1135+
const originalFetch3 = globalThis.fetch
1136+
globalThis.fetch = (async (input: any, init?: any) => {
1137+
const url = typeof input === "string" ? input : input.url
1138+
const method = (init?.method ?? "GET").toUpperCase()
1139+
requests.push({ method, url })
1140+
if (method === "GET" && url.includes("/datamate-project-bindings/by-"))
1141+
return new Response(
1142+
JSON.stringify({
1143+
// Only the name differs; the identifiers match the recorded row, so
1144+
// the notification can be attributed to the rename alone.
1145+
binding: {
1146+
id: 1,
1147+
datamate_id: 42,
1148+
datamate_name: "Growth (renamed)",
1149+
repo_remote: "[email protected]:acme/app.git",
1150+
project_path: projectDir,
1151+
},
1152+
datamate: { id: 42, name: "Growth (renamed)" },
1153+
}),
1154+
{ status: 200, headers: { "content-type": "application/json" } },
1155+
)
1156+
return originalFetch3(input, init)
1157+
}) as typeof fetch
1158+
let notified = 0
1159+
const unsubscribe = onBindingChanged(() => notified++)
1160+
try {
1161+
const outcome = await resolveBindingOutcome(projectDir)
1162+
expect(outcome.status).toBe("bound")
1163+
if (outcome.status === "bound") expect(outcome.binding.datamateName).toBe("Growth (renamed)")
1164+
expect(notified).toBe(1)
1165+
} finally {
1166+
unsubscribe()
1167+
globalThis.fetch = originalFetch3
1168+
}
1169+
})
1170+
})
1171+
10951172
describe("the poller coalesces overlapping misses", () => {
10961173
test("two refreshes on a cold memo put one request on the wire", async () => {
10971174
// A remount while a slow refresh is still out started a second one; both

0 commit comments

Comments
 (0)