From e4a1a52e5b6baccb7bf0e1df1c2f3bbaeffc49e3 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 20:28:52 +0800 Subject: [PATCH 1/2] fix(account): unify account RW mirror, temp-park SSOT, and sorted PG UNNEST writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前: - A1/A9:`removeVmFromDb` 未清理 `_pgPendingVms` 且同步删除与 `_pgFlushChain` 异步 PG UPSERT 竞态,删槽后行可能被回写复活;`clearActiveVmFromDb` 不重置 `_lastActiveVmId` / `_pgPendingActive` 且未串入 `_pgFlushChain`。 - A2/A3/A13:`markVmAuthCooldown` / `clearClaudeAuthCooldown` 仅读写 `vm.claude.temp_unschedulable_*`,顶层过期值会遮蔽新冷却;`markVmRestriction` / `clearVmQuotaRestriction` / `clearRecoverableVmCooldown` / `bindVmProxy` / `persistVmTimezone` 写入缺少 `{ mode: 0o600 }`;`getVm` 与 `health-probe` 直接读静态 `vm.json` 或忽略顶层/合并后的 `codex_slot_runtime`。 - A5/A6/A7/A8/A10/A11/A12:`atomicWriteJson` hook 仅传路径导致 `syncVmFile` 重复读盘解析;`syncCodexQuotaSchedule` 在 local 限制下连续两次 RMW;`vm-registry` 内 13 处 `persist*` 重复 RMW 模板;`readFileCached` 未用 `bigint` `statSignature`;`vms-repo` / `vm-db-sync` 仍读写与解密死列 `access_token`/`refresh_token`/`session_key`;`reconcileVms` 循环 N 次 `r.get` 且两次 `r.list`;hook / mirror 异常被静默吞掉;存在零引用导出 `isVmJsonPath`、`persistSlotEnginePolicyMany`。 - PG9:`api-keys._applyUsageBatchToPg` 与 `rate-limit-service._applyWindowBatchToPg` 未按主键排序有跨实例 `40P01` 死锁风险,且 `api-keys` 使用变长 `VALUES`。 - 改后: - `src/lib/vm/vm-db-sync.mjs`:`removeVmFromDb` 清理 `_pgPendingVms` 并将 PG `DELETE FROM vms WHERE id = $1` 串入 `_pgFlushChain`(含 `_pgPendingDeletes` 防失败回队复活);`clearActiveVmFromDb` 重置 `_lastActiveVmId` / `_pgPendingActive` 并串入 `_pgFlushChain`;`reconcileVms` 改单次 `SELECT id, file_mtime_ms FROM vms` + 单次 `r.list()`;`syncVmFile` 接受 hook 透传对象跳过重复 `readFileSync + JSON.parse`;移除 3 个死列写入并修正头注释;新增失败计数与按 id 限频 warn;去掉 `isVmJsonPath` 导出。 - `src/lib/db/repos/vms-repo.mjs`:停止读写与 `maybeDecrypt` 3 个死令牌列(不改 schema,保持解码对象兼容空值)。 - `src/lib/vm/vm-file.mjs`:`atomicWriteJson` / `writeJsonIfChanged` 透传对象至 `notifyVmWrite`;`readFileCached` 复用 `statSync(file, { bigint: true })` + `statSignature`;hook 异常计入失败计数并按路径限频 warn。 - `src/lib/oauth/oauth-credentials.mjs`:新增 `readVmTempPark` / `setVmTempPark` / `clearVmTempPark` SSOT 辅助,统一双处同步读写与 `until <= now` 双删,并补齐 3 处 `{ mode: 0o600 }`。 - `src/lib/vm/vm-registry.mjs`:13 处 `persist*` 收敛复用 `patchVmRecord`(统一 `0o600`,修复 `bindVmProxy` / `persistVmTimezone` 权限);合并 `syncCodexQuotaSchedule` 连续 RMW 为单次写入;导出 `mergeVmRuntime` 并让 `getVm` 默认叠加活跃 `CodexRuntimeStore`;移除零引用 `persistSlotEnginePolicyMany` 及孤立测试。 - `src/lib/admin/health-probe.mjs`:`isHealthProbeTarget` 改用 `mergeVmRuntime` + `readVmTempPark` 统一读取运行态冷却与刷票错误。 - `src/lib/admin/api-keys.mjs` & `src/lib/pool/rate-limit-service.mjs`:PG 批量写按 `keyId` / `accountId` 字典序排序,并将 `api-keys._applyUsageBatchToPg` 切换为固定 10 参 `UNNEST`。 - 未改 / 延后:不做 `vms` 表 `DROP COLUMN` 迁移;未触碰调度器禁区(`scheduler/`、`src/lib/scheduler/`、`src/lib/pool/availability.mjs`、`src/lib/pool/pool-scheduler.mjs`)、`src/lib/admin/panel-routes.mjs`、`CHANGELOG.md`、system 提示词域与 AFO 域。 ## 验收记录(Run) - 环境与基线:WSL2 Debian + Windows git.exe,工作树 `X:\vm2api-wt-r3-acct-rw`,基于 `origin/dev` `7870fa8d5` - 已跑命令与结果: - `npx biome format --write <17 changed .mjs files> && npx biome check <17 changed .mjs files>`: PASS (17 files clean, 0 errors) - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS (0 syntax errors) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci`: PASS (13/13 isolated test files, 247/247 tests pass, 0 fail) - `node --test --test-concurrency=4 test/unit/{vm-db-sync,vm-file,oauth-credentials,api-keys,rate-limit-service,proxy-pool-bind,schedule-state-registry,request-redis-opt,panel-vm-delete,panel-vm-deactivate,panel-vm-active-hours,panel-vm-pool-policy,health-probe,vm-rename,slot-engine,runtime-state,backup-service,legacy-import}.test.mjs`: PASS (18 files, 268/268 tests pass, 0 fail) - `VM2API_TEST_PG_URL='postgresql://vm2api:testpass@127.0.0.1:55433/vm2api' node --test test/unit/request-redis-opt.test.mjs test/unit/pg-repos-parity.test.mjs`: PASS (17/17 tests pass on real PostgreSQL 18, 0 fail, 0 skipped) ## 回退与手破验证(Broken by hand) - 回退 A1 `removeVmFromDb`(不清 `_pgPendingVms` 且直接走 `r.remove`)-> `PG mode removeVmFromDb cancels pending upsert and chains DELETE behind in-flight flush (A1/A8)` FAIL(`AssertionError [ERR_ASSERTION]: queued upsert must not resurrect deleted slot (true !== false)`)-> 恢复后 PASS - 回退 A2 `markVmAuthCooldown`(仅写 `vm.claude.*` 留顶层过期值)-> `temp park SSOT keeps claude.* and top-level identical across expired quota -> auth cooldown and writes 0600 (A2/A3)` FAIL(`AssertionError [ERR_ASSERTION]: top-level until must match claude.* after auth cooldown (1796127785079 !== 1796128145079)`)-> 恢复后 PASS - 回退 A3 `markVmRestriction`(移除 `{ mode: 0o600 }`)-> `temp park SSOT keeps claude.* and top-level identical across expired quota -> auth cooldown and writes 0600 (A2/A3)` FAIL(`AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 420 !== 384`)-> 恢复后 PASS ## 真实使用(Real use) - 在本地 WSL 临时隔离 `postgres:18-alpine` 容器(仅监听 `127.0.0.1:55433`,测后自动 `docker rm -f` 销毁)实跑 `request-redis-opt.test.mjs` 与 `pg-repos-parity.test.mjs`,实测验证固定 10 参 `UNNEST` 批量更新 `api_keys`(含 NULL/空串/ISO 窗口)与 `VmsRepo` 停写死列后的 SQLite↔PG18 双后端一致性(17/17 PASS);实跑 `kin-scheduler` 真实 Rust 调度器二进制通过 `test:ci` 全部 13 个隔离套件。未连接生产机 `ph24`。 ## 未运行项(Not run) - 未运行全量 556 文件 `npm run test:unit`、Web 前端构建、ARM64 与生产机 `ph24` 联调:本次改动严格限定于 Node 后端账户读写与 PG 批量写 8 个文件,已通过 `test:ci`(13 套件 / 247 用例)、全部 18 个关联单测(268 用例)与真实 PG18 集成一致性验证(17 用例)。 --- src/lib/admin/api-keys.mjs | 69 ++++-- src/lib/admin/health-probe.mjs | 32 +-- src/lib/db/repos/vms-repo.mjs | 29 ++- src/lib/oauth/oauth-credentials.mjs | 156 +++++++++---- src/lib/pool/rate-limit-service.mjs | 8 +- src/lib/vm/vm-db-sync.mjs | 181 +++++++++++---- src/lib/vm/vm-file.mjs | 66 ++++-- src/lib/vm/vm-registry.mjs | 317 +++++++++++--------------- test/unit/health-probe.test.mjs | 70 ++++++ test/unit/oauth-credentials.test.mjs | 114 +++++++++ test/unit/pool-scheduler.test.mjs | 9 +- test/unit/proxy-pool-bind.test.mjs | 26 ++- test/unit/rate-limit-service.test.mjs | 27 +++ test/unit/request-redis-opt.test.mjs | 18 +- test/unit/slot-engine.test.mjs | 20 +- test/unit/vm-db-sync.test.mjs | 176 +++++++++++++- test/unit/vm-file.test.mjs | 55 +++++ 17 files changed, 1007 insertions(+), 366 deletions(-) diff --git a/src/lib/admin/api-keys.mjs b/src/lib/admin/api-keys.mjs index 16017a1d58..b79cdd8b18 100644 --- a/src/lib/admin/api-keys.mjs +++ b/src/lib/admin/api-keys.mjs @@ -1564,24 +1564,32 @@ export class ApiKeyStore { } async _applyUsageBatchToPg(pgPool, entries, nowIsoStr) { - const params = [nowIsoStr] - const tuples = [] - for (const entry of entries) { - const base = params.length + 1 - params.push( - String(entry.keyId), - Math.round(Number(entry.requests) || 0), - Math.round(Number(entry.quota_requests_used) || 0), - Math.round(Number(entry.tokens_in) || 0), - Math.round(Number(entry.tokens_out) || 0), - Math.round(Number(entry.cache_read_tokens) || 0), - Math.round(Number(entry.cache_creation_tokens) || 0), - Number(entry.cost) || 0, - entry.last_used_at ? String(entry.last_used_at) : nowIsoStr, - ) - tuples.push( - `($${base}::text, $${base + 1}::bigint, $${base + 2}::bigint, $${base + 3}::bigint, $${base + 4}::bigint, $${base + 5}::bigint, $${base + 6}::bigint, $${base + 7}::double precision, $${base + 8}::text)`, - ) + if (!Array.isArray(entries) || entries.length === 0) return [] + // Sort deterministically by primary key to prevent cross-instance 40P01 deadlocks. + const sorted = [...entries].sort((a, b) => { + const ka = String(a.keyId) + const kb = String(b.keyId) + return ka < kb ? -1 : ka > kb ? 1 : 0 + }) + const ids = [] + const requests = [] + const quotaRequestsUsed = [] + const tokensIn = [] + const tokensOut = [] + const cacheReadTokens = [] + const cacheCreationTokens = [] + const costs = [] + const lastUsedAts = [] + for (const entry of sorted) { + ids.push(String(entry.keyId)) + requests.push(Math.round(Number(entry.requests) || 0)) + quotaRequestsUsed.push(Math.round(Number(entry.quota_requests_used) || 0)) + tokensIn.push(Math.round(Number(entry.tokens_in) || 0)) + tokensOut.push(Math.round(Number(entry.tokens_out) || 0)) + cacheReadTokens.push(Math.round(Number(entry.cache_read_tokens) || 0)) + cacheCreationTokens.push(Math.round(Number(entry.cache_creation_tokens) || 0)) + costs.push(Number(entry.cost) || 0) + lastUsedAts.push(entry.last_used_at ? String(entry.last_used_at) : nowIsoStr) } const sql = ` UPDATE api_keys AS k @@ -1640,11 +1648,32 @@ export class ApiKeyStore { ELSE COALESCE(k.last_used_at, $1::text) END, updated_at = $1::text - FROM (VALUES ${tuples.join(', ')}) AS v(id, requests, quota_requests_used, tokens_in, tokens_out, cache_read_tokens, cache_creation_tokens, cost, last_used_at) + FROM UNNEST( + $2::text[], + $3::bigint[], + $4::bigint[], + $5::bigint[], + $6::bigint[], + $7::bigint[], + $8::bigint[], + $9::double precision[], + $10::text[] + ) AS v(id, requests, quota_requests_used, tokens_in, tokens_out, cache_read_tokens, cache_creation_tokens, cost, last_used_at) WHERE k.id = v.id AND k.deleted_at IS NULL RETURNING k.* ` - const res = await pgPool.query(sql, params) + const res = await pgPool.query(sql, [ + nowIsoStr, + ids, + requests, + quotaRequestsUsed, + tokensIn, + tokensOut, + cacheReadTokens, + cacheCreationTokens, + costs, + lastUsedAts, + ]) return Array.isArray(res?.rows) ? res.rows : [] } diff --git a/src/lib/admin/health-probe.mjs b/src/lib/admin/health-probe.mjs index 24ca9a98bb..1a83253417 100644 --- a/src/lib/admin/health-probe.mjs +++ b/src/lib/admin/health-probe.mjs @@ -10,7 +10,8 @@ */ import crypto from 'node:crypto' import { verifyDirectClaudeCodeHeaders, verifyOfficialClaudeCode } from '../identity/official-cc-verifier.mjs' -import { vmHasClaudeCredential } from '../vm/vm-registry.mjs' +import { mergeVmRuntime, vmHasClaudeCredential } from '../vm/vm-registry.mjs' +import { readVmTempPark } from '../oauth/oauth-credentials.mjs' import { isValidVmId } from '../vm/vm-file.mjs' import { activeHoursOf, evaluateActiveHours } from '../pool/active-hours.mjs' import { slotAllowsModel } from '../pool/slot-model-gate.mjs' @@ -1047,32 +1048,35 @@ export function formatHealthSse(protocol, inbound, snapshot, cfg = DEFAULT_HEALT } const HARD_UNAVAILABLE = new Set(['stopped', 'dead', 'error', 'disabled']) +const AUTH_PARK_REASON_RE = /authentication_failed|invalid_grant|oauth_invalid_grant|oauth_revoked/i function isHealthProbeTarget(vm, now = Date.now()) { if (!vm) return false - if (vm.schedulable === false) return false - const status = String(vm.status || '').toLowerCase() + const effective = mergeVmRuntime(vm) + if (effective.schedulable === false) return false + const status = String(effective.status || '').toLowerCase() if (HARD_UNAVAILABLE.has(status)) return false - const grantErr = String(vm.claude?.refresh_error || vm.refresh_error || vm.schedule_disabled_reason || '') + const grantErr = String( + effective.claude?.refresh_error || effective.refresh_error || effective.schedule_disabled_reason || '', + ) if ( /invalid_grant|refresh token not found|oauth_revoked|token has been revoked|token_revoked|invalidated oauth token/i.test( grantErr, ) ) return false - const coolUntil = Number(vm.cooldown_until || vm.claude?.temp_unschedulable_until) || 0 - if ( - coolUntil > now && - /authentication_failed|invalid_grant|oauth_invalid_grant|oauth_revoked/i.test( - String(vm.cooldown_reason || vm.claude?.temp_unschedulable_reason || ''), - ) - ) { + const park = readVmTempPark(effective, { now }) + const accountCoolUntil = Number(effective.cooldown_until) || 0 + if (accountCoolUntil > now && AUTH_PARK_REASON_RE.test(String(effective.cooldown_reason || park.reason || ''))) { + return false + } + if (park.active && AUTH_PARK_REASON_RE.test(String(park.reason || effective.cooldown_reason || ''))) { return false } // Off-shift slots take no real traffic, probes included (a probe is a pinned real chat). - if (!evaluateActiveHours(activeHoursOf(vm), now, vm.timezone).active) return false - if (vm.claude) return vmHasClaudeCredential(vm) - return !!(vm.has_token || vm.has_refresh) + if (!evaluateActiveHours(activeHoursOf(effective), now, effective.timezone).active) return false + if (effective.claude) return vmHasClaudeCredential(effective) + return !!(effective.has_token || effective.has_refresh) } export function selectHealthProbeTargets(vms = [], cfg = DEFAULT_HEALTH_PROBE, now = Date.now(), platform = null) { diff --git a/src/lib/db/repos/vms-repo.mjs b/src/lib/db/repos/vms-repo.mjs index 11bf8e0855..9e7200383a 100644 --- a/src/lib/db/repos/vms-repo.mjs +++ b/src/lib/db/repos/vms-repo.mjs @@ -14,6 +14,9 @@ import { normalizeOwnerId, vmOriginOf } from '../../admin/resource-owner.mjs' import { isCodexVm } from '../../vm/vm-kind.mjs' const ACTIVE_VM_KEY = 'active_vm' +const LIVE_VM_COLUMNS = `id, name, status, schedulable, email, account_uuid, org_uuid, + oauth_expires_at, oauth_source, proxy_id, claude_code_version, timezone, locale, + owner_user_id, origin, vm_json, encrypted, file_mtime_ms, synced_at, created_at, updated_at` function stripCodexSecrets(codex) { if (!codex || typeof codex !== 'object') return codex @@ -58,9 +61,6 @@ export function buildSafeVmRowParams(vm, mtimeMs = null, now = new Date().toISOS email, account_uuid: accountUuid, org_uuid: orgUuid, - access_token: null, - refresh_token: null, - session_key: null, oauth_expires_at: expiresRaw != null && expiresRaw !== '' ? String(expiresRaw) : null, oauth_source: oauthSource, proxy_id: vm.proxy?.id ?? null, @@ -82,22 +82,21 @@ export class VmsRepo { constructor(db = getDb()) { this.db = db this.settings = new SettingsRepo(db) - this._get = db.prepare('SELECT * FROM vms WHERE id = ?') - this._list = db.prepare('SELECT * FROM vms ORDER BY id') + this._get = db.prepare(`SELECT ${LIVE_VM_COLUMNS} FROM vms WHERE id = ?`) + this._list = db.prepare(`SELECT ${LIVE_VM_COLUMNS} FROM vms ORDER BY id`) this._remove = db.prepare('DELETE FROM vms WHERE id = ?') this._upsert = db.prepare(` INSERT INTO vms ( id, name, status, schedulable, email, account_uuid, org_uuid, - access_token, refresh_token, session_key, oauth_expires_at, oauth_source, + oauth_expires_at, oauth_source, proxy_id, claude_code_version, timezone, locale, owner_user_id, origin, vm_json, encrypted, file_mtime_ms, synced_at, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, status = excluded.status, schedulable = excluded.schedulable, email = excluded.email, account_uuid = excluded.account_uuid, org_uuid = excluded.org_uuid, - access_token = excluded.access_token, refresh_token = excluded.refresh_token, - session_key = excluded.session_key, oauth_expires_at = excluded.oauth_expires_at, + oauth_expires_at = excluded.oauth_expires_at, oauth_source = excluded.oauth_source, proxy_id = excluded.proxy_id, claude_code_version = excluded.claude_code_version, timezone = excluded.timezone, locale = excluded.locale, owner_user_id = excluded.owner_user_id, origin = excluded.origin, @@ -119,9 +118,6 @@ export class VmsRepo { p.email, p.account_uuid, p.org_uuid, - p.access_token, - p.refresh_token, - p.session_key, p.oauth_expires_at, p.oauth_source, p.proxy_id, @@ -140,7 +136,7 @@ export class VmsRepo { return this.get(vm.id) } - /** Returns {row, vm} — row has decrypted credential columns, vm is the parsed vm.json. */ + /** Returns decoded VM mirror metadata + parsed vm.json (token columns are never read or persisted). */ get(id) { return this._decode(this._get.get(id)) } @@ -192,9 +188,10 @@ export class VmsRepo { email: row.email, account_uuid: row.account_uuid, org_uuid: row.org_uuid, - access_token: maybeDecrypt(row.access_token), - refresh_token: maybeDecrypt(row.refresh_token), - session_key: maybeDecrypt(row.session_key), + // Compatibility shape: legacy token columns remain NULL in schema and are never read/decrypted. + access_token: null, + refresh_token: null, + session_key: null, oauth_expires_at: row.oauth_expires_at, oauth_source: row.oauth_source, proxy_id: row.proxy_id, diff --git a/src/lib/oauth/oauth-credentials.mjs b/src/lib/oauth/oauth-credentials.mjs index ec1ed26d56..7794e524a8 100644 --- a/src/lib/oauth/oauth-credentials.mjs +++ b/src/lib/oauth/oauth-credentials.mjs @@ -891,7 +891,7 @@ export function persistOauthToVm(vmPath, cred, { acceptLiveGrant = false, operat vm.claude.refresh_error = null vm.claude.refreshed_at = new Date().toISOString() vm.claude._token_version = n._token_version || Date.now() - clearClaudeAuthCooldown(vm.claude) + clearClaudeAuthCooldown(vm) restoreScheduleAfterLiveCredential(vm, { operatorImport }) vm.updated_at = new Date().toISOString() atomicWriteJson(vmPath, vm, { mode: 0o600 }) @@ -902,28 +902,108 @@ export function isQuotaParkReason(reason) { return /^quota_\d+[mhd]|account_quota_exhausted|^rate_limited$/i.test(String(reason || '')) } -function clearClaudeAuthCooldown(claude = {}) { - delete claude.temp_unschedulable_until - delete claude.temp_unschedulable_reason - delete claude.oauth_401_generation - return claude +function parseTempParkUntilMs(raw) { + if (raw == null || raw === '') return 0 + const n = Number(raw) + if (Number.isFinite(n) && n > 0) return Math.floor(n) + if (typeof raw === 'string') { + const parsed = Date.parse(raw) + if (Number.isFinite(parsed) && parsed > 0) return Math.floor(parsed) + } + return 0 } -/** Quota / 429 / account cooldown: same temp_unschedulable_* store as auth park. */ -export function markVmRestriction(vmPath, { until, reason } = {}) { - if (!vmPath || !fs.existsSync(vmPath)) return null - const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) +/** + * SSOT reader for temporary unschedulable / cooldown park fields on a VM record or summary. + * Prefers an active future deadline over an expired/stale mirror so legacy skewed records + * never mask a live park. + */ +export function readVmTempPark(vm, { now = Date.now() } = {}) { + if (!vm || typeof vm !== 'object') return { until: null, reason: null, active: false } + const claudeUntil = parseTempParkUntilMs(vm.claude?.temp_unschedulable_until) + const topUntil = parseTempParkUntilMs(vm.temp_unschedulable_until) + const claudeReason = String(vm.claude?.temp_unschedulable_reason || '').trim() || null + const topReason = String(vm.temp_unschedulable_reason || '').trim() || null + + let until = 0 + let reason = null + if (claudeUntil > now && topUntil > now) { + if (claudeUntil >= topUntil) { + until = claudeUntil + reason = claudeReason || topReason + } else { + until = topUntil + reason = topReason || claudeReason + } + } else if (claudeUntil > now) { + until = claudeUntil + reason = claudeReason || topReason + } else if (topUntil > now) { + until = topUntil + reason = topReason || claudeReason + } else { + until = claudeUntil || topUntil + reason = claudeReason || topReason + } + return { + until: until > 0 ? until : null, + reason, + active: until > now, + } +} + +/** + * SSOT writer for temporary unschedulable / cooldown park fields. + * Always keeps `vm.claude.temp_unschedulable_*` and top-level `vm.temp_unschedulable_*` + * identical, and deletes both `until` fields whenever `until <= now`. + */ +export function setVmTempPark(vm, { until = null, reason = null, now = Date.now() } = {}) { + if (!vm || typeof vm !== 'object') return vm vm.claude = { ...(vm.claude || {}) } - const untilMs = Number(until) || 0 - if (untilMs > Date.now()) { + const untilMs = parseTempParkUntilMs(until) + if (untilMs > now) { vm.claude.temp_unschedulable_until = untilMs vm.temp_unschedulable_until = untilMs + } else { + delete vm.claude.temp_unschedulable_until + delete vm.temp_unschedulable_until + } + const why = reason != null ? String(reason).trim() : '' + if (why) { + vm.claude.temp_unschedulable_reason = why + vm.temp_unschedulable_reason = why + } else { + delete vm.claude.temp_unschedulable_reason + delete vm.temp_unschedulable_reason + } + return vm +} + +/** SSOT clearer for temporary unschedulable / cooldown park fields across both mirrors. */ +export function clearVmTempPark(vm, { clearGeneration = false } = {}) { + if (!vm || typeof vm !== 'object') return vm + if (vm.claude && typeof vm.claude === 'object') { + vm.claude = { ...vm.claude } + delete vm.claude.temp_unschedulable_until + delete vm.claude.temp_unschedulable_reason + if (clearGeneration) delete vm.claude.oauth_401_generation } - const why = reason || 'restricted' - vm.claude.temp_unschedulable_reason = why - vm.temp_unschedulable_reason = why + delete vm.temp_unschedulable_until + delete vm.temp_unschedulable_reason + return vm +} + +function clearClaudeAuthCooldown(vm) { + return clearVmTempPark(vm, { clearGeneration: true }) +} + +/** Quota / 429 / account cooldown: same temp_unschedulable_* store as auth park. */ +export function markVmRestriction(vmPath, { until, reason } = {}) { + if (!vmPath || !fs.existsSync(vmPath)) return null + const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + setVmTempPark(vm, { until, reason: reason || 'restricted' }) vm.updated_at = new Date().toISOString() - atomicWriteJson(vmPath, vm) + atomicWriteJson(vmPath, vm, { mode: 0o600 }) return vm } @@ -931,15 +1011,11 @@ export function markVmRestriction(vmPath, { until, reason } = {}) { export function clearVmQuotaRestriction(vmPath) { if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - const reason = vm.claude?.temp_unschedulable_reason || vm.temp_unschedulable_reason - if (!isQuotaParkReason(reason)) return vm - vm.claude = { ...(vm.claude || {}) } - delete vm.claude.temp_unschedulable_until - delete vm.claude.temp_unschedulable_reason - delete vm.temp_unschedulable_until - delete vm.temp_unschedulable_reason + const park = readVmTempPark(vm) + if (!isQuotaParkReason(park.reason)) return vm + clearVmTempPark(vm) vm.updated_at = new Date().toISOString() - atomicWriteJson(vmPath, vm) + atomicWriteJson(vmPath, vm, { mode: 0o600 }) return vm } @@ -960,19 +1036,15 @@ function isRecoverableCooldownReason(reason) { export function clearRecoverableVmCooldown(vmPath) { if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - const reason = vm.claude?.temp_unschedulable_reason || vm.temp_unschedulable_reason - if (!isRecoverableCooldownReason(reason)) return vm - vm.claude = { ...(vm.claude || {}) } - delete vm.claude.temp_unschedulable_until - delete vm.claude.temp_unschedulable_reason - delete vm.temp_unschedulable_until - delete vm.temp_unschedulable_reason + const park = readVmTempPark(vm) + if (!isRecoverableCooldownReason(park.reason)) return vm + clearVmTempPark(vm) if (vm.codex?.extra?.codex_limited_until) { vm.codex = { ...vm.codex, extra: { ...vm.codex.extra } } delete vm.codex.extra.codex_limited_until } vm.updated_at = new Date().toISOString() - atomicWriteJson(vmPath, vm) + atomicWriteJson(vmPath, vm, { mode: 0o600 }) return vm } @@ -984,9 +1056,7 @@ export function markVmAuthCooldown( if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) vm.claude = stripCredentialSecrets({ ...(vm.claude || {}) }) - const untilMs = Number(until) || 0 - if (untilMs > Date.now()) vm.claude.temp_unschedulable_until = untilMs - vm.claude.temp_unschedulable_reason = reason || 'authentication_failed_after_refresh' + setVmTempPark(vm, { until, reason: reason || 'authentication_failed_after_refresh' }) if (generation != null && generation !== '') vm.claude.oauth_401_generation = generation vm.updated_at = new Date().toISOString() atomicWriteJson(vmPath, vm, { mode: 0o600 }) @@ -997,13 +1067,19 @@ export function markVmAuthCooldown( export function clearVmAuthCooldown(vmPath) { if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - if (!vm.claude) return vm - if (isQuotaParkReason(vm.claude.temp_unschedulable_reason || vm.temp_unschedulable_reason)) return vm + const park = readVmTempPark(vm) + if (isQuotaParkReason(park.reason)) return vm const had = - vm.claude.temp_unschedulable_until || vm.claude.temp_unschedulable_reason || vm.claude.oauth_401_generation + park.until || + park.reason || + vm.claude?.temp_unschedulable_until || + vm.claude?.temp_unschedulable_reason || + vm.temp_unschedulable_until || + vm.temp_unschedulable_reason || + vm.claude?.oauth_401_generation if (!had) return vm - vm.claude = stripCredentialSecrets({ ...vm.claude }) - clearClaudeAuthCooldown(vm.claude) + if (vm.claude && typeof vm.claude === 'object') vm.claude = stripCredentialSecrets({ ...vm.claude }) + clearClaudeAuthCooldown(vm) vm.updated_at = new Date().toISOString() atomicWriteJson(vmPath, vm, { mode: 0o600 }) return vm diff --git a/src/lib/pool/rate-limit-service.mjs b/src/lib/pool/rate-limit-service.mjs index 67e7606159..27e82d0b05 100755 --- a/src/lib/pool/rate-limit-service.mjs +++ b/src/lib/pool/rate-limit-service.mjs @@ -257,6 +257,12 @@ export class RateLimitService { async _applyWindowBatchToPg(pgPool, batch) { if (!batch.length) return 0 + // Sort deterministically by accountId to prevent cross-instance 40P01 deadlocks. + const sorted = [...batch].sort((a, b) => { + const ka = String(a.accountId) + const kb = String(b.accountId) + return ka < kb ? -1 : ka > kb ? 1 : 0 + }) const nowIso = new Date().toISOString() const ids = [] const vmIds = [] @@ -277,7 +283,7 @@ export class RateLimitService { const rtVmIds = [] const rtUpdated = [] - for (const w of batch) { + for (const w of sorted) { const id = String(w.accountId) const vmId = w.vmId ? String(w.vmId) : null const upd = w.updatedAt || nowIso diff --git a/src/lib/vm/vm-db-sync.mjs b/src/lib/vm/vm-db-sync.mjs index 66a5baafb7..cd81c0814f 100644 --- a/src/lib/vm/vm-db-sync.mjs +++ b/src/lib/vm/vm-db-sync.mjs @@ -1,10 +1,11 @@ /** - * VM/credential DB mirror — write-through + reconcile + fs.watch. + * VM metadata DB mirror — write-through + reconcile + fs.watch. * - * Policy (user requirement: credentials must live in the database): - * - vms/*.json stay the runtime single-writer surface (persistOauthToVm, - * CLI seed, execution context all read files — no behavior drift). - * - Every vm.json write is mirrored into the `vms` table: + * Policy (aligned with `vms-repo.mjs`): + * - `vms/*.json` stay the runtime metadata single-writer surface; live OAuth + * secrets stay strictly in the slot worker `credentials.json`. + * - Every vm.json write is mirrored into the `vms` table (non-secret metadata, + * identity, expiry, and credential presence flags only): * 1. write-through hook installed on vm-file.atomicWriteJson * 2. explicit syncVmFile() calls from writers that bypass vm-file * 3. startup reconcile: newer file → upsert; missing file + DB row → @@ -31,6 +32,8 @@ import { migrateScheduleFields, reclaimAssignedVms, repairSlotSmbios, repairVmPr const ACTIVE_VM_KEY = 'active_vm' const WATCH_DEBOUNCE_MS = 500 const PG_UPSERT_BATCH_CHUNK = 100 +const DB_SYNC_WARN_THROTTLE_MS = 30_000 +const DB_SYNC_WARN_CACHE_MAX = 1024 let _repo = null let _watcher = null @@ -42,10 +45,33 @@ let _lastActiveVmId = null let _pgPendingActive = undefined let _pgFlushScheduled = false let _pgFlushChain = Promise.resolve() +let _mirrorFailureCount = 0 const _lastSyncedMtime = new Map() // filePath -> Math.floor(mtimeMs) const _watchDirtyFiles = new Set() // base filenames changed inside vms/ const _pgPendingVms = new Map() // vmId -> { vm, mtimeMs } +const _pgPendingDeletes = new Set() // vmId currently queued for PG DELETE +const _lastWarnAtByKey = new Map() // `${op}:${id}` -> timestamp ms + +export function getVmDbSyncFailureCount() { + return _mirrorFailureCount +} + +function recordVmDbSyncFailure(key, op, err) { + _mirrorFailureCount += 1 + const id = String(key || 'unknown') + const throttleKey = `${op}:${id}` + const now = Date.now() + const last = _lastWarnAtByKey.get(throttleKey) || 0 + if (now - last >= DB_SYNC_WARN_THROTTLE_MS) { + _lastWarnAtByKey.set(throttleKey, now) + if (_lastWarnAtByKey.size > DB_SYNC_WARN_CACHE_MAX) { + const oldest = _lastWarnAtByKey.keys().next().value + if (oldest !== undefined) _lastWarnAtByKey.delete(oldest) + } + console.warn(`[vm-db-sync] ${op} failed for ${id} (failures=${_mirrorFailureCount}): ${err?.message || err}`) + } +} function repo() { if (!isDbOpen()) return null @@ -83,9 +109,6 @@ async function upsertVmsPgAsync(pgPool, entries) { email: [], account_uuid: [], org_uuid: [], - access_token: [], - refresh_token: [], - session_key: [], oauth_expires_at: [], oauth_source: [], proxy_id: [], @@ -108,23 +131,22 @@ async function upsertVmsPgAsync(pgPool, entries) { await pgPool.query( `INSERT INTO vms ( id, name, status, schedulable, email, account_uuid, org_uuid, - access_token, refresh_token, session_key, oauth_expires_at, oauth_source, + oauth_expires_at, oauth_source, proxy_id, claude_code_version, timezone, locale, owner_user_id, origin, vm_json, encrypted, file_mtime_ms, synced_at, created_at, updated_at ) SELECT * FROM UNNEST( $1::text[], $2::text[], $3::text[], $4::integer[], $5::text[], $6::text[], $7::text[], - $8::text[], $9::text[], $10::text[], $11::text[], $12::text[], - $13::text[], $14::text[], $15::text[], $16::text[], - $17::text[], $18::text[], - $19::text[], $20::integer[], $21::bigint[], $22::text[], $23::text[], $24::text[] + $8::text[], $9::text[], + $10::text[], $11::text[], $12::text[], $13::text[], + $14::text[], $15::text[], + $16::text[], $17::integer[], $18::bigint[], $19::text[], $20::text[], $21::text[] ) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, status = EXCLUDED.status, schedulable = EXCLUDED.schedulable, email = EXCLUDED.email, account_uuid = EXCLUDED.account_uuid, org_uuid = EXCLUDED.org_uuid, - access_token = EXCLUDED.access_token, refresh_token = EXCLUDED.refresh_token, - session_key = EXCLUDED.session_key, oauth_expires_at = EXCLUDED.oauth_expires_at, + oauth_expires_at = EXCLUDED.oauth_expires_at, oauth_source = EXCLUDED.oauth_source, proxy_id = EXCLUDED.proxy_id, claude_code_version = EXCLUDED.claude_code_version, timezone = EXCLUDED.timezone, locale = EXCLUDED.locale, owner_user_id = EXCLUDED.owner_user_id, origin = EXCLUDED.origin, @@ -139,9 +161,6 @@ async function upsertVmsPgAsync(pgPool, entries) { cols.email, cols.account_uuid, cols.org_uuid, - cols.access_token, - cols.refresh_token, - cols.session_key, cols.oauth_expires_at, cols.oauth_source, cols.proxy_id, @@ -177,7 +196,9 @@ function schedulePgFlush() { _pgFlushScheduled = true queueMicrotask(() => { _pgFlushScheduled = false - void flushVmDbSyncAsync().catch(() => {}) + void flushVmDbSyncAsync().catch((err) => { + recordVmDbSyncFailure('pg-flush', 'flush', err) + }) }) } @@ -218,7 +239,7 @@ export function flushVmDbSyncAsync() { } } catch (err) { for (const [id, item] of vmEntries) { - if (!_pgPendingVms.has(id)) _pgPendingVms.set(id, item) + if (!_pgPendingVms.has(id) && !_pgPendingDeletes.has(id)) _pgPendingVms.set(id, item) } if (pendingActive !== undefined && _pgPendingActive === undefined) { _pgPendingActive = pendingActive @@ -233,7 +254,7 @@ export function flushVmDbSyncAsync() { return next } -export function isVmJsonPath(filePath) { +function isVmJsonPath(filePath) { const base = path.basename(String(filePath || '')) const dir = path.basename(path.dirname(String(filePath || ''))) if (dir !== 'vms') return false @@ -241,7 +262,7 @@ export function isVmJsonPath(filePath) { } /** Mirror one vms/*.json file into the DB (safe no-op without DB; async pgPool in PG mode). */ -export function syncVmFile(filePath) { +export function syncVmFile(filePath, parsedOrData = undefined) { const pgPool = resolvePgPool() const r = pgPool ? null : repo() if (!pgPool && !r) return false @@ -249,8 +270,13 @@ export function syncVmFile(filePath) { const base = path.basename(filePath) const st = fs.statSync(filePath) const mtimeFloor = Math.floor(st.mtimeMs) + const resolvePayload = () => { + if (parsedOrData && typeof parsedOrData === 'object') return parsedOrData + if (typeof parsedOrData === 'string') return JSON.parse(parsedOrData) + return JSON.parse(fs.readFileSync(filePath, 'utf8')) + } if (base === 'active.json') { - const a = JSON.parse(fs.readFileSync(filePath, 'utf8')) + const a = resolvePayload() _lastSyncedMtime.set(filePath, mtimeFloor) if (!a?.active_vm) return true if (pgPool) { @@ -264,38 +290,65 @@ export function syncVmFile(filePath) { } return true } - const vm = JSON.parse(fs.readFileSync(filePath, 'utf8')) + const vm = resolvePayload() if (!vm?.id) return false _lastSyncedMtime.set(filePath, mtimeFloor) if (pgPool) { - _pgPendingVms.set(String(vm.id), { vm, mtimeMs: st.mtimeMs }) + const key = String(vm.id) + const snapshot = parsedOrData && typeof parsedOrData === 'object' ? structuredClone(vm) : vm + _pgPendingDeletes.delete(key) + _pgPendingVms.set(key, { vm: snapshot, mtimeMs: st.mtimeMs }) schedulePgFlush() } else { r.upsertFromVmJson(vm, { mtimeMs: st.mtimeMs }) } return true - } catch { + } catch (err) { + recordVmDbSyncFailure(path.basename(String(filePath || '')), 'sync', err) return false } } /** Remove a VM row (called when the vm.json file is deleted). */ export function removeVmFromDb(id) { - const r = repo() - if (!r || !id) return false - const removed = r.remove(id) + if (!id) return false + const key = String(id) + _pgPendingVms.delete(key) + if (_projectRoot) { + _lastSyncedMtime.delete(path.join(_projectRoot, 'vms', `${key}.json`)) + } + const pgPool = resolvePgPool() + const r = pgPool ? null : repo() + if (!pgPool && !r) return false + let removed = false + if (pgPool) { + _pgPendingDeletes.add(key) + const del = _pgFlushChain.then(async () => { + try { + await pgPool.query('DELETE FROM vms WHERE id = $1', [key]) + notifyDbTablesMutated(['vms']) + } catch (err) { + recordVmDbSyncFailure(key, 'pg-delete', err) + } finally { + _pgPendingDeletes.delete(key) + } + }) + _pgFlushChain = del.catch(() => {}) + removed = true + } else { + removed = r.remove(id) + } // A deleted slot must not linger in named pools or codex_slot_runtime: the panel // cannot render or uncheck an unknown id, and every save of that pool used to fail. const store = getActiveCodexRuntimeStore() if (store) { void store.delete(id).catch(() => {}) } else if (isDbOpen()) { - const pgPool = resolvePgPool() if (pgPool) { void deleteCodexRuntimePgAsync(pgPool, id).catch(() => {}) } else { try { - getDb().prepare('DELETE FROM codex_slot_runtime WHERE vm_id = ?').run(String(id)) + getDb().prepare('DELETE FROM codex_slot_runtime WHERE vm_id = ?').run(key) } catch {} } } @@ -318,6 +371,21 @@ function pruneVmPools(knownIds) { /** Forget settings.active_vm so startup reconcile does not rewrite active.json. */ export function clearActiveVmFromDb() { + _lastActiveVmId = null + _pgPendingActive = undefined + const pgPool = resolvePgPool() + if (pgPool) { + const del = _pgFlushChain.then(async () => { + try { + await pgPool.query('DELETE FROM settings WHERE key = $1', [ACTIVE_VM_KEY]) + notifyDbTablesMutated(['settings']) + } catch (err) { + recordVmDbSyncFailure('active.json', 'pg-clear-active', err) + } + }) + _pgFlushChain = del.catch(() => {}) + return true + } const r = repo() if (!r) return false r.clearActiveVmId() @@ -337,6 +405,12 @@ export function reconcileVms(projectRoot) { const out = { upserted: 0, rebuilt: 0, active: null } const seen = new Set() + // Fetch existing mtimes in one query instead of N per-file r.get() round trips. + const dbMtimes = new Map() + for (const row of r.db.prepare('SELECT id, file_mtime_ms FROM vms').all()) { + if (row?.id) dbMtimes.set(String(row.id), Number(row.file_mtime_ms) || 0) + } + if (fs.existsSync(dir)) { for (const f of fs.readdirSync(dir)) { if (!isVmRecordFile(f)) continue @@ -344,33 +418,41 @@ export function reconcileVms(projectRoot) { try { const vm = JSON.parse(fs.readFileSync(file, 'utf8')) if (!vm?.id) continue - seen.add(vm.id) + const id = String(vm.id) + seen.add(id) const st = fs.statSync(file) - _lastSyncedMtime.set(file, Math.floor(st.mtimeMs)) - const row = r.get(vm.id) - if (!row || (row.file_mtime_ms || 0) < Math.floor(st.mtimeMs)) { + const mtimeFloor = Math.floor(st.mtimeMs) + _lastSyncedMtime.set(file, mtimeFloor) + const prevMtime = dbMtimes.has(id) ? dbMtimes.get(id) : null + if (prevMtime === null || prevMtime < mtimeFloor) { r.upsertFromVmJson(vm, { mtimeMs: st.mtimeMs }) out.upserted += 1 } - } catch {} + } catch (err) { + recordVmDbSyncFailure(f, 'reconcile-file', err) + } } } - // DB rows without files → rebuild files (restore / disaster pull-up) - for (const row of r.list()) { - if (seen.has(row.id) || !row.vm) continue + // Single r.list() pass: rebuild missing files and collect known ids for pool pruning. + const rows = r.list() + const known = new Set(seen) + for (const row of rows) { + if (!row?.id || !row.vm) continue + known.add(row.id) + if (seen.has(row.id)) continue try { fs.mkdirSync(dir, { recursive: true }) const file = path.join(dir, `${row.id}.json`) atomicWriteJson(file, row.vm, { mode: 0o600 }) out.rebuilt += 1 - } catch {} + } catch (err) { + recordVmDbSyncFailure(row.id, 'reconcile-rebuild', err) + } } // Pool memberships for slots that exist nowhere any more (file deleted outside // the panel, or DB row gone). Rebuilt rows above count as alive. - const known = new Set(seen) - for (const row of r.list()) if (row?.id && row.vm) known.add(row.id) out.pruned_pool_members = pruneVmPools(known) // active.json ↔ settings.active_vm @@ -394,7 +476,9 @@ export function reconcileVms(projectRoot) { out.active = dbActive } } - } catch {} + } catch (err) { + recordVmDbSyncFailure('active.json', 'reconcile-active', err) + } return out } @@ -405,8 +489,8 @@ export function reconcileVms(projectRoot) { */ export function initVmDbSync(projectRoot, { watch = true } = {}) { _projectRoot = projectRoot - setVmWriteHook((filePath) => { - if (isVmJsonPath(filePath)) syncVmFile(filePath) + setVmWriteHook((filePath, parsedOrData) => { + if (isVmJsonPath(filePath)) syncVmFile(filePath, parsedOrData) }) const result = reconcileVms(projectRoot) // Older releases soft-deleted tenants without releasing their assigned slots. @@ -505,7 +589,9 @@ function syncChangedVmFilesPgAsync(pgPool, dir, candidates) { _lastSyncedMtime.set(c.file, c.mtimeFloor) } if (queued) await flushVmDbSyncAsync() - } catch {} + } catch (err) { + recordVmDbSyncFailure('watch-pg-sync', 'watch-sync', err) + } })() } @@ -602,6 +688,9 @@ export function resetVmDbSyncState() { _watchFullScan = false _lastActiveVmId = null _pgPendingVms.clear() + _pgPendingDeletes.clear() _pgPendingActive = undefined _pgFlushScheduled = false + _mirrorFailureCount = 0 + _lastWarnAtByKey.clear() } diff --git a/src/lib/vm/vm-file.mjs b/src/lib/vm/vm-file.mjs index 6dce7d5082..10bf614557 100644 --- a/src/lib/vm/vm-file.mjs +++ b/src/lib/vm/vm-file.mjs @@ -54,10 +54,10 @@ export function listVmRecordFiles(dir) { * * A scheduling attempt reads every slot record, and the pool re-runs the * attempt on every request, retry and failover. Caching UTF-8 text (never a - * parsed object) keyed by path + (mtimeMs, size, ino) avoids repeating those - * decodes while the on-disk identity is unchanged. A matching signature is a - * freshness hint, not a byte-identity proof: writers that change bytes - * without a new mtime/size/inode can miss. Callers always receive a newly + * parsed object) keyed by path + statSignature(dev:ino:size:mtimeNs:ctimeNs) + * avoids repeating those decodes while the on-disk identity is unchanged. + * Using bigint stat with ctimeNs catches same-size external rewrites even + * when mtime is preserved or restored. Callers always receive a newly * parsed object, so mutating a returned record cannot poison the next read. * * `KIN_VM_READ_CACHE_MS=0` disables the cache (escape hatch). The name is @@ -80,6 +80,10 @@ function isNotFound(err) { return err && err.code === 'ENOENT' } +function statSignature(stat) { + return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}` +} + function putReadCache(file, entry) { if (readCache.has(file)) readCache.delete(file) readCache.set(file, entry) @@ -100,14 +104,15 @@ export function readFileCached(file) { } let stat try { - stat = fs.statSync(file) + stat = fs.statSync(file, { bigint: true }) } catch (err) { readCache.delete(file) if (isNotFound(err)) return null throw err } + const sig = statSignature(stat) const hit = readCache.get(file) - if (hit && hit.mtimeMs === stat.mtimeMs && hit.size === stat.size && hit.ino === stat.ino) { + if (hit && hit.sig === sig) { putReadCache(file, hit) return hit.text } @@ -119,7 +124,7 @@ export function readFileCached(file) { if (isNotFound(err)) return null throw err } - putReadCache(file, { mtimeMs: stat.mtimeMs, size: stat.size, ino: stat.ino, text }) + putReadCache(file, { sig, text }) return text } @@ -143,10 +148,6 @@ function deepFreeze(value) { return Object.freeze(value) } -function statSignature(stat) { - return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}` -} - function parseFrozen(file) { let text try { @@ -224,16 +225,40 @@ export function vmLockBusy(key) { * registration seam to avoid an import cycle and to keep unit tests * (no DB) behavior-identical. */ +const VM_WRITE_HOOK_WARN_THROTTLE_MS = 30_000 let vmWriteHook = null +let vmWriteHookFailureCount = 0 +const vmWriteHookLastWarnAt = new Map() + +export function getVmWriteHookFailureCount() { + return vmWriteHookFailureCount +} + export function setVmWriteHook(fn) { vmWriteHook = typeof fn === 'function' ? fn : null + vmWriteHookLastWarnAt.clear() } -function notifyVmWrite(filePath) { +function notifyVmWrite(filePath, parsedOrData) { if (!vmWriteHook) return try { - vmWriteHook(filePath) - } catch {} + vmWriteHook(filePath, parsedOrData) + } catch (err) { + vmWriteHookFailureCount += 1 + const key = String(filePath || '') + const now = Date.now() + const last = vmWriteHookLastWarnAt.get(key) || 0 + if (now - last >= VM_WRITE_HOOK_WARN_THROTTLE_MS) { + vmWriteHookLastWarnAt.set(key, now) + if (vmWriteHookLastWarnAt.size > VM_READ_CACHE_MAX_ENTRIES) { + const oldest = vmWriteHookLastWarnAt.keys().next().value + if (oldest !== undefined) vmWriteHookLastWarnAt.delete(oldest) + } + console.warn( + `[vm-file] write hook failed for ${path.basename(key) || key} (failures=${vmWriteHookFailureCount}): ${err?.message || err}`, + ) + } + } } export function withVmLock(key, fn) { @@ -255,10 +280,9 @@ export function withVmLock(key, fn) { return run } -export function atomicWriteJson(filePath, obj, { mode } = {}) { +function writeAtomicText(filePath, data, parsedOrData, { mode } = {}) { const dir = path.dirname(filePath) const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`) - const data = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2) const opts = mode ? { mode } : undefined fs.writeFileSync(tmp, data, opts) try { @@ -275,10 +299,15 @@ export function atomicWriteJson(filePath, obj, { mode } = {}) { } catch {} } invalidateReadCache(filePath) - notifyVmWrite(filePath) + notifyVmWrite(filePath, parsedOrData) return true } +export function atomicWriteJson(filePath, obj, { mode } = {}) { + const data = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2) + return writeAtomicText(filePath, data, obj, { mode }) +} + export function writeJsonIfChanged(filePath, obj, { mode } = {}) { const data = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2) try { @@ -286,8 +315,7 @@ export function writeJsonIfChanged(filePath, obj, { mode } = {}) { return false } } catch {} - atomicWriteJson(filePath, data, { mode }) - return true + return writeAtomicText(filePath, data, obj, { mode }) } /** Resolve controller/slot binary with `/opt/vm2api` primary and `/opt/kin-gateway` legacy compat fallback. */ diff --git a/src/lib/vm/vm-registry.mjs b/src/lib/vm/vm-registry.mjs index e9f79714fe..c989773fe7 100644 --- a/src/lib/vm/vm-registry.mjs +++ b/src/lib/vm/vm-registry.mjs @@ -11,8 +11,11 @@ import { hasCredentialPresence, hasRefreshPresence, clearVmQuotaRestriction, + clearVmTempPark, isQuotaParkReason, markVmRestriction, + readVmTempPark, + setVmTempPark, expiresAtToMs, ensureSlotSubscriptionType, } from '../oauth/oauth-credentials.mjs' @@ -75,14 +78,26 @@ export function listVms(projectRoot, routing = null) { .filter(Boolean) } -export function getVm(projectRoot, id) { - return readJsonCached(path.join(projectRoot, 'vms', `${id}.json`)) +/** + * Overlay live runtime state (CodexRuntimeStore) onto a VM record or summary. + * Safe no-op for non-Codex slots or when no active runtime store is registered. + */ +export function mergeVmRuntime(vm) { + if (!vm || typeof vm !== 'object' || !isCodexVm(vm)) return vm + const runtimeStore = getActiveCodexRuntimeStore() + return runtimeStore ? runtimeStore.mergeVm(vm) : vm +} + +export function getVm(projectRoot, id, { mergeRuntime = true } = {}) { + const vm = readJsonCached(path.join(projectRoot, 'vms', `${id}.json`)) + if (!vm || !mergeRuntime) return vm + return mergeVmRuntime(vm) } export function summarizeVm(rawVm, projectRoot = null, routing = null) { const kind = normalizeVmKind(rawVm) - const runtimeStore = kind.kind === 'codex' ? getActiveCodexRuntimeStore() : null - const vm = runtimeStore ? runtimeStore.mergeVm(rawVm) : rawVm + const vm = kind.kind === 'codex' ? mergeVmRuntime(rawVm) : rawVm + const tempPark = readVmTempPark(vm) const codex = kind.kind === 'codex' ? summarizeCodexSlot(projectRoot, vm) : null const quota = codex?.usage?.quota || {} const globalOpenAI = normalizeOpenAIQuotaPolicy(routing?.codex?.quota) @@ -200,8 +215,8 @@ export function summarizeVm(rawVm, projectRoot = null, routing = null) { schedule_off: vm.schedule_off === true, unschedulable: vm.unschedulable || null, schedule_hold: vm.schedule_hold || null, - temp_unschedulable_until: vm.claude?.temp_unschedulable_until || vm.temp_unschedulable_until || null, - temp_unschedulable_reason: vm.claude?.temp_unschedulable_reason || vm.temp_unschedulable_reason || null, + temp_unschedulable_until: tempPark.until, + temp_unschedulable_reason: tempPark.reason, owner_user_id: normalizeOwnerId(vm.owner_user_id), origin: vmOriginOf(vm), proxy_id: vm.proxy?.id || null, @@ -248,43 +263,46 @@ export function getActiveVmId(projectRoot) { export function persistVmSubscription(projectRoot, vmId, profile, { accountUuid = null, orgUuid = null } = {}) { const identity = flattenOauthIdentity(profile) if (!identity.subscription_type) return null - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.claude = vm.claude || {} - // A profile request may finish after an operator replaces the slot's account. - if (accountUuid && vm.claude.account_uuid !== accountUuid) return null - if (orgUuid && vm.claude.org_uuid !== orgUuid) return null - vm.claude.subscription_type = identity.subscription_type - vm.claude.rate_limit_tier = identity.rate_limit_tier - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + let matched = true + const vm = patchVmRecord(projectRoot, vmId, (rec) => { + rec.claude = rec.claude || {} + // A profile request may finish after an operator replaces the slot's account. + if (accountUuid && rec.claude.account_uuid !== accountUuid) { + matched = false + return false + } + if (orgUuid && rec.claude.org_uuid !== orgUuid) { + matched = false + return false + } + rec.claude.subscription_type = identity.subscription_type + rec.claude.rate_limit_tier = identity.rate_limit_tier + }) + return matched ? vm : null } export function persistAccountTier(projectRoot, vmId, tier, { source = null } = {}) { const key = String(tier || '').toLowerCase() if (key !== 'pro' && key !== 'max') return null - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.claude = vm.claude || {} - if (vm.claude.account_tier_source === 'profile' && source !== 'profile' && source !== 'usage') return vm - if (source === 'profile' || source === 'usage') { - ensureSlotSubscriptionType(path.join(projectRoot, 'vms', vmId, 'cli-home'), key, { source }) - } - const hasMachine = vm.machine && typeof vm.machine === 'object' - const currentDisk = Number.isInteger(vm.machine?.disk_gb) ? vm.machine.disk_gb : 0 - const diskNeedsBump = key === 'max' && (hasMachine || vm.runtime?.type === 'kvm') && currentDisk < VM_DISK_GB_MAX_TIER - if (vm.claude.account_tier === key && (vm.claude.account_tier_source || null) === source && !diskNeedsBump) return vm - vm.claude.account_tier = key - vm.claude.account_tier_source = source - if (diskNeedsBump) { - vm.machine = { ...(hasMachine ? vm.machine : {}), disk_gb: VM_DISK_GB_MAX_TIER } - } - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.claude = vm.claude || {} + if (vm.claude.account_tier_source === 'profile' && source !== 'profile' && source !== 'usage') return false + if (source === 'profile' || source === 'usage') { + ensureSlotSubscriptionType(path.join(projectRoot, 'vms', vmId, 'cli-home'), key, { source }) + } + const hasMachine = vm.machine && typeof vm.machine === 'object' + const currentDisk = Number.isInteger(vm.machine?.disk_gb) ? vm.machine.disk_gb : 0 + const diskNeedsBump = + key === 'max' && (hasMachine || vm.runtime?.type === 'kvm') && currentDisk < VM_DISK_GB_MAX_TIER + if (vm.claude.account_tier === key && (vm.claude.account_tier_source || null) === source && !diskNeedsBump) { + return false + } + vm.claude.account_tier = key + vm.claude.account_tier_source = source + if (diskNeedsBump) { + vm.machine = { ...(hasMachine ? vm.machine : {}), disk_gb: VM_DISK_GB_MAX_TIER } + } + }) } /** @@ -364,8 +382,7 @@ export function persistCodexUsage( } } syncCodexQuotaSchedule(projectRoot, vm, { now, policy }) - const latest = getVm(projectRoot, vmId) || vm - return store ? store.mergeVm(latest) : latest + return getVm(projectRoot, vmId) || (store ? store.mergeVm(vm) : vm) } /** @@ -395,23 +412,16 @@ export function syncCodexQuotaSchedule(projectRoot, vm, { now = Date.now(), poli draft.temp_unschedulable_until_ms = null } else if (untilMs != null) { draft.temp_unschedulable_until_ms = untilMs + } else { + draft.temp_unschedulable_until_ms = null } draft.temp_unschedulable_reason = why }, { critical: true, now }, ) - vm.claude = { ...(vm.claude || {}) } - if (until == null && /_local$/.test(ev.reason || '')) { - delete vm.claude.temp_unschedulable_until - delete vm.temp_unschedulable_until - } else if (untilMs != null) { - vm.claude.temp_unschedulable_until = untilMs - vm.temp_unschedulable_until = untilMs - } - vm.claude.temp_unschedulable_reason = why - vm.temp_unschedulable_reason = why + setVmTempPark(vm, { until, reason: why, now }) } else { - if (until == null && /_local$/.test(ev.reason || '')) clearVmQuotaRestriction(file) + // Single RMW: setVmTempPark clears stale until on both mirrors whenever until <= now (incl. null). const next = markVmRestriction(file, { until, reason: ev.reason }) if (next) { vm.claude = next.claude @@ -439,8 +449,7 @@ export function syncCodexQuotaSchedule(projectRoot, vm, { now = Date.now(), poli } if (ev.action === 'clear' || ev.action === 'enable') { if (bypassVmJson) { - const existingReason = - effectiveVm.claude?.temp_unschedulable_reason || effectiveVm.temp_unschedulable_reason || '' + const existingReason = readVmTempPark(effectiveVm, { now }).reason || '' if (isQuotaParkReason(existingReason)) { store.noteVmJsonWriteAvoided(1) store.patch( @@ -452,12 +461,7 @@ export function syncCodexQuotaSchedule(projectRoot, vm, { now = Date.now(), poli }, { critical: true, now }, ) - if (vm.claude && typeof vm.claude === 'object') { - delete vm.claude.temp_unschedulable_until - delete vm.claude.temp_unschedulable_reason - } - delete vm.temp_unschedulable_until - delete vm.temp_unschedulable_reason + clearVmTempPark(vm) } } else { const next = clearVmQuotaRestriction(file) @@ -496,100 +500,71 @@ export function syncCodexQuotaSchedule(projectRoot, vm, { now = Date.now(), poli } export function persistAllowedModels(projectRoot, vmId, models) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) const next = Array.isArray(models) ? [...new Set(models.map((id) => String(id || '').trim()).filter(Boolean))] : [] - vm.policy = { ...(vm.policy || {}) } - if (!next.length) delete vm.policy.allowed_models - else vm.policy.allowed_models = next - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.policy = { ...(vm.policy || {}) } + if (!next.length) delete vm.policy.allowed_models + else vm.policy.allowed_models = next + }) } /** Reload can recreate the container (new id, new exit network); the record must follow. Re-reads so other fields are not clobbered. */ export function persistVmRuntime(projectRoot, vmId, runtime) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!runtime || !fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.runtime = runtime - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + if (!runtime) return null + return patchVmRecord(projectRoot, vmId, { runtime }) } export function persistVmSessionSlots(projectRoot, vmId, value, { override = true } = {}) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.policy = { - ...(vm.policy || {}), - sessionSlots: value, - sessionSlotsOverride: override, - } - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.policy = { + ...(vm.policy || {}), + sessionSlots: value, + sessionSlotsOverride: override, + } + }) } export function persistVmMaxSessions(projectRoot, vmId, value, { override = true } = {}) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 256) { - throw new TypeError('max_sessions must be an integer between 0 and 256') - } - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.policy = { - ...(vm.policy || {}), - maxSessions: value, - sessionsOverride: override, - } - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 256) { + throw new TypeError('max_sessions must be an integer between 0 and 256') + } + vm.policy = { + ...(vm.policy || {}), + maxSessions: value, + sessionsOverride: override, + } + }) } /** `override` is a parsed `quota_override` (null clears it, the slot follows global quota again). */ export function persistVmQuotaOverride(projectRoot, vmId, override) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.policy = { ...(vm.policy || {}) } - if (override) vm.policy.quota = override - else delete vm.policy.quota - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.policy = { ...(vm.policy || {}) } + if (override) vm.policy.quota = override + else delete vm.policy.quota + }) } /** `value` is a parsed `active_hours` window (null clears it: the slot runs 24h). */ export function persistVmActiveHours(projectRoot, vmId, value) { const parsed = parseActiveHoursInput(value) if (!parsed.ok) throw new TypeError(parsed.error) - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.policy = { ...(vm.policy || {}) } - if (parsed.value == null) delete vm.policy.active_hours - else vm.policy.active_hours = parsed.value - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.policy = { ...(vm.policy || {}) } + if (parsed.value == null) delete vm.policy.active_hours + else vm.policy.active_hours = parsed.value + }) } export function persistVmScheduleLevel(projectRoot, vmId, value) { const parsed = parseScheduleLevelInput(value) if (!parsed.ok) throw new TypeError(parsed.error) - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.policy = { ...(vm.policy || {}) } - if (parsed.value == null) delete vm.policy.priority - else vm.policy.priority = parsed.value - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, vmId, (vm) => { + vm.policy = { ...(vm.policy || {}) } + if (parsed.value == null) delete vm.policy.priority + else vm.policy.priority = parsed.value + }) } function applySlotEnginePatch(vm, patch = {}) { @@ -616,28 +591,9 @@ function applySlotEnginePatch(vm, patch = {}) { } export function persistSlotEnginePolicy(projectRoot, vmId, patch = {}) { - const file = path.join(projectRoot, 'vms', `${vmId}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - applySlotEnginePatch(vm, patch) - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm -} - -export function persistSlotEnginePolicyMany(projectRoot, ids, patch = {}) { - const targets = - Array.isArray(ids) && ids.length - ? ids.map((id) => String(id || '').trim()).filter(Boolean) - : listVms(projectRoot).map((vm) => vm.id) - const items = [] - const missing = [] - for (const id of targets) { - const vm = persistSlotEnginePolicy(projectRoot, id, patch) - if (!vm) missing.push(id) - else items.push(summarizeVm(vm)) - } - return { updated: items.length, missing, items } + return patchVmRecord(projectRoot, vmId, (vm) => { + applySlotEnginePatch(vm, patch) + }) } export function setActiveVm(projectRoot, id) { const file = path.join(projectRoot, 'vms', 'active.json') @@ -939,25 +895,23 @@ export function clearKernelRestartPending(project, id) { } export function bindVmProxy(projectRoot, id, proxyInfo) { - const file = path.join(projectRoot, 'vms', `${id}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.proxy = proxyInfo - ? { - id: proxyInfo.id, - host: proxyInfo.host, - port: proxyInfo.port, - scheme: proxyInfo.scheme || proxyInfo.kind || 'socks5', - url: proxyInfo.url || null, - username: proxyInfo.username || null, - password: proxyInfo.password == null ? null : proxyInfo.password, - } - : null - // Eligibility (`slotHasBoundProxy`) and CLI egress both require this flag. - // It is not an operator toggle — it follows whether an exit is bound. - vm.proxy_cli_enabled = hasBoundExit(vm.proxy) - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm) + const vm = patchVmRecord(projectRoot, id, (rec) => { + rec.proxy = proxyInfo + ? { + id: proxyInfo.id, + host: proxyInfo.host, + port: proxyInfo.port, + scheme: proxyInfo.scheme || proxyInfo.kind || 'socks5', + url: proxyInfo.url || null, + username: proxyInfo.username || null, + password: proxyInfo.password == null ? null : proxyInfo.password, + } + : null + // Eligibility (`slotHasBoundProxy`) and CLI egress both require this flag. + // It is not an operator toggle — it follows whether an exit is bound. + rec.proxy_cli_enabled = hasBoundExit(rec.proxy) + }) + if (!vm) return null // Re-binding changes the premise of an automatic proxy hold: the proxy it was // written for is no longer this slot's exit. Every clearing path is tag-guarded, // so without reconciling here the slot stayed restricted until the new proxy's @@ -991,6 +945,7 @@ export function patchVmRecord(projectRoot, id, patch) { const vm = JSON.parse(fs.readFileSync(file, 'utf8')) if (typeof patch === 'function') { const next = patch(vm) + if (next === false) return vm if (next && typeof next === 'object' && next !== vm) Object.assign(vm, next) } else if (patch && typeof patch === 'object') { Object.assign(vm, patch) @@ -1076,14 +1031,12 @@ export function repairSlotSmbios(projectRoot) { export function persistVmTimezone(projectRoot, id, timezone, { source = 'manual' } = {}) { const zone = validTimezone(timezone) if (!zone) return null - const file = path.join(projectRoot, 'vms', `${id}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.timezone = zone - vm.timezone_source = source - if (vm.fingerprint && typeof vm.fingerprint === 'object') vm.fingerprint.timezone = zone - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm) + const vm = patchVmRecord(projectRoot, id, (rec) => { + rec.timezone = zone + rec.timezone_source = source + if (rec.fingerprint && typeof rec.fingerprint === 'object') rec.fingerprint.timezone = zone + }) + if (!vm) return null if (fs.existsSync(fingerprintDir(projectRoot, id))) { try { syncSlotIdentityTimezoneAndPreset(projectRoot, vm, { timezone: zone, locale: vm.locale }) @@ -1093,14 +1046,10 @@ export function persistVmTimezone(projectRoot, id, timezone, { source = 'manual' } export function persistVmOwner(projectRoot, id, { ownerUserId = null, origin = null } = {}) { - const file = path.join(projectRoot, 'vms', `${id}.json`) - if (!fs.existsSync(file)) return null - const vm = JSON.parse(fs.readFileSync(file, 'utf8')) - vm.owner_user_id = normalizeOwnerId(ownerUserId) - vm.origin = origin || vmOriginOf({ ...vm, owner_user_id: vm.owner_user_id }) - vm.updated_at = new Date().toISOString() - atomicWriteJson(file, vm, { mode: 0o600 }) - return vm + return patchVmRecord(projectRoot, id, (vm) => { + vm.owner_user_id = normalizeOwnerId(ownerUserId) + vm.origin = origin || vmOriginOf({ ...vm, owner_user_id: vm.owner_user_id }) + }) } /** Return administrator-assigned slots to the platform when their tenant is removed. */ diff --git a/test/unit/health-probe.test.mjs b/test/unit/health-probe.test.mjs index fc413d38f0..ddef06d099 100644 --- a/test/unit/health-probe.test.mjs +++ b/test/unit/health-probe.test.mjs @@ -1,6 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { isClientStream } from '../../src/lib/protocol/convert.mjs' +import { setActiveCodexRuntimeStore } from '../../src/lib/pool/codex-runtime-store.mjs' import { normalizeHealthProbeConfig, isHealthShape, @@ -937,3 +938,72 @@ test('runRealProbe supports single-model targeted reprobe', async () => { assert.equal(single.model, 'claude-sonnet-4-6') monitor.stop() }) + +test('selectHealthProbeTargets uses unified readVmTempPark and merged Codex runtime state (A13)', (t) => { + const now = Date.now() + t.after(() => setActiveCodexRuntimeStore(null)) + + // 1. Summary VM with top-level temp_unschedulable_* (no nested claude object) must be excluded on auth park. + // 2. VM with expired cooldown_until but active claude.temp_unschedulable_until must still be excluded. + const vms = [ + { + id: 'vm-summary-parked', + platform: 'anthropic', + schedulable: true, + status: 'running', + has_token: true, + temp_unschedulable_until: now + 60_000, + temp_unschedulable_reason: 'authentication_failed_after_refresh', + }, + { + id: 'vm-skewed-cool', + platform: 'anthropic', + schedulable: true, + status: 'running', + cooldown_until: now - 10_000, + cooldown_reason: 'quota_5h_header', + claude: { + has_access: true, + temp_unschedulable_until: now + 60_000, + temp_unschedulable_reason: 'authentication_failed_after_refresh', + }, + }, + { + id: 'vm-healthy', + platform: 'anthropic', + schedulable: true, + status: 'running', + has_token: true, + }, + ] + assert.deepEqual( + selectHealthProbeTargets(vms, cfg, now, 'anthropic').map((v) => v.id), + ['vm-healthy'], + ) + + // 3. Raw Codex VM whose static vm.json looks healthy must honor live CodexRuntimeStore auth park / refresh error. + setActiveCodexRuntimeStore({ + mergeVm(vm) { + if (vm.id === 'codex-live-parked') { + return { + ...vm, + temp_unschedulable_until: now + 60_000, + temp_unschedulable_reason: 'authentication_failed_after_refresh', + } + } + if (vm.id === 'codex-live-revoked') { + return { ...vm, refresh_error: 'oauth_revoked' } + } + return vm + }, + }) + const codexVms = [ + { id: 'codex-live-parked', platform: 'openai', schedulable: true, status: 'running', has_token: true }, + { id: 'codex-live-revoked', platform: 'openai', schedulable: true, status: 'running', has_token: true }, + { id: 'codex-live-ok', platform: 'openai', schedulable: true, status: 'running', has_token: true }, + ] + assert.deepEqual( + selectHealthProbeTargets(codexVms, cfg, now, 'openai').map((v) => v.id), + ['codex-live-ok'], + ) +}) diff --git a/test/unit/oauth-credentials.test.mjs b/test/unit/oauth-credentials.test.mjs index 924a6e78aa..79ea387f87 100644 --- a/test/unit/oauth-credentials.test.mjs +++ b/test/unit/oauth-credentials.test.mjs @@ -15,6 +15,9 @@ import { markVmAuthCooldown, clearVmAuthCooldown, clearRecoverableVmCooldown, + readVmTempPark, + setVmTempPark, + clearVmTempPark, restoreScheduleAfterLiveCredential, readWorkerCredentialFile, readSlotCredentialIdentity, @@ -700,3 +703,114 @@ test('custom duration quota park (quota_24h_header) is preserved by auth healing fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('temp park SSOT keeps claude.* and top-level identical across expired quota -> auth cooldown and writes 0600 (A2/A3)', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-oauth-a2-a3-')) + try { + const vmPath = path.join(dir, 'vm-a2.json') + const now = Date.now() + const expiredUntil = now - 60_000 + const futureQuota = now + 30_000 + const futureAuth = now + 300_000 + fs.writeFileSync( + vmPath, + JSON.stringify({ + id: 'vm-a2', + status: 'running', + schedulable: true, + claude: { has_access: true, has_refresh: true }, + }), + { mode: 0o644 }, + ) + + // 1. Quota restriction sets both mirrors and enforces 0600 file permissions. + markVmRestriction(vmPath, { until: futureQuota, reason: 'quota_5h_header' }) + let vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, futureQuota) + assert.equal(vm.claude.temp_unschedulable_until, futureQuota) + assert.equal(vm.temp_unschedulable_reason, 'quota_5h_header') + assert.equal(vm.claude.temp_unschedulable_reason, 'quota_5h_header') + if (process.platform !== 'win32') { + assert.equal(fs.statSync(vmPath).mode & 0o777, 0o600) + } + + // 2. Simulate quota park expiring, then 401 triggers markVmAuthCooldown. + vm.temp_unschedulable_until = expiredUntil + vm.claude.temp_unschedulable_until = expiredUntil + fs.writeFileSync(vmPath, JSON.stringify(vm, null, 2), { mode: 0o644 }) + + markVmAuthCooldown(vmPath, { + until: futureAuth, + reason: 'authentication_failed_after_refresh', + generation: 7, + }) + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, futureAuth, 'top-level until must match claude.* after auth cooldown') + assert.equal(vm.claude.temp_unschedulable_until, futureAuth) + assert.equal(vm.temp_unschedulable_reason, 'authentication_failed_after_refresh') + assert.equal(vm.claude.temp_unschedulable_reason, 'authentication_failed_after_refresh') + assert.equal(vm.claude.oauth_401_generation, 7) + assert.deepEqual(readVmTempPark(vm, { now }), { + until: futureAuth, + reason: 'authentication_failed_after_refresh', + active: true, + }) + if (process.platform !== 'win32') { + assert.equal(fs.statSync(vmPath).mode & 0o777, 0o600) + } + + // 3. Clearing auth cooldown clears BOTH claude.* and top-level fields. + clearVmAuthCooldown(vmPath) + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, undefined) + assert.equal(vm.temp_unschedulable_reason, undefined) + assert.equal(vm.claude.temp_unschedulable_until, undefined) + assert.equal(vm.claude.temp_unschedulable_reason, undefined) + assert.equal(vm.claude.oauth_401_generation, undefined) + + // 4. Setting until <= now (or null) deletes both until fields (single-RMW local restriction). + markVmRestriction(vmPath, { until: futureQuota, reason: 'quota_5h_header' }) + markVmRestriction(vmPath, { until: null, reason: 'quota_5h_local' }) + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, undefined) + assert.equal(vm.claude.temp_unschedulable_until, undefined) + assert.equal(vm.temp_unschedulable_reason, 'quota_5h_local') + assert.equal(vm.claude.temp_unschedulable_reason, 'quota_5h_local') + + // 5. clearVmQuotaRestriction and clearRecoverableVmCooldown enforce 0600 permissions. + fs.chmodSync(vmPath, 0o644) + clearVmQuotaRestriction(vmPath) + if (process.platform !== 'win32') { + assert.equal(fs.statSync(vmPath).mode & 0o777, 0o600) + } + markVmRestriction(vmPath, { until: futureQuota, reason: 'rate_limited' }) + fs.chmodSync(vmPath, 0o644) + clearRecoverableVmCooldown(vmPath) + if (process.platform !== 'win32') { + assert.equal(fs.statSync(vmPath).mode & 0o777, 0o600) + } + + // 6. Helper contract checks: readVmTempPark prefers active future deadline over stale expired mirror. + const skewed = { + temp_unschedulable_until: expiredUntil, + temp_unschedulable_reason: 'quota_5h_header', + claude: { + temp_unschedulable_until: futureAuth, + temp_unschedulable_reason: 'authentication_failed_after_refresh', + }, + } + assert.deepEqual(readVmTempPark(skewed, { now }), { + until: futureAuth, + reason: 'authentication_failed_after_refresh', + active: true, + }) + setVmTempPark(skewed, { until: expiredUntil, reason: 'quota_5h_local', now }) + assert.equal(skewed.temp_unschedulable_until, undefined) + assert.equal(skewed.claude.temp_unschedulable_until, undefined) + clearVmTempPark(skewed) + assert.equal(skewed.temp_unschedulable_reason, undefined) + assert.equal(skewed.claude.temp_unschedulable_reason, undefined) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/pool-scheduler.test.mjs b/test/unit/pool-scheduler.test.mjs index 06ba391d07..2b2126df82 100644 --- a/test/unit/pool-scheduler.test.mjs +++ b/test/unit/pool-scheduler.test.mjs @@ -652,8 +652,13 @@ test('vm-db-sync PG mode offloads single-VM writes to async pgPool UNNEST and av assert.ok(upsertCall, 'PG vm-db-sync must use async UNNEST upsert') assert.deepEqual(upsertCall.params[0], ['vm-01'], 'must only upsert the single changed vmId') assert.deepEqual(upsertCall.params[1], ['vm-01-updated']) - assert.equal(upsertCall.params[7][0], null, 'access_token column must stay null') - const storedJson = JSON.parse(upsertCall.params[18][0]) + assert.equal( + /access_token|refresh_token|session_key/i.test(upsertCall.sql), + false, + 'dead token columns must not be written by PG UNNEST', + ) + assert.equal(upsertCall.params.length, 21) + const storedJson = JSON.parse(upsertCall.params[15][0]) assert.equal(storedJson.claude.access_token, undefined, 'vm_json must strip credential secrets') assert.equal(storedJson.claude.has_access, true) diff --git a/test/unit/proxy-pool-bind.test.mjs b/test/unit/proxy-pool-bind.test.mjs index 4d047ac631..d5f42efa5f 100644 --- a/test/unit/proxy-pool-bind.test.mjs +++ b/test/unit/proxy-pool-bind.test.mjs @@ -5,7 +5,7 @@ import os from 'node:os' import path from 'node:path' import net from 'node:net' import { ProxyPool, MAX_VMS_PER_PROXY, clampBindLimit } from '../../src/lib/vm/proxy-pool.mjs' -import { reconcileProxyScheduleHold, bindVmProxy } from '../../src/lib/vm/vm-registry.mjs' +import { reconcileProxyScheduleHold, bindVmProxy, persistVmTimezone } from '../../src/lib/vm/vm-registry.mjs' function tmpDir(prefix = 'kin-px-') { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)) @@ -856,3 +856,27 @@ test('re-binding preserves a manual proxy hold and another subsystem hold (#1395 assert.equal(f.get('vm-maint').schedule_hold?.reason, 'maintenance') assert.equal(f.get('vm-maint').schedulable, false) }) + +test('bindVmProxy and persistVmTimezone preserve 0600 file permissions (A3)', (t) => { + const f = holdFixture(t) + f.save({ id: 'vm-perm', status: 'running', schedulable: true }) + const file = path.join(f.root, 'vms', 'vm-perm.json') + fs.chmodSync(file, 0o644) + + bindVmProxy(f.root, 'vm-perm', { + id: 'proxy-sec', + host: '10.0.0.9', + port: 1080, + username: 'u', + password: 'secret-proxy-password', + }) + if (process.platform !== 'win32') { + assert.equal(fs.statSync(file).mode & 0o777, 0o600, 'bindVmProxy must write vm.json with 0600 mode') + } + + fs.chmodSync(file, 0o644) + persistVmTimezone(f.root, 'vm-perm', 'UTC', { source: 'manual' }) + if (process.platform !== 'win32') { + assert.equal(fs.statSync(file).mode & 0o777, 0o600, 'persistVmTimezone must write vm.json with 0600 mode') + } +}) diff --git a/test/unit/rate-limit-service.test.mjs b/test/unit/rate-limit-service.test.mjs index 9a8c4a6e62..0cfa188885 100755 --- a/test/unit/rate-limit-service.test.mjs +++ b/test/unit/rate-limit-service.test.mjs @@ -389,4 +389,31 @@ test('PG mode: 200 session windows batch asynchronously with 0 sync repo calls; assert.ok(upd529) assert.deepEqual(upd529.params[6], [true]) assert.ok(typeof upd529.params[7][0] === 'string' && upd529.params[7][0].includes('T')) + + // 5. PG9: batched PG writes sort accountIds lexicographically to prevent cross-instance 40P01 deadlocks + pgQueries.length = 0 + for (const [accountId, vmId] of [ + ['acc-sort-z', 'vm-sort-z'], + ['acc-sort-a', 'vm-sort-a'], + ['acc-sort-m', 'vm-sort-m'], + ]) { + svc.updateSessionWindow({ + accountId, + vmId, + headers: { + 'anthropic-ratelimit-unified-5h-status': 'allowed', + 'anthropic-ratelimit-unified-5h-reset': reset5hSec, + }, + now: now + 20_000, + }) + } + const sortedFlush = await svc.flushWindowWrites() + assert.equal(sortedFlush.flushed, 3) + const expectedOrder = ['acc-sort-a', 'acc-sort-m', 'acc-sort-z'] + const insAcct = pgQueries.find((q) => /INSERT INTO accounts\b/i.test(q.sql)) + const updAcct = pgQueries.find((q) => /UPDATE accounts AS a[\s\S]*FROM UNNEST/i.test(q.sql)) + const insRt = pgQueries.find((q) => /INSERT INTO account_runtime\b/i.test(q.sql)) + assert.deepEqual(insAcct?.params[0], expectedOrder) + assert.deepEqual(updAcct?.params[0], expectedOrder) + assert.deepEqual(insRt?.params[0], expectedOrder) }) diff --git a/test/unit/request-redis-opt.test.mjs b/test/unit/request-redis-opt.test.mjs index bdd18982b3..ce33f5730d 100644 --- a/test/unit/request-redis-opt.test.mjs +++ b/test/unit/request-redis-opt.test.mjs @@ -422,7 +422,14 @@ test('ApiKeyStore Dirty-Set Write-Behind batches usage, enforces Safety Floor on assert.equal(okRes.flushed, 2) assert.equal(okRes.failed, 0) const batchSql = pgQueries[1].sql - assert.match(batchSql, /UPDATE api_keys AS k[\s\S]*FROM \(VALUES/) + const batchParams = pgQueries[1].params + assert.match(batchSql, /UPDATE api_keys AS k[\s\S]*FROM UNNEST\(/) + assert.equal(batchParams.length, 10, 'PG usage batch must use fixed 10-parameter UNNEST') + assert.deepEqual( + batchParams[1], + [kA.id, kB.id].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)), + 'PG usage batch must sort keyIds lexicographically to prevent 40P01 deadlocks', + ) assert.match(batchSql, /\(\$1::text\)::timestamptz/) assert.match(batchSql, /NULLIF\(k\.window_5h_start, ''\)::timestamptz/) assert.match(batchSql, /NULLIF\(k\.window_1d_start, ''\)::timestamptz/) @@ -449,15 +456,19 @@ test('ApiKeyStore usage flusher drains multiple batches per tick, logs throttled // 1. Multi-batch tick draining (>200 dirty keys drained in one tick, not capped at 1 batch) const seenBatches = [] + const seenSorted = [] const batchPgPool = { query: async (_sql, params) => { - seenBatches.push((params.length - 1) / 9) + assert.equal(params.length, 10) + seenBatches.push(params[1].length) + const ids = params[1] + seenSorted.push(ids.every((id, idx) => idx === 0 || ids[idx - 1] <= id)) return { rows: [] } }, } const tickStore = new ApiKeyStore({ db, writeBehindUsage: true, usageFlushIntervalMs: 60_000, pgPool: batchPgPool }) const billing = getCacheRuntime().billing - for (let i = 0; i < 250; i += 1) { + for (let i = 249; i >= 0; i -= 1) { await billing.accumulateKeyUsage(`key_tick_${i}`, { requests: 1, quota_requests_used: 1, @@ -469,6 +480,7 @@ test('ApiKeyStore usage flusher drains multiple batches per tick, logs throttled const drained = await tickStore._drainUsageTick() assert.equal(drained, 250, 'single tick must drain across multiple 200-key batches until empty') assert.deepEqual(seenBatches, [200, 50]) + assert.deepEqual(seenSorted, [true, true], 'each PG UNNEST batch must be sorted by keyId') await tickStore.close() // 2. Throttled console.error observability on repeated flush failures (without swallowing errors) diff --git a/test/unit/slot-engine.test.mjs b/test/unit/slot-engine.test.mjs index f0b5f36a2a..277b37282d 100644 --- a/test/unit/slot-engine.test.mjs +++ b/test/unit/slot-engine.test.mjs @@ -32,13 +32,7 @@ import { validateInferenceRoutingPatch, } from '../../src/lib/vm/slot-engine.mjs' -import { - getVm, - listVms, - persistSlotEnginePolicy, - persistSlotEnginePolicyMany, - summarizeVm, -} from '../../src/lib/vm/vm-registry.mjs' +import { getVm, listVms, persistSlotEnginePolicy, summarizeVm } from '../../src/lib/vm/vm-registry.mjs' test('session slots default to native capacity and clamp persisted values', () => { assert.equal(KERNEL_NATIVE_SLOT_COUNT, 20) @@ -239,18 +233,6 @@ test('persisted CRAG pin survives summary projection and overrides conflicting g assert.equal(resolveKernelDataplane(wrapped, { inference: { dataplane: 'crag' } }), 'wrap') }) -test('persistSlotEnginePolicyMany updates listed ids only', () => { - const root = makeRoot() - writeVm(root, 'vm-01') - writeVm(root, 'vm-02') - const report = persistSlotEnginePolicyMany(root, ['vm-01'], { inference_engine: 'rust' }) - assert.equal(report.updated, 1) - assert.equal(report.items[0].inference_engine, 'rust') - const two = JSON.parse(fs.readFileSync(path.join(root, 'vms', 'vm-02.json'), 'utf8')) - assert.equal(two.inference_engine, undefined) - fs.rmSync(root, { recursive: true, force: true }) -}) - test('patch parsers reject unknown values', () => { assert.equal(parseSlotEnginePolicyPatch({}).ok, false) assert.equal(parseSlotEnginePolicyPatch({ inference_engine: 'kvm' }).ok, false) diff --git a/test/unit/vm-db-sync.test.mjs b/test/unit/vm-db-sync.test.mjs index 7df6dfadd1..12beb2c433 100644 --- a/test/unit/vm-db-sync.test.mjs +++ b/test/unit/vm-db-sync.test.mjs @@ -8,7 +8,18 @@ import { VmsRepo } from '../../src/lib/db/repos/vms-repo.mjs' import { UsersRepo } from '../../src/lib/db/repos/users-repo.mjs' import { VmPoolsRepo } from '../../src/lib/db/repos/vm-pools-repo.mjs' import { encryptString, decryptString, isEncrypted } from '../../src/lib/db/secure.mjs' -import { initVmDbSync, stopVmWatch, syncVmFile, removeVmFromDb, reconcileVms } from '../../src/lib/vm/vm-db-sync.mjs' +import { + initVmDbSync, + stopVmWatch, + syncVmFile, + removeVmFromDb, + clearActiveVmFromDb, + reconcileVms, + setVmDbSyncPgPool, + flushVmDbSyncAsync, + resetVmDbSyncState, + getVmDbSyncFailureCount, +} from '../../src/lib/vm/vm-db-sync.mjs' import { setVmWriteHook, atomicWriteJson } from '../../src/lib/vm/vm-file.mjs' import { persistOauthToVm } from '../../src/lib/oauth/oauth-credentials.mjs' import { clearScheduleHold, setVmSchedulable, setActiveVm } from '../../src/lib/vm/vm-registry.mjs' @@ -46,6 +57,8 @@ beforeEach(() => { afterEach(() => { stopVmWatch() setVmWriteHook(null) + setVmDbSyncPgPool(null) + resetVmDbSyncState() closeDatabase() fs.rmSync(project, { recursive: true, force: true }) delete process.env.KIN_DB_SECRET @@ -312,3 +325,164 @@ test('Codex VM mirror populates email/org_uuid/oauth_expires_at/oauth_source and assert.equal(row.vm.codex.has_access, true) assert.equal(row.vm.codex.has_refresh, true) }) + +test('PG mode removeVmFromDb cancels pending upsert and chains DELETE behind in-flight flush (A1/A8)', async () => { + seedVmFile('vm-del-queued') + seedVmFile('vm-del-inflight') + + const pgRows = new Map() + const executedOps = [] + let releaseInflightUpsert = null + let holdNextUpsert = false + + const mockPgPool = { + async query(sql, params) { + const text = String(sql) + if (/INSERT INTO vms\b/i.test(text)) { + // A8: dead token columns must never be written in PG UNNEST + assert.equal(/access_token|refresh_token|session_key/i.test(text), false, 'dead token cols omitted from PG SQL') + assert.equal(params.length, 21, 'PG UNNEST upsert must carry 21 live columns') + if (holdNextUpsert) { + holdNextUpsert = false + await new Promise((resolve) => { + releaseInflightUpsert = resolve + }) + } + const ids = params[0] || [] + for (let i = 0; i < ids.length; i += 1) { + pgRows.set(ids[i], { id: ids[i], vm_json: params[15][i] }) + executedOps.push(`upsert:${ids[i]}`) + } + return { rows: [], rowCount: ids.length } + } + if (/DELETE FROM vms WHERE id = \$1/i.test(text)) { + const id = params[0] + pgRows.delete(id) + executedOps.push(`delete:${id}`) + return { rows: [], rowCount: 1 } + } + if (/DELETE FROM codex_slot_runtime/i.test(text)) { + return { rows: [], rowCount: 0 } + } + return { rows: [], rowCount: 0 } + }, + } + + setVmDbSyncPgPool(mockPgPool) + + // Case 1: enqueue upsert then immediately removeVmFromDb before microtask runs -> row never resurrected + new VmsRepo(getDb()).upsertFromVmJson( + JSON.parse(fs.readFileSync(path.join(project, 'vms', 'vm-del-queued.json'), 'utf8')), + ) + syncVmFile(path.join(project, 'vms', 'vm-del-queued.json')) + assert.equal(removeVmFromDb('vm-del-queued'), true) + await flushVmDbSyncAsync() + assert.equal(pgRows.has('vm-del-queued'), false, 'queued upsert must not resurrect deleted slot') + assert.equal(executedOps.includes('upsert:vm-del-queued'), false) + assert.ok(executedOps.includes('delete:vm-del-queued')) + + // Case 2: upsert is already in flight when removeVmFromDb runs -> DELETE chains AFTER upsert + holdNextUpsert = true + syncVmFile(path.join(project, 'vms', 'vm-del-inflight.json')) + const inflightFlush = flushVmDbSyncAsync() + await new Promise((r) => setTimeout(r, 10)) + assert.ok(releaseInflightUpsert, 'upsert must be in flight') + assert.equal(removeVmFromDb('vm-del-inflight'), true) + releaseInflightUpsert() + await inflightFlush + await flushVmDbSyncAsync() + assert.equal(pgRows.has('vm-del-inflight'), false, 'chained DELETE must remove row written by in-flight upsert') + assert.deepEqual( + executedOps.filter((op) => op.endsWith(':vm-del-inflight')), + ['upsert:vm-del-inflight', 'delete:vm-del-inflight'], + ) +}) + +test('PG mode clearActiveVmFromDb resets _lastActiveVmId and chains DELETE onto _pgFlushChain (A9)', async () => { + const settings = new Map() + const activeOps = [] + const mockPgPool = { + async query(sql, params) { + const text = String(sql) + if (/INSERT INTO settings\b/i.test(text)) { + settings.set(params[0], params[1]) + activeOps.push(`set:${params[1]}`) + return { rows: [], rowCount: 1 } + } + if (/DELETE FROM settings WHERE key = \$1/i.test(text)) { + settings.delete(params[0]) + activeOps.push(`del:${params[0]}`) + return { rows: [], rowCount: 1 } + } + return { rows: [], rowCount: 0 } + }, + } + + setVmDbSyncPgPool(mockPgPool) + const activeFile = path.join(project, 'vms', 'active.json') + fs.mkdirSync(path.dirname(activeFile), { recursive: true }) + fs.writeFileSync(activeFile, JSON.stringify({ active_vm: 'vm-a9' })) + + syncVmFile(activeFile) + await flushVmDbSyncAsync() + assert.equal(settings.get('active_vm'), '"vm-a9"') + + // Clear active VM: must reset _lastActiveVmId and delete from settings on _pgFlushChain + assert.equal(clearActiveVmFromDb(), true) + await flushVmDbSyncAsync() + assert.equal(settings.has('active_vm'), false) + + // Re-activating the SAME VM id must not be skipped by a stale _lastActiveVmId + syncVmFile(activeFile) + await flushVmDbSyncAsync() + assert.equal(settings.get('active_vm'), '"vm-a9"') + assert.deepEqual(activeOps, ['set:"vm-a9"', 'del:active_vm', 'set:"vm-a9"']) +}) + +test('atomicWriteJson hook passes object to syncVmFile without re-reading disk and reconciles in bulk (A5/A10/A11)', async (t) => { + seedVmFile('vm-bulk-1') + seedVmFile('vm-bulk-2') + seedVmFile('vm-bulk-3') + initVmDbSync(project, { watch: false }) + + // A5: atomicWriteJson passes parsed object directly to hook -> zero fs.readFileSync on vm.json during write-through + const targetFile = path.join(project, 'vms', 'vm-bulk-1.json') + let readTargetCount = 0 + const origReadFileSync = fs.readFileSync + t.mock.method(fs, 'readFileSync', function (p, ...rest) { + if (String(p) === targetFile) readTargetCount += 1 + return origReadFileSync.call(this, p, ...rest) + }) + atomicWriteJson(targetFile, { id: 'vm-bulk-1', name: 'direct-pass', status: 'running', claude: { has_access: true } }) + assert.equal(readTargetCount, 0, 'write-through syncVmFile must skip re-reading vm.json when object is passed') + assert.equal(new VmsRepo(getDb()).get('vm-bulk-1').name, 'direct-pass') + + // A10: reconcileVms uses 1 bulk mtime SELECT and 1 list query instead of N per-file SELECTs + const db = getDb() + const origPrepare = db.prepare.bind(db) + let mtimeBulkQueries = 0 + let perRowGetQueries = 0 + let fullListQueries = 0 + t.mock.method(db, 'prepare', (sql) => { + const s = String(sql) + if (/SELECT id, file_mtime_ms FROM vms/i.test(s)) mtimeBulkQueries += 1 + if (/FROM vms WHERE id = \?/i.test(s)) perRowGetQueries += 1 + if (/FROM vms ORDER BY id/i.test(s)) fullListQueries += 1 + return origPrepare(sql) + }) + // Reset cached repo so VmsRepo prepares go through mock too + reconcileVms(project) + assert.equal(mtimeBulkQueries, 1, 'reconcileVms must load existing mtimes in a single query') + assert.equal(perRowGetQueries, 0, 'reconcileVms must not loop r.get() per file') + assert.ok(fullListQueries <= 1, 'reconcileVms must not run r.list() twice') + + // A11: mirror sync failure increments failure counter and emits throttled warn + const warns = [] + t.mock.method(console, 'warn', (msg) => warns.push(String(msg))) + const beforeFails = getVmDbSyncFailureCount() + assert.equal(syncVmFile(path.join(project, 'vms', 'does-not-exist.json')), false) + assert.equal(syncVmFile(path.join(project, 'vms', 'does-not-exist.json')), false) + assert.equal(getVmDbSyncFailureCount(), beforeFails + 2) + assert.equal(warns.length, 1, 'repeated failures for same file within throttle window emit 1 warn') + assert.match(warns[0], /\[vm-db-sync\] sync failed for does-not-exist\.json/) +}) diff --git a/test/unit/vm-file.test.mjs b/test/unit/vm-file.test.mjs index a749efc92b..e4dbd71a0f 100644 --- a/test/unit/vm-file.test.mjs +++ b/test/unit/vm-file.test.mjs @@ -12,6 +12,8 @@ import { vmLockBusy, readFileCached, invalidateReadCache, + setVmWriteHook, + getVmWriteHookFailureCount, VM_READ_CACHE_MAX_ENTRIES, } from '../../src/lib/vm/vm-file.mjs' import { getVm, listVms } from '../../src/lib/vm/vm-registry.mjs' @@ -278,3 +280,56 @@ test('disabled cache still distinguishes missing, corrupt, and I/O', () => { }) assert.equal(result.status, 0, `${result.stderr}\n${result.stdout}`) }) + +test('readFileCached detects same-size external rewrite even when mtime is restored (A7)', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-vf-a7-')) + t.after(() => { + invalidateReadCache() + fs.rmSync(dir, { recursive: true, force: true }) + }) + const file = path.join(dir, 'cred.json') + fs.writeFileSync(file, '{"tok":"aaaa1111"}') + const st1 = fs.statSync(file) + assert.equal(readFileCached(file), '{"tok":"aaaa1111"}') + + // External rewrite with identical byte length and explicitly restored mtime/atime. + fs.writeFileSync(file, '{"tok":"bbbb2222"}') + fs.utimesSync(file, st1.atime, st1.mtime) + assert.equal(readFileCached(file), '{"tok":"bbbb2222"}') +}) + +test('write hooks receive parsed object directly and throttle hook error warnings (A5/A11)', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-vf-hook-')) + t.after(() => { + setVmWriteHook(null) + fs.rmSync(dir, { recursive: true, force: true }) + }) + const seen = [] + setVmWriteHook((filePath, payload) => { + seen.push({ filePath, payload }) + }) + const file = path.join(dir, 'vm-01.json') + const doc1 = { id: 'vm-01', name: 'first' } + atomicWriteJson(file, doc1, { mode: 0o600 }) + assert.equal(seen.length, 1) + assert.equal(seen[0].filePath, file) + assert.equal(seen[0].payload, doc1) + + const doc2 = { id: 'vm-01', name: 'second' } + assert.equal(writeJsonIfChanged(file, doc2, { mode: 0o600 }), true) + assert.equal(seen.length, 2) + assert.equal(seen[1].payload, doc2) + + // Hook errors increment counter and emit throttled console.warn instead of silently swallowing. + const warns = [] + t.mock.method(console, 'warn', (msg) => warns.push(String(msg))) + const beforeCount = getVmWriteHookFailureCount() + setVmWriteHook(() => { + throw new Error('hook boom') + }) + atomicWriteJson(file, { id: 'vm-01', name: 'third' }, { mode: 0o600 }) + atomicWriteJson(file, { id: 'vm-01', name: 'fourth' }, { mode: 0o600 }) + assert.equal(getVmWriteHookFailureCount(), beforeCount + 2) + assert.equal(warns.length, 1, 'repeated hook errors on the same path within throttle window emit 1 warn') + assert.match(warns[0], /hook boom/) +}) From 432aaa2b8ab7c6501e689b1bdb1649422cfb862a Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 02:31:25 +0800 Subject: [PATCH 2/2] fix(account): address PR #2457 review findings (M1/m1/m2/m4/m5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前: - M1:`persistOauthToVm` 调用的 `clearClaudeAuthCooldown(vm)` 无条件执行 `clearVmTempPark(vm, { clearGeneration: true })`,凭据刷新镜像会同时抹掉 `markVmRestriction` 写下的配额/429 park(`isQuotaParkReason`),导致限额槽位提前恢复可调度。 - m1:`scheduler-runtime.mjs` 的 `tempUnschedulableState` 仍采用顶层优先读取(`vm.temp_unschedulable_until ?? vm.claude?...`),存量“顶层过期 + claude 有效”的 `vm.json` 上与 `readVmTempPark` 分叉。 - m2:`routing-runtime.mjs` 中 `applyRoutingOpenAIQuota` 与 `migrateLegacyOpenAIPolicies` 用默认 `getVm`(`mergeRuntime: true`)读改写 `atomicWriteJson`,会把 `CodexRuntimeStore` 运行态覆盖写入静态 `vm.json`。 - m4:`vm-db-sync.mjs` 的 `removeVmFromDb` 在 PG `DELETE FROM vms WHERE id = $1` 失败后于 `finally` 移出 `_pgPendingDeletes` 且不再重试,PG 瞬时抖动后可能被下次启动 `reconcileVms` 重建复活。 - m3 / m5:PR 原文对 PG 排序写表述偏强(实际受执行计划形状影响,应为“降低死锁概率”);`getVmDbSyncFailureCount` / `getVmWriteHookFailureCount` 为轻量化失败计数观测读接口并服务于单测断言。 - 改后: - `src/lib/oauth/oauth-credentials.mjs`:新增 `findPreservedQuotaPark`;`clearClaudeAuthCooldown` 在存在有效或 local 配额 park 时保留并回写双处镜像(仅清 `oauth_401_generation` 与认证类冷却),非配额认证冷却(如 `auth_failed` / `oauth_refresh_failed` / `authentication_failed_after_refresh`)照常双清;`clearVmAuthCooldown` 同步处理存量偏斜(一侧配额 + 另一侧认证冷却)。 - `src/lib/scheduler/scheduler-runtime.mjs`:`tempUnschedulableState` 复用 `readVmTempPark(vm, { now })` 统一 SSOT 读取,同时保持 `tempUnschedulableTelemetryFields` 在未激活/过期时的 `0 / null` double_option 清除语义。 - `src/lib/admin/routing-runtime.mjs`:`applyRoutingOpenAIQuota` 与 `migrateLegacyOpenAIPolicies` 的 RMW 读取改为 `getVm(..., { mergeRuntime: false })`,不再把 `CodexRuntimeStore` 运行态覆盖落盘到 `vm.json`。 - `src/lib/vm/vm-db-sync.mjs`:PG `DELETE` 纳入 `flushVmDbSyncAsync` 统一队列(与 `_pgPendingVms` 互斥去重),失败时若同 id 未被 `syncVmFile` 重建则重新入队 `_pgPendingDeletes` 并按指数退避 `.unref()` 定时器自动重试(`resetVmDbSyncState` / `stopVmWatch` / 解绑 pool 时清理);`schedulePgFlush` 通过序列号避免显式 flush 后微任务重复触发。 - 补齐 `test/unit/{oauth-credentials,scheduler-codex-quota-snapshot,routing-runtime-load,vm-db-sync}.test.mjs` 定向回归单测。 - 未改 / 延后:保持 `getVmDbSyncFailureCount` / `getVmWriteHookFailureCount` 用于故障计数观测与单测校验;未改 `availability.mjs` / `panel-api.mjs` / `codex-slot-pool.mjs` 其余存量读取点;未拆 PR、未改 `CHANGELOG.md`。 ## 验收记录(Run) - 环境与基线:WSL2 Debian (Node v24.13.0) + Windows git.exe,工作树 `X:\vm2api-wt-fix-2457`,合入最新 `origin/dev` (`a91fd8811`) 无冲突 - 已跑命令与结果: - `npx biome format --write <8 files> && npx biome check <8 files>`: PASS (8 files clean, 0 errors) - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS (0 syntax errors) - `KIN_SCHEDULER_BIN=/tmp/kin-sched-target/release/kin-scheduler node --test --test-concurrency=4 test/unit/{oauth-credentials,pool-scheduler,vm-db-sync,vm-file,health-probe,routing-runtime-load,scheduler-codex-quota-snapshot,scheduler-m3-cutover,request-redis-opt,rate-limit-service,api-keys,proxy-pool-bind,schedule-state-registry,panel-vm-delete,panel-vm-deactivate,panel-vm-active-hours,panel-vm-pool-policy,vm-rename,slot-engine,runtime-state,backup-service,legacy-import}.test.mjs`: PASS (22 files, 321/321 tests pass, 0 fail, 0 skipped) - `VM2API_TEST_CONCURRENCY=4 KIN_SCHEDULER_BIN=/tmp/kin-sched-target/release/kin-scheduler npm run test:ci`: PASS (13/13 isolated test files, 250/250 tests pass, 0 fail, 0 skipped) ## 回退与手破验证(Broken by hand) - 临时回退 M1 守卫(`clearClaudeAuthCooldown` 改回无条件 `clearVmTempPark(vm, { clearGeneration: true })`)-> `persistOauthToVm and mirrorWorkerCredentialsToVm preserve active quota parks while clearing auth cooldowns (M1)` FAIL(`AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: undefined !== 1796153407920`)-> 恢复后 `test/unit/oauth-credentials.test.mjs` 33/33 PASS ## 真实使用(Real use) - 本轮使用 WSL 本地编译的真实 `kin-scheduler` 二进制(`/tmp/kin-sched-target/release/kin-scheduler`)运行 `test:ci` 全部 13 个隔离套件及 `scheduler-m3-cutover` / `scheduler-codex-quota-snapshot`;未在真 PG18 容器或生产机 `ph24` 上复跑(前序 commit `e4a1a52e5` 已在真 PG18 验证 UNNEST 写入与列映射)。 ## 未运行项(Not run) - 未运行全量 553 文件 `npm run test:unit`、真 PG18 一次性容器(本次 m4 用故障注入 mock PG pool 验证重试状态机)、Web 前端构建、ARM64 与生产机 `ph24` 联调:本次修订限定于评审指出的 4 个后端源文件和 4 个单测文件(共 8 文件),已通过语法检查、Biome、22 个关联单测(321 用例)与完整 `test:ci`(13 套件 / 250 用例)。 --- src/lib/admin/routing-runtime.mjs | 4 +- src/lib/oauth/oauth-credentials.mjs | 37 +++++- src/lib/scheduler/scheduler-runtime.mjs | 21 ++-- src/lib/vm/vm-db-sync.mjs | 96 +++++++++++++--- test/unit/oauth-credentials.test.mjs | 105 ++++++++++++++++++ test/unit/routing-runtime-load.test.mjs | 87 +++++++++++++++ .../scheduler-codex-quota-snapshot.test.mjs | 49 ++++++++ test/unit/vm-db-sync.test.mjs | 77 +++++++++++++ 8 files changed, 440 insertions(+), 36 deletions(-) diff --git a/src/lib/admin/routing-runtime.mjs b/src/lib/admin/routing-runtime.mjs index af69f16d07..ef7099e7d7 100644 --- a/src/lib/admin/routing-runtime.mjs +++ b/src/lib/admin/routing-runtime.mjs @@ -306,7 +306,7 @@ export function createRoutingRuntime(ctx) { const applied = { concurrency: 0, rpm: 0, sessions: 0, skipped: 0 } for (const listed of listVms(ctx.cfg.paths.project, getRouting())) { if (!listed.codex_kernel && listed.platform !== 'openai' && listed.family !== 'codex') continue - const stored = getVm(ctx.cfg.paths.project, listed.id) + const stored = getVm(ctx.cfg.paths.project, listed.id, { mergeRuntime: false }) if (!stored) continue const current = stored.policy || {} const patch = {} @@ -850,7 +850,7 @@ export function createRoutingRuntime(ctx) { const quota = normalizeOpenAIQuotaPolicy(doc.codex?.quota) for (const summary of listVms(ctx.cfg.paths.project)) { if (!isCodexVm(summary)) continue - const stored = getVm(ctx.cfg.paths.project, summary.id) + const stored = getVm(ctx.cfg.paths.project, summary.id, { mergeRuntime: false }) if (!stored) continue const policy = stored.policy || {} const nextPolicy = { ...policy } diff --git a/src/lib/oauth/oauth-credentials.mjs b/src/lib/oauth/oauth-credentials.mjs index 7794e524a8..5d3a481a12 100644 --- a/src/lib/oauth/oauth-credentials.mjs +++ b/src/lib/oauth/oauth-credentials.mjs @@ -993,7 +993,36 @@ export function clearVmTempPark(vm, { clearGeneration = false } = {}) { return vm } -function clearClaudeAuthCooldown(vm) { +function findPreservedQuotaPark(vm, { now = Date.now() } = {}) { + if (!vm || typeof vm !== 'object') return null + const topUntil = parseTempParkUntilMs(vm.temp_unschedulable_until) + const claudeUntil = parseTempParkUntilMs(vm.claude?.temp_unschedulable_until) + const topReason = String(vm.temp_unschedulable_reason || '').trim() || null + const claudeReason = String(vm.claude?.temp_unschedulable_reason || '').trim() || null + + const topIsQuota = isQuotaParkReason(topReason) && (topUntil > now || topUntil === 0) + const claudeIsQuota = isQuotaParkReason(claudeReason) && (claudeUntil > now || claudeUntil === 0) + if (topIsQuota && claudeIsQuota) { + return topUntil >= claudeUntil + ? { until: topUntil || null, reason: topReason } + : { until: claudeUntil || null, reason: claudeReason } + } + if (topIsQuota) return { until: topUntil || null, reason: topReason } + if (claudeIsQuota) return { until: claudeUntil || null, reason: claudeReason } + return null +} + +function clearClaudeAuthCooldown(vm, { now = Date.now() } = {}) { + if (!vm || typeof vm !== 'object') return vm + const preservedQuota = findPreservedQuotaPark(vm, { now }) + if (preservedQuota) { + setVmTempPark(vm, { until: preservedQuota.until, reason: preservedQuota.reason, now }) + if (vm.claude && typeof vm.claude === 'object') { + vm.claude = { ...vm.claude } + delete vm.claude.oauth_401_generation + } + return vm + } return clearVmTempPark(vm, { clearGeneration: true }) } @@ -1068,7 +1097,11 @@ export function clearVmAuthCooldown(vmPath) { if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) const park = readVmTempPark(vm) - if (isQuotaParkReason(park.reason)) return vm + const hasSkewedAuthPark = + (vm.claude?.temp_unschedulable_reason && !isQuotaParkReason(vm.claude.temp_unschedulable_reason)) || + (vm.temp_unschedulable_reason && !isQuotaParkReason(vm.temp_unschedulable_reason)) || + Boolean(vm.claude?.oauth_401_generation) + if (isQuotaParkReason(park.reason) && !hasSkewedAuthPark) return vm const had = park.until || park.reason || diff --git a/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index 4c42b7ad3f..59f0ccd113 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -70,6 +70,7 @@ import { import { canonicalPersonaCompat, personaPresetFromLegacyMode } from '../identity/persona-template.mjs' import { normalizeUnifiedPreset } from '../identity/system-prompt-spec.mjs' import { activeHoursOf, evaluateActiveHours } from '../pool/active-hours.mjs' +import { readVmTempPark } from '../oauth/oauth-credentials.mjs' import { buildApiEndpointTelemetryUpdate, endpointMatchesModel, stripPrefix } from '../pool/api-scheduler.mjs' import { isLeftoverQuotaScheduleOff } from '../pool/availability.mjs' import { isCodexSlotParked } from '../pool/codex-slot-pool.mjs' @@ -387,21 +388,13 @@ function extractQuotaPctsForVm(vm, acct, now) { return { u5, u7 } } -function parseTempUnschedulableUntilMs(vm) { - const raw = vm?.temp_unschedulable_until ?? vm?.claude?.temp_unschedulable_until - if (raw == null || raw === '') return null - const asNum = Number(raw) - if (Number.isFinite(asNum) && asNum > 0) return Math.floor(asNum) - const parsed = Date.parse(String(raw)) - return Number.isFinite(parsed) && parsed > 0 ? parsed : null -} - function tempUnschedulableState(vm, now = Date.now()) { - const untilMs = parseTempUnschedulableUntilMs(vm) - const reasonRaw = vm?.temp_unschedulable_reason ?? vm?.claude?.temp_unschedulable_reason ?? null - const reason = reasonRaw != null && String(reasonRaw).trim() ? String(reasonRaw).trim() : null - const active = untilMs != null && untilMs > now - return { active, untilMs: active ? untilMs : null, reason } + const park = readVmTempPark(vm, { now }) + return { + active: park.active, + untilMs: park.active ? park.until : null, + reason: park.reason, + } } /** Telemetry wire values: cleared slots send `0` / `null` so Rust will not fall back to stale snapshot until. */ diff --git a/src/lib/vm/vm-db-sync.mjs b/src/lib/vm/vm-db-sync.mjs index cd81c0814f..ff40d5832c 100644 --- a/src/lib/vm/vm-db-sync.mjs +++ b/src/lib/vm/vm-db-sync.mjs @@ -32,6 +32,8 @@ import { migrateScheduleFields, reclaimAssignedVms, repairSlotSmbios, repairVmPr const ACTIVE_VM_KEY = 'active_vm' const WATCH_DEBOUNCE_MS = 500 const PG_UPSERT_BATCH_CHUNK = 100 +const PG_DELETE_RETRY_BASE_MS = 1_000 +const PG_DELETE_RETRY_MAX_MS = 30_000 const DB_SYNC_WARN_THROTTLE_MS = 30_000 const DB_SYNC_WARN_CACHE_MAX = 1024 @@ -44,7 +46,11 @@ let _watchFullScan = false let _lastActiveVmId = null let _pgPendingActive = undefined let _pgFlushScheduled = false +let _pgFlushSeq = 0 +let _pgScheduledSeq = 0 let _pgFlushChain = Promise.resolve() +let _pgDeleteRetryTimer = null +let _pgDeleteRetryAttempts = 0 let _mirrorFailureCount = 0 const _lastSyncedMtime = new Map() // filePath -> Math.floor(mtimeMs) @@ -93,6 +99,10 @@ function resolvePgPool() { /** Optional test/runtime seam to bind or clear an explicit async pgPool. */ export function setVmDbSyncPgPool(pgPool = null) { _explicitPgPool = pgPool || null + if (!_explicitPgPool) { + clearPgDeleteRetryTimer() + _pgDeleteRetryAttempts = 0 + } } async function upsertVmsPgAsync(pgPool, entries) { @@ -191,32 +201,62 @@ async function upsertActiveVmPgAsync(pgPool, activeVmId) { ) } +function clearPgDeleteRetryTimer() { + if (_pgDeleteRetryTimer) { + clearTimeout(_pgDeleteRetryTimer) + _pgDeleteRetryTimer = null + } +} + +function schedulePgDeleteRetry() { + if (_pgPendingDeletes.size === 0 || _pgDeleteRetryTimer) return + const delay = Math.min(PG_DELETE_RETRY_BASE_MS * 2 ** Math.min(_pgDeleteRetryAttempts, 5), PG_DELETE_RETRY_MAX_MS) + _pgDeleteRetryAttempts += 1 + _pgDeleteRetryTimer = setTimeout(() => { + _pgDeleteRetryTimer = null + if (_pgPendingDeletes.size === 0) return + void flushVmDbSyncAsync().catch((err) => { + recordVmDbSyncFailure('pg-delete-retry', 'flush', err) + }) + }, delay) + if (typeof _pgDeleteRetryTimer.unref === 'function') _pgDeleteRetryTimer.unref() +} + function schedulePgFlush() { + _pgScheduledSeq = _pgFlushSeq if (_pgFlushScheduled) return _pgFlushScheduled = true queueMicrotask(() => { _pgFlushScheduled = false + if (_pgFlushSeq > _pgScheduledSeq) return void flushVmDbSyncAsync().catch((err) => { recordVmDbSyncFailure('pg-flush', 'flush', err) }) }) } -/** Drain all pending async PostgreSQL VM mirror upserts (no-op in SQLite mode). */ +/** Drain all pending async PostgreSQL VM mirror upserts and deletes (no-op in SQLite mode). */ export function flushVmDbSyncAsync() { + _pgFlushSeq += 1 const run = async () => { const pgPool = resolvePgPool() if (!pgPool) { _pgPendingVms.clear() + _pgPendingDeletes.clear() _pgPendingActive = undefined - return { upserted: 0, activeUpdated: false } + clearPgDeleteRetryTimer() + _pgDeleteRetryAttempts = 0 + return { upserted: 0, deleted: 0, activeUpdated: false } } let upserted = 0 + let deleted = 0 let activeUpdated = false for (let round = 0; round < 8; round += 1) { - if (_pgPendingVms.size === 0 && _pgPendingActive === undefined) break + if (_pgPendingVms.size === 0 && _pgPendingDeletes.size === 0 && _pgPendingActive === undefined) break const vmEntries = [..._pgPendingVms.entries()] _pgPendingVms.clear() + const deleteIds = [..._pgPendingDeletes] + _pgPendingDeletes.clear() const pendingActive = _pgPendingActive _pgPendingActive = undefined const mutated = [] @@ -234,20 +274,44 @@ export function flushVmDbSyncAsync() { activeUpdated = true mutated.push('settings') } - if (mutated.length > 0) { - notifyDbTablesMutated(mutated) - } } catch (err) { + for (const id of deleteIds) { + if (!_pgPendingVms.has(id)) _pgPendingDeletes.add(id) + } for (const [id, item] of vmEntries) { if (!_pgPendingVms.has(id) && !_pgPendingDeletes.has(id)) _pgPendingVms.set(id, item) } if (pendingActive !== undefined && _pgPendingActive === undefined) { _pgPendingActive = pendingActive } + if (_pgPendingDeletes.size > 0) schedulePgDeleteRetry() throw err } + let deleteFailed = false + for (const id of deleteIds) { + try { + await pgPool.query('DELETE FROM vms WHERE id = $1', [id]) + deleted += 1 + if (!mutated.includes('vms')) mutated.push('vms') + } catch (err) { + recordVmDbSyncFailure(id, 'pg-delete', err) + if (!_pgPendingVms.has(id)) _pgPendingDeletes.add(id) + deleteFailed = true + } + } + if (mutated.length > 0) { + notifyDbTablesMutated(mutated) + } + if (deleteFailed) { + if (_pgPendingDeletes.size > 0) schedulePgDeleteRetry() + break + } + if (_pgPendingDeletes.size === 0) { + clearPgDeleteRetryTimer() + _pgDeleteRetryAttempts = 0 + } } - return { upserted, activeUpdated } + return { upserted, deleted, activeUpdated } } const next = _pgFlushChain.then(run, run) _pgFlushChain = next.catch(() => {}) @@ -323,17 +387,7 @@ export function removeVmFromDb(id) { let removed = false if (pgPool) { _pgPendingDeletes.add(key) - const del = _pgFlushChain.then(async () => { - try { - await pgPool.query('DELETE FROM vms WHERE id = $1', [key]) - notifyDbTablesMutated(['vms']) - } catch (err) { - recordVmDbSyncFailure(key, 'pg-delete', err) - } finally { - _pgPendingDeletes.delete(key) - } - }) - _pgFlushChain = del.catch(() => {}) + schedulePgFlush() removed = true } else { removed = r.remove(id) @@ -671,6 +725,8 @@ export function stopVmWatch() { clearTimeout(_watchTimer) _watchTimer = null } + clearPgDeleteRetryTimer() + _pgDeleteRetryAttempts = 0 _watchDirtyFiles.clear() _watchFullScan = false if (_watcher) { @@ -683,6 +739,8 @@ export function stopVmWatch() { /** Test helper: inspect/clear in-process mtime cache. */ export function resetVmDbSyncState() { + clearPgDeleteRetryTimer() + _pgDeleteRetryAttempts = 0 _lastSyncedMtime.clear() _watchDirtyFiles.clear() _watchFullScan = false @@ -691,6 +749,8 @@ export function resetVmDbSyncState() { _pgPendingDeletes.clear() _pgPendingActive = undefined _pgFlushScheduled = false + _pgFlushSeq = 0 + _pgScheduledSeq = 0 _mirrorFailureCount = 0 _lastWarnAtByKey.clear() } diff --git a/test/unit/oauth-credentials.test.mjs b/test/unit/oauth-credentials.test.mjs index 79ea387f87..d962f453dd 100644 --- a/test/unit/oauth-credentials.test.mjs +++ b/test/unit/oauth-credentials.test.mjs @@ -5,10 +5,13 @@ import os from 'node:os' import path from 'node:path' import { runInNewContext } from 'node:vm' import { listVms, isCodexVm, summarizeVm } from '../../src/lib/vm/vm-registry.mjs' +import { evaluateAccount } from '../../src/lib/pool/availability.mjs' +import { createSchedulerRuntime } from '../../src/lib/scheduler/scheduler-runtime.mjs' import { needsRefresh, expiresAtToMs, normalizeOauth, + mirrorWorkerCredentialsToVm, persistOauthToVm, markVmRestriction, clearVmQuotaRestriction, @@ -814,3 +817,105 @@ test('temp park SSOT keeps claude.* and top-level identical across expired quota fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('persistOauthToVm and mirrorWorkerCredentialsToVm preserve active quota parks while clearing auth cooldowns (M1)', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-oauth-m1-quota-')) + try { + const vmPath = path.join(dir, 'vm-m1.json') + const homeDir = path.join(dir, 'cli-home') + const now = Date.now() + const quotaUntil = now + 3_600_000 + fs.writeFileSync( + vmPath, + JSON.stringify({ + id: 'vm-m1', + status: 'running', + schedulable: true, + claude: { has_access: true, has_refresh: true }, + }), + ) + + // 1. Quota park via markVmRestriction MUST survive persistOauthToVm and mirrorWorkerCredentialsToVm + markVmRestriction(vmPath, { until: quotaUntil, reason: 'quota_5h' }) + persistOauthToVm(vmPath, { + access_token: 'sk-ant-oat01-FRESH', + refresh_token: 'sk-ant-ort01-FRESH', + expires_at: now + 7_200_000, + }) + writeWorkerCredentialFile(homeDir, { + access_token: 'sk-ant-oat01-MIRRORED', + refresh_token: 'sk-ant-ort01-MIRRORED', + expires_at: now + 7_200_000, + }) + mirrorWorkerCredentialsToVm(vmPath, homeDir) + + let vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, quotaUntil) + assert.equal(vm.temp_unschedulable_reason, 'quota_5h') + assert.equal(vm.claude.temp_unschedulable_until, quotaUntil) + assert.equal(vm.claude.temp_unschedulable_reason, 'quota_5h') + assert.deepEqual(readVmTempPark(vm, { now }), { + until: quotaUntil, + reason: 'quota_5h', + active: true, + }) + + // Both downstream readers (scheduler-runtime & availability) must still see the active quota park. + const avail = evaluateAccount({ vm, now }) + assert.equal(avail.accept, false) + assert.equal(avail.key, 'cool') + assert.equal(avail.reason, 'cooldown') + assert.equal(avail.until, quotaUntil) + const schedRuntime = createSchedulerRuntime({ + cfg: { paths: { project: '' } }, + getRoutingConfig: () => ({ pool: {}, concurrency: {} }), + getVms: () => [vm], + accountQuota: {}, + client: { isStandby: true, stopped: true }, + telemetryIntervalMs: 0, + }) + const tel = schedRuntime.buildTelemetryBatch({ now }).find((u) => u.node_key === 'claude_vm:vm-m1') + assert.ok(tel) + assert.equal(tel.schedulable, false) + assert.equal(tel.temp_unschedulable_until_ms, quotaUntil) + assert.equal(tel.temp_unschedulable_reason, 'quota_5h') + + // 2. Legacy skewed record: top-level quota park + claude auth cooldown -> refresh drops auth cooldown & preserves quota park on both mirrors + vm.temp_unschedulable_until = quotaUntil + vm.temp_unschedulable_reason = 'quota_5h' + vm.claude.temp_unschedulable_until = now + 7_200_000 + vm.claude.temp_unschedulable_reason = 'authentication_failed_after_refresh' + vm.claude.oauth_401_generation = 4 + fs.writeFileSync(vmPath, JSON.stringify(vm)) + + persistOauthToVm(vmPath, { + access_token: 'sk-ant-oat01-HEAL-SKEW', + refresh_token: 'sk-ant-ort01-HEAL-SKEW', + expires_at: now + 9_000_000, + }) + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, quotaUntil) + assert.equal(vm.temp_unschedulable_reason, 'quota_5h') + assert.equal(vm.claude.temp_unschedulable_until, quotaUntil) + assert.equal(vm.claude.temp_unschedulable_reason, 'quota_5h') + assert.equal(vm.claude.oauth_401_generation, undefined) + + // 3. Non-quota auth cooldowns ('auth_failed', 'oauth_refresh_failed') ARE cleared on refresh + for (const authReason of ['auth_failed', 'oauth_refresh_failed']) { + markVmAuthCooldown(vmPath, { until: now + 300_000, reason: authReason, generation: 8 }) + persistOauthToVm(vmPath, { + access_token: `sk-ant-oat01-${authReason}`, + refresh_token: `sk-ant-ort01-${authReason}`, + expires_at: now + 10_000_000, + }) + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.temp_unschedulable_until, undefined, `${authReason} must clear top-level until`) + assert.equal(vm.temp_unschedulable_reason, undefined, `${authReason} must clear top-level reason`) + assert.equal(vm.claude.temp_unschedulable_until, undefined, `${authReason} must clear claude until`) + assert.equal(vm.claude.temp_unschedulable_reason, undefined, `${authReason} must clear claude reason`) + assert.equal(vm.claude.oauth_401_generation, undefined) + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/routing-runtime-load.test.mjs b/test/unit/routing-runtime-load.test.mjs index 5a03b653dc..d5c6528ef0 100644 --- a/test/unit/routing-runtime-load.test.mjs +++ b/test/unit/routing-runtime-load.test.mjs @@ -8,6 +8,7 @@ import { createRoutingRuntime } from '../../src/lib/admin/routing-runtime.mjs' import { buildRouting } from '../../src/lib/admin/panel-api.mjs' import { DEFAULT_CODEX_ROUTING } from '../../src/lib/protocol/codex-route.mjs' import { OFFICIAL_CLI_VERSION } from '../../src/lib/identity/vm-identity.mjs' +import { mergeCodexRuntimeIntoVm, setActiveCodexRuntimeStore } from '../../src/lib/pool/codex-runtime-store.mjs' function runtimeFor(file) { return createRoutingRuntime({ routingConfigPath: file }) @@ -897,3 +898,89 @@ test('persistRoutingPatch merges and normalizes batch_group and loadRoutingConfi fs.rmSync(root, { recursive: true, force: true }) } }) + +test('applyRoutingOpenAIQuota and legacy OpenAI migration read disk VM without persisting CodexRuntimeStore overlay (m2)', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-routing-codex-overlay-')) + const vmsDir = path.join(root, 'vms') + const routingFile = path.join(root, 'routing.json') + const vmFile = path.join(vmsDir, 'vm-codex-m2.json') + fs.mkdirSync(vmsDir, { recursive: true }) + const diskVm = { + id: 'vm-codex-m2', + name: 'codex-m2', + platform: 'openai', + family: 'codex', + codex_kernel: true, + status: 'running', + refresh_error: 'disk_refresh_err', + codex: { + email: 'disk@example.com', + plan_type: 'plus', + refresh_error: 'disk_refresh_err', + refresh_error_at: '2026-01-01T00:00:00.000Z', + }, + policy: { maxConcurrency: 2, maxRpm: 0, maxSessions: 0 }, + } + fs.writeFileSync(vmFile, JSON.stringify(diskVm, null, 2)) + fs.writeFileSync(routingFile, JSON.stringify({ codex: {} })) + + const runtimeRecord = { + vm_id: 'vm-codex-m2', + email: 'runtime-overlay@example.com', + plan_type: 'pro', + refresh_error: null, + refresh_error_at: null, + extra: { + codex_5h_used_percent: 42, + codex_7d_used_percent: 15, + }, + used_5h_pct: 42, + used_7d_pct: 15, + usage_updated_at: '2026-02-01T00:00:00.000Z', + updated_at: '2026-02-01T00:00:00.000Z', + } + setActiveCodexRuntimeStore({ + mergeVm(vm) { + return vm?.id === 'vm-codex-m2' ? mergeCodexRuntimeIntoVm(vm, runtimeRecord) : vm + }, + }) + + try { + const runtime = createRoutingRuntime({ + cfg: { paths: { project: root } }, + routingConfigPath: routingFile, + routingConfig: { codex: { quota: { max_concurrency: 5, max_rpm: 30, max_sessions: 4 } } }, + }) + + // 1. Legacy migration via loadRoutingConfig (routing.json lacks codex.quota) + runtime.loadRoutingConfig() + let saved = JSON.parse(fs.readFileSync(vmFile, 'utf8')) + assert.equal(saved.refresh_error, 'disk_refresh_err') + assert.equal(saved.codex.refresh_error, 'disk_refresh_err') + assert.equal(saved.codex.refresh_error_at, '2026-01-01T00:00:00.000Z') + assert.equal(saved.codex.email, 'disk@example.com') + assert.equal(saved.codex.plan_type, 'plus') + assert.equal(saved.codex.usage, undefined) + assert.equal(saved.codex.extra, undefined) + + // 2. applyRoutingOpenAIQuota updates policy without leaking runtime overlay into vm.json + const applied = runtime.applyRoutingOpenAIQuota({ max_concurrency: 5, max_rpm: 30, max_sessions: 4 }) + assert.equal(applied.concurrency, 1) + assert.equal(applied.rpm, 1) + assert.equal(applied.sessions, 1) + saved = JSON.parse(fs.readFileSync(vmFile, 'utf8')) + assert.equal(saved.policy.maxConcurrency, 5) + assert.equal(saved.policy.maxRpm, 30) + assert.equal(saved.policy.maxSessions, 4) + assert.equal(saved.refresh_error, 'disk_refresh_err') + assert.equal(saved.codex.refresh_error, 'disk_refresh_err') + assert.equal(saved.codex.refresh_error_at, '2026-01-01T00:00:00.000Z') + assert.equal(saved.codex.email, 'disk@example.com') + assert.equal(saved.codex.plan_type, 'plus') + assert.equal(saved.codex.usage, undefined) + assert.equal(saved.codex.extra, undefined) + } finally { + setActiveCodexRuntimeStore(null) + fs.rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/test/unit/scheduler-codex-quota-snapshot.test.mjs b/test/unit/scheduler-codex-quota-snapshot.test.mjs index e9204fb591..8f89330550 100644 --- a/test/unit/scheduler-codex-quota-snapshot.test.mjs +++ b/test/unit/scheduler-codex-quota-snapshot.test.mjs @@ -4,6 +4,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { OPENAI_QUOTA_DEFAULTS } from '../../src/lib/pool/openai-quota-policy.mjs' +import { readVmTempPark } from '../../src/lib/oauth/oauth-credentials.mjs' import { createSchedulerRuntime } from '../../src/lib/scheduler/scheduler-runtime.mjs' function makeRuntime(overrides = {}) { @@ -199,3 +200,51 @@ test('SchedulerRuntime overlays byCodexRuntimeByVmId snapshot and enqueueCodexVm assert.equal(enqueued.length, 1) assert.equal(enqueued[0].temp_unschedulable_until_ms, now + 60_000) }) + +test('scheduler-runtime uses readVmTempPark SSOT on legacy skewed expired top-level + active claude park (m1)', () => { + const now = Date.now() + const activeClaudeUntil = now + 180_000 + const skewedVm = { + id: 'claude-skewed', + platform: 'claude', + status: 'running', + schedulable: true, + temp_unschedulable_until: now - 60_000, + temp_unschedulable_reason: 'quota_5h', + claude: { + has_access: true, + has_refresh: true, + temp_unschedulable_until: activeClaudeUntil, + temp_unschedulable_reason: 'authentication_failed_after_refresh', + }, + } + const ssot = readVmTempPark(skewedVm, { now }) + assert.deepEqual(ssot, { + until: activeClaudeUntil, + reason: 'authentication_failed_after_refresh', + active: true, + }) + + const { runtime } = makeRuntime({ vms: [skewedVm] }) + const snap = runtime.buildConfigSnapshot() + const nodeCfg = snap.nodes.find((n) => n.node_id === 'claude-skewed') + assert.ok(nodeCfg) + assert.equal(nodeCfg.temp_unschedulable_until_ms, activeClaudeUntil) + assert.equal(nodeCfg.temp_unschedulable_reason, 'authentication_failed_after_refresh') + + const update = runtime.buildTelemetryBatch({ now }).find((u) => u.node_key === 'claude_vm:claude-skewed') + assert.ok(update) + assert.equal(update.schedulable, false) + assert.equal(update.unschedulable_reason, 'authentication_failed_after_refresh') + assert.equal(update.temp_unschedulable_until_ms, activeClaudeUntil) + assert.equal(update.temp_unschedulable_reason, 'authentication_failed_after_refresh') + + // Once both mirrors expire, telemetry still emits explicit 0 / null for Rust double_option clear semantics + const afterExpiry = runtime + .buildTelemetryBatch({ now: activeClaudeUntil + 1_000 }) + .find((u) => u.node_key === 'claude_vm:claude-skewed') + assert.ok(afterExpiry) + assert.equal(afterExpiry.schedulable, true) + assert.equal(afterExpiry.temp_unschedulable_until_ms, 0) + assert.equal(afterExpiry.temp_unschedulable_reason, null) +}) diff --git a/test/unit/vm-db-sync.test.mjs b/test/unit/vm-db-sync.test.mjs index 12beb2c433..3111e33268 100644 --- a/test/unit/vm-db-sync.test.mjs +++ b/test/unit/vm-db-sync.test.mjs @@ -486,3 +486,80 @@ test('atomicWriteJson hook passes object to syncVmFile without re-reading disk a assert.equal(warns.length, 1, 'repeated failures for same file within throttle window emit 1 warn') assert.match(warns[0], /\[vm-db-sync\] sync failed for does-not-exist\.json/) }) + +test('PG mode removeVmFromDb re-queues failed DELETE and succeeds once PG recovers (m4)', async (t) => { + const pgRows = new Map([ + ['vm-del-retry', { id: 'vm-del-retry' }], + ['vm-del-recreate', { id: 'vm-del-recreate' }], + ]) + let failDeletes = true + const deleteAttempts = [] + const mockPgPool = { + async query(sql, params) { + const text = String(sql) + if (/INSERT INTO vms\b/i.test(text)) { + const ids = params[0] || [] + for (let i = 0; i < ids.length; i += 1) { + pgRows.set(ids[i], { id: ids[i], vm_json: params[15][i] }) + } + return { rows: [], rowCount: ids.length } + } + if (/DELETE FROM vms WHERE id = \$1/i.test(text)) { + const id = params[0] + deleteAttempts.push(id) + if (failDeletes) { + throw new Error('pg connection reset') + } + pgRows.delete(id) + return { rows: [], rowCount: 1 } + } + return { rows: [], rowCount: 0 } + }, + } + + const warns = [] + t.mock.method(console, 'warn', (msg) => warns.push(String(msg))) + setVmDbSyncPgPool(mockPgPool) + + // Attempt 1 fails -> failure counted, row still in PG, delete re-queued in _pgPendingDeletes + const beforeFails = getVmDbSyncFailureCount() + assert.equal(removeVmFromDb('vm-del-retry'), true) + const r1 = await flushVmDbSyncAsync() + assert.equal(r1.deleted, 0) + assert.equal(pgRows.has('vm-del-retry'), true) + assert.ok(getVmDbSyncFailureCount() >= beforeFails + 1) + + // Duplicate removeVmFromDb while queued deduplicates; still fails while PG is down -> stays queued + const failsBeforeDup = getVmDbSyncFailureCount() + assert.equal(removeVmFromDb('vm-del-retry'), true) + const r2 = await flushVmDbSyncAsync() + assert.equal(r2.deleted, 0) + assert.equal(pgRows.has('vm-del-retry'), true) + assert.ok(getVmDbSyncFailureCount() >= failsBeforeDup + 1) + assert.equal(warns.length, 1, 'throttled warn for repeated pg-delete failures on same id') + + // PG recovers -> next flush retries the re-queued DELETE once and removes the row + failDeletes = false + const attemptsBeforeRecovery = deleteAttempts.length + const r3 = await flushVmDbSyncAsync() + assert.equal(r3.deleted, 1) + assert.equal(deleteAttempts.length, attemptsBeforeRecovery + 1, 'deduplicated pending delete runs once on recovery') + assert.equal(pgRows.has('vm-del-retry'), false, 'retried DELETE must remove row once PG recovers') + const attemptsAfterRecovery = deleteAttempts.length + const r4 = await flushVmDbSyncAsync() + assert.equal(r4.deleted, 0) + assert.equal(deleteAttempts.length, attemptsAfterRecovery, 'completed DELETE must not repeat') + + // Recreating a slot while a failed DELETE is queued cancels the stale DELETE so the new row survives + failDeletes = true + assert.equal(removeVmFromDb('vm-del-recreate'), true) + await flushVmDbSyncAsync() + assert.equal(pgRows.has('vm-del-recreate'), true) + failDeletes = false + seedVmFile('vm-del-recreate', { name: 'reborn' }) + syncVmFile(path.join(project, 'vms', 'vm-del-recreate.json')) + const r5 = await flushVmDbSyncAsync() + assert.equal(r5.upserted, 1) + assert.equal(r5.deleted, 0) + assert.equal(pgRows.has('vm-del-recreate'), true, 'recreated VM must survive stale failed DELETE') +})