Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 49 additions & 20 deletions src/lib/admin/api-keys.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 : []
}

Expand Down
32 changes: 18 additions & 14 deletions src/lib/admin/health-probe.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/admin/routing-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand Down Expand Up @@ -880,7 +880,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 }
Expand Down
29 changes: 13 additions & 16 deletions src/lib/db/repos/vms-repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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))
}
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading