diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b24342..d87965c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. ## Unreleased - OpenCode 1, OpenCode 2 and Pi: when shared routing reports that every account is at its concurrent-request limit, requests wait for a free slot instead of ending the turn. +- OpenCode: the one-time state move no longer treats a running older plugin as gone after the system clock is corrected forward. A start with a different XDG_STATE_HOME no longer moves the state while an earlier move under another state folder is unfinished; it stops and says to start again with the setting used then. ## 2.16.6 diff --git a/packages/core/src/holder-registry.ts b/packages/core/src/holder-registry.ts index a0217d6a..990b3aca 100644 --- a/packages/core/src/holder-registry.ts +++ b/packages/core/src/holder-registry.ts @@ -426,24 +426,29 @@ export function recordPredatesBoot( } /** - * Whether an entry's process may still be running. An entry from before - * this boot or a dead pid is stale. Otherwise an unreadable incarnation - * counts as alive; only a different incarnation clears a live pid. + * Whether an entry's process may still be running. A dead pid is stale. + * When the entry's incarnation and the pid's current one are both known, + * they decide: equal is the same process, different is a reused pid. Only + * when the incarnation cannot settle it does a registration from before + * this boot count as stale. That rule reads the wall clock, which can be + * corrected forward while a process runs, so it must never override a + * matching incarnation. */ export async function holderEntryIsLive( entry: Pick & { registeredAt?: unknown }, liveness: HolderLiveness = defaultLiveness, ): Promise { - if (recordPredatesBoot(entry.registeredAt, liveness)) return false if (!liveness.pidAlive(entry.pid)) return false - if (entry.incarnation === null) return true - let current: string | null - try { - current = await liveness.incarnation(entry.pid) - } catch { - current = null + if (entry.incarnation !== null) { + let current: string | null + try { + current = await liveness.incarnation(entry.pid) + } catch { + current = null + } + if (current !== null) return current === entry.incarnation } - return current === null || current === entry.incarnation + return !recordPredatesBoot(entry.registeredAt, liveness) } export interface HolderFileContents { diff --git a/packages/core/src/state-layout-decision.ts b/packages/core/src/state-layout-decision.ts index 82554614..e55f64fa 100644 --- a/packages/core/src/state-layout-decision.ts +++ b/packages/core/src/state-layout-decision.ts @@ -1266,6 +1266,15 @@ async function underLayoutLock( await acquireHolderLocks(dataset, ctx) if (!relocationMoveEnabled(options)) return stay([RELOCATION_MOVE_DISABLED_REASON], false) + // Before this start snapshots the old files for a move of its own: a + // journal another move set aside means that move is unfinished and + // recorded in another state folder. + const foreign = await foreignMovingJournals(dataset) + if (foreign === undefined) + return stay([ + `${dataset.oldDir} can't be listed, so a move another state folder left unfinished can't be ruled out`, + ]) + if (foreign.length) moveUnfinishedElsewhere(dataset, foreign) const holdersMark = ctx.stack.size const files = [...dataset.slots.flatMap((slot) => [slot.from, slot.to])] const artifacts = @@ -1351,6 +1360,51 @@ async function stateLayoutFenceStep(ctx: StateLayoutTransitionContext) { await ctx.onStep?.('fence-checked') } +/** + * Journals in the config folder that a move set aside + * (`.moving-`), or undefined when the folder can't be + * listed. Called with the old folder's holder lock held, when this start's + * state folder records no unfinished move of its own, so any such journal + * belongs to a move whose record is in another state folder: a start under + * another `XDG_STATE_HOME` (or HOME) that stopped before writing its + * relocation tombstones: the small files written over the old runtime files + * that point older plugins at the new folder. + * A new move here would find no journal, move without one and retire the + * old files, leaving that move unable to roll back and this one without + * the journal local accounts need. + */ +async function foreignMovingJournals( + dataset: RelocationDataset, +): Promise { + const journal = dataset.oldPaths.journal + let names: string[] + try { + names = await readdir(dirname(journal)) + } catch { + return undefined + } + return names + .filter((name) => isMovingJournalName(basename(journal), name)) + .sort() + .map((name) => join(dirname(journal), name)) +} + +/** + * Refuse to move while another state folder's move is unfinished. Nothing + * of that move is removed or adopted: only a start with its state folder + * can finish or roll it back. + */ +function moveUnfinishedElsewhere( + dataset: RelocationDataset, + movingJournals: readonly string[], +): never { + refuse( + 'move-unfinished-elsewhere', + `An earlier move of anthropic-auth state for ${dataset.oldDir} did not finish: it set the journal aside as ${movingJournals.join(' and ')}, and its record is not in ${dataset.sub}, the state folder this process uses. Start anthropic-auth again with the XDG_STATE_HOME (and HOME) that were set then, so that move finishes or rolls back; to keep the old layout afterwards, run ${RESTORE_LEGACY_COMMAND} with that same setting. Nothing was changed.`, + [dataset.oldDir, ...movingJournals, dataset.sub], + ) +} + /** * Decisions made in this process, by everything that selects the dataset. * A host may initialise its plugin more than once in one process; each diff --git a/packages/core/src/state-layout-errors.ts b/packages/core/src/state-layout-errors.ts index 48c8e880..931cdac8 100644 --- a/packages/core/src/state-layout-errors.ts +++ b/packages/core/src/state-layout-errors.ts @@ -8,6 +8,11 @@ export type StateLayoutRefusalCode = | 'conflict' /** The dataset was moved under another state root (`XDG_STATE_HOME`). */ | 'moved-elsewhere' + /** + * A move recorded under another state root stopped part way, leaving the + * journal set aside in the config folder. + */ + | 'move-unfinished-elsewhere' /** A marker or tombstone belongs to a different config folder or dataset. */ | 'other-dataset' /** `layout.json` exists but can't be read or parsed, or is missing after a move. */ @@ -41,6 +46,7 @@ const PUBLIC_MESSAGES: Record = { conflict: 'anthropic-auth found two copies of the same account state and stopped using both so a refresh token is never used twice. The log names both files: keep the copy you trust, move the other one away, then restart OpenCode.', 'moved-elsewhere': `anthropic-auth state for this config folder was moved under another state folder (XDG_STATE_HOME). Restore XDG_STATE_HOME, or run ${RESTORE_LEGACY_COMMAND} with the old XDG_STATE_HOME first. The log names both folders.`, + 'move-unfinished-elsewhere': `An earlier move of anthropic-auth state for this config folder did not finish, and its record is in another state folder. Start again with the XDG_STATE_HOME (and HOME) that were set then, so that move finishes or rolls back; to keep the old layout afterwards, run ${RESTORE_LEGACY_COMMAND} with that same setting. The log names the journal the move set aside.`, 'other-dataset': "anthropic-auth's state folder belongs to another config folder. Check OPENCODE_CONFIG_DIR and any symlink to the config folder; the log names both folders.", 'marker-unreadable': diff --git a/packages/core/src/tests/holder-registry.test.ts b/packages/core/src/tests/holder-registry.test.ts index 77865af2..5256ea61 100644 --- a/packages/core/src/tests/holder-registry.test.ts +++ b/packages/core/src/tests/holder-registry.test.ts @@ -295,6 +295,71 @@ test('an unreadable incarnation counts as alive and a matching one is never clea ).toBe(false) }) +test('a matching incarnation keeps a holder live after the wall clock is corrected forward', async () => { + // The process registered one minute after boot while the wall clock was an + // hour slow. Two hours later the clock has been corrected, so the recorded + // time now looks older than this boot. + const boot = Date.UTC(2026, 0, 2, 11) + const registeredAt = boot + 60_000 - 3_600_000 + const now = boot + 2 * 3_600_000 + const clock = { now: () => now, uptime: () => 2 * 3_600 } + const pid = 910020 + const at = (incarnation: string | null): HolderLiveness => ({ + ...liveness({ incarnations: { [pid]: incarnation } }), + ...clock, + }) + const entry = { pid, incarnation: 'started-once', registeredAt } + + expect(await holderEntryIsLive(entry, at('started-once'))).toBe(true) + // A known different incarnation is a reused pid. + expect(await holderEntryIsLive(entry, at('another'))).toBe(false) + // Without a provable incarnation the before-this-boot rule decides. + expect(await holderEntryIsLive(entry, at(null))).toBe(false) + expect( + await holderEntryIsLive( + { ...entry, incarnation: null }, + at('started-once'), + ), + ).toBe(false) + // A dead pid is stale whatever its incarnation. + expect( + await holderEntryIsLive(entry, { + ...at('started-once'), + pidAlive: () => false, + }), + ).toBe(false) + // Missing or unusable times keep the entry when nothing else proves it gone. + for (const time of [undefined, 'soon', -1, now + 60_000]) + expect( + await holderEntryIsLive( + { pid, incarnation: null, registeredAt: time }, + at(null), + ), + ).toBe(true) + + // The next locked write keeps the live entry instead of pruning it. + const dir = await folder('opencode') + const paths = await dataset(dir) + const holder = { + ...entry, + instance: 'registered-before-the-clock-step', + role: 'opencode2', + release: '2.16.5', + kind: 'legacy', + identity: dir, + files: nativeHolderDatasetFiles(paths), + } + await writeFile( + join(dir, HOLDER_FILE_NAME), + JSON.stringify({ version: 1, entries: [holder] }), + ) + await register(paths, { liveness: at('started-once'), now: () => now }) + expect((await holders(dir)).entries.map((value) => value.pid)).toEqual([ + pid, + process.pid, + ]) +}) + test('a malformed holder file is never overwritten; an ordinary process keeps serving, logs once and retries', async () => { const dir = await folder('opencode') const paths = await dataset(dir) diff --git a/packages/core/src/tests/state-layout-move.test.ts b/packages/core/src/tests/state-layout-move.test.ts index 36e79241..6d6490f2 100644 --- a/packages/core/src/tests/state-layout-move.test.ts +++ b/packages/core/src/tests/state-layout-move.test.ts @@ -18,7 +18,7 @@ import { writeFile, } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { withLock } from '@cortexkit/common-auth/fs' import type { OAuthQuotaSnapshot } from '../accounts.ts' import type { ProviderAccountUuid } from '../claude-code.ts' @@ -27,6 +27,7 @@ import { type HolderLiveness, HolderRegistrationError, resetNativeHolderRegistryForTests, + stateRefusalPublicMessage, } from '../holder-registry.ts' import type { PreNArtifactLocations } from '../layout-fence.ts' import { __setLogTestSink, type LogTestRecord } from '../logger.ts' @@ -54,7 +55,10 @@ import { type StateLayoutDecision, unmovedRegistrationPolicy, } from '../state-layout-decision.ts' -import { StateLayoutRefusalError } from '../state-layout-errors.ts' +import { + StateLayoutRefusalError, + stateLayoutRefusalPublicMessage, +} from '../state-layout-errors.ts' import { defaultStateLayoutFs, type StateLayoutFs, @@ -1775,6 +1779,74 @@ test('a start under another XDG_STATE_HOME that waited for the old holder lock w ) }) +test('a start under another XDG_STATE_HOME refuses while a move to the usual state folder stopped after setting the journal aside', async () => { + const m = await machine() + const otherRoot = join(m.root, 'other-state') + const otherSub = join(otherRoot, 'cortexkit', 'anthropic-auth', 'opencode') + // The first mover stops after setting the journal aside, before either + // runtime tombstone: only its own state folder records the move. + await expect( + decide(m, { onStep: crashAt('journal-set-aside') }), + ).rejects.toBeInstanceOf(StateLayoutCrash) + const record = await readStateLayoutRecord(m.sub) + expect(record?.phase).toBe('preparing') + const moving = `${m.oldPaths.journal}.moving-${record?.attempt}` + expect(await exists(moving)).toBe(true) + expect(await exists(m.oldPaths.journal)).toBe(false) + const before = await oldTree(m) + + // A second start with another state folder must not move the dataset + // without its journal, or adopt or remove the other attempt's files. + const second = decide(m, { env: { XDG_STATE_HOME: otherRoot } }) + await expect(second).rejects.toMatchObject({ + code: 'move-unfinished-elsewhere', + }) + await expect(second).rejects.toThrow(moving) + const refusal = await second.catch((error: unknown) => error) + expect(refusal).toBeInstanceOf(StateLayoutRefusalError) + const shown = stateRefusalPublicMessage(refusal) + expect(shown).toBe( + stateLayoutRefusalPublicMessage('move-unfinished-elsewhere'), + ) + expect(shown).not.toContain(record?.attempt as string) + expect(await oldTree(m)).toEqual(before) + expect(await readFile(moving, 'utf8')).toBe(m.original.journal as string) + expect(await readRelocationPointer(m.oldPaths.runtime)).toBeUndefined() + expect(await exists(join(otherSub, 'layout.json'))).toBe(false) + expect(processStateLayout(m.oldPaths.legacyConfig)).toBe(LEGACY_STATE_LAYOUT) + + // The original setting rolls the first move back and then finishes a move. + expect((await decide(m)).kind).toBe('state-home') + expect(await exists(moving)).toBe(false) + expect(await readFile(m.newPaths.journal, 'utf8')).toBe( + m.original.journal as string, + ) + expect(await usableCopies(m)).toEqual(['state-home']) +}) + +test('under another XDG_STATE_HOME, a start recovers its own move that stopped after setting the journal aside', async () => { + const m = await machine() + const otherRoot = join(m.root, 'other-state') + const otherSub = join(otherRoot, 'cortexkit', 'anthropic-auth', 'opencode') + const env = { XDG_STATE_HOME: otherRoot } + await expect( + decide(m, { env, onStep: crashAt('journal-set-aside') }), + ).rejects.toBeInstanceOf(StateLayoutCrash) + const record = await readStateLayoutRecord(otherSub) + expect(record?.phase).toBe('preparing') + const moving = `${m.oldPaths.journal}.moving-${record?.attempt}` + expect(await exists(moving)).toBe(true) + + // Its own preparing record rolls the journal back before the check runs. + const decision = await decide(m, { env }) + expect(decision.kind).toBe('state-home') + expect(decision.layout).toEqual({ kind: 'state-home', dir: otherSub }) + expect(await exists(moving)).toBe(false) + expect( + await readFile(join(otherSub, basename(m.oldPaths.journal)), 'utf8'), + ).toBe(m.original.journal as string) +}) + test('a state-home process whose registration fails refuses and never falls back to legacy', async () => { const m = await machine() expect((await decide(m)).kind).toBe('state-home')