From 9c6c50c93b7278947ed709892a74cde05c0b1ece Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 21:02:54 +0800 Subject: [PATCH 1/2] fix(panel,db): align PG pre-agg metrics, async reprice, query shapes, N+1, locks, and cache invalidation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前: 1. `StatisticsRepo._totalsFromPreAgg` / `_modelLeaderboardFromPreAgg` 未读取 `016` 新增的 `cache_creation_5m_tokens`、`cache_creation_1h_tokens`、`total_ttft_ms`、`ttft_count`、`total_duration_ms`、`duration_count`,PG 预聚合统计在封口桶上丢失 5m/1h 缓存与 TTFT/耗时均值; 2. `UsageLogsView.listBatch` 对 `account_id`/`model` 使用单条 `OR` 谓词易触发 PG 休眠实体全表回表,`listBatchAsync` 在与 PG 页去重前对 live 条目全量过滤且重复归一化/查名; 3. `UsageLogsRepo` 存在 `ownerBilling` `totalsSql`+`itemsSql` 双次全表扫、PG 下 `repriceRange` 同步 `ORDER BY id` 分页逐行更新且不回拨预聚合 watermark、`windowStats` 缺 `ORDER BY minute ASC` 致 PG 随机分钟、SQLite `trimDebugToMaxBytes` 多轮全表扫与 `_pruneUsage` 一次性大事务删除、以及与 `pg-log-writer.mjs` 重复维护 `SUMMARY_COLUMNS`/`toRow`; 4. `ApiEndpointsRepo.listHydrated()` 为 `1+2N` N+1 查询、`panel-2fa.twoFactorEnabledFor` 为 `1+N` 查询、`SettingsRepo` 未接入 `EntityCache`; 5. `panel-routes.mjs` 存在 VM/API Key 变更漏清 `stats`、`vmIdToClear` 误抓 `create|import|...` 非 ID 段、缺少 `/api/panel/gemini/` 失效分支、`/vms/:id/stop` 跨 `await stopSlot` RMW 覆盖热路径字段、`/reset-fingerprint` & `/reconcile-fingerprint` 无 `withVmLock(vmPath)`、`/seed-settings` 写盘未持 `withVmLock(vmPath)`、`/admin/routing` 与 `/api/panel/routing` 校验与回滚不一致、`GET /api/panel/vms` 过滤后 `total` 未更新、`GET /api/panel/billing` 非法日期未校验致 500、5 条零引用死路由残留、`/dashboard` 与 `/usage` 缓存键冗余 `role`、以及 `/request-logs/:id/attempts` 租户归属校验解析整份 `getDebug`。 - 改后: 1. `src/lib/db/repos/statistics-repo.mjs`:`_totalsFromPreAgg` 与 `_modelLeaderboardFromPreAgg` 读取 `016` 新增指标列(`COALESCE(..., 0)`),与 `dashboard-aggregator` 对齐 `COALESCE(SUM(actual_cost), 0)` 口径; 2. `src/lib/db/repos/usage-logs-view.mjs`:`listBatch` 对 `account_id` / `model` 改写为两路互斥 `UNION ALL + ORDER BY created_at DESC, id DESC LIMIT` 合并取前 N(不新增索引),`IFNULL` 改 `COALESCE`;`listBatchAsync` 先按 PG 页 `request_id` 去重再过滤并复用 `matchAndNormalizeLiveEntry` 归一化后的 row; 3. `src/lib/db/repos/usage-logs-repo.mjs`:`ownerBilling`/`ownerBillingAsync` 去 `totalsSql` 单次分组查询并由 `items` 累加 `totals`;新增 `repriceRangeAsync`(PG 原生 `pg.Pool` 按 `(created_at, id)` 键集分页 + `id` 升序 `UNNEST` 批量 `UPDATE` + `resetWatermarkBefore` + 异步 `runDashboardAggregation`);`windowStats` 补 `ORDER BY minute ASC`;`trimDebugToMaxBytes` 改单次窗口函数 `DELETE`,`_pruneUsage` 改 500 行有界分批归档删除;复用 `pg-log-writer.mjs` 导出的 `USAGE_LOG_COLUMNS` 与 `usageLogToRow`(SSOT); 4. `src/lib/db/repos/api-endpoints-repo.mjs`、`src/lib/core/panel-2fa.mjs`、`src/lib/db/repos/settings-repo.mjs`:`listHydrated()` 改为 3 次平表 Map 装配;`twoFactorEnabledFor` 改为单条 `SELECT key, value FROM settings WHERE key LIKE 'panel_2fa:%'`;`SettingsRepo` 仅在主 DB(`isDbOpen() && db === getDb()`,带 `DB_INSTANCE_ID` 切换防串读)接入 `EntityCache.getSettingSync` 并在 `set`/`remove` 触发 `invalidateSettings()`; 5. `src/lib/admin/panel-routes.mjs`:补齐 VM/Key/Gemini 失效矩阵与非 ID 段排除;`/vms/:id/stop` 在 `await stopSlot` 后重读 `vmPath` 再落盘、`/reset-fingerprint` & `/reconcile-fingerprint` 与 `/seed-settings` 写盘临界区统一持 `withVmLock(vmPath)`;抽出 `applyValidatedRoutingPatch` 供 `/api/panel/routing` 与 `/admin/routing` 共享;`GET /api/panel/vms` 复用无过滤 SWR 并同步更新 `total: filteredItems.length`;`GET /api/panel/billing` 校验 `since`/`until` 非法返 400 `invalid_range`;`POST /api/panel/pricing/reprice` 调用 `repriceRangeAsync`;删除 5 条死路由及对应失效条目/死 import;去掉 `/dashboard` 与 `/usage` 缓存键中的 `role`;attempts 路由改用 `requestLog.repo.belongsToOwner`; 6. 同步补充/更新 9 个已有单测文件(0 新建碎片测试文件)。 - 未改 / 延后:零触碰 `panel-api.mjs`、`gemini/routes.mjs`、`request-log.mjs`、`routing-runtime.mjs`、`scheduler/`、`CHANGELOG.md` 及 `pg-core` 的 21 个文件;`test/unit/pg-log-writer.test.mjs:184` 的 `origin/dev` 既有 `012/013` 迁移断言归日志域(已在 `log-author` 分支修复),本轨道不越界触碰。 ## 验收记录(Run) - 环境与基线:Windows + WSL2 Debian Node v24.13.0,基于 `fix/r3-pg-core-infra` (`0b570d128`) 叠分支于独立工作树 `X:\vm2api-wt-r3-panel-be` - 已跑命令与结果: - `npx biome check <16 changed .mjs files>`: PASS (16 files, 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 files, 0 fail) - `VM2API_TEST_CONCURRENCY=4 npm run test:unit -- statistics-repo usage-logs-view usage-logs-repo api-endpoints panel-2fa panel-users panel-route-coverage panel-acl panel-tenant-guards panel-vm-seed-settings panel-vm-deactivate tenant-billing pricing settings-routing-audit panel-kernels panel-redis-opt log-realtime-merge request-log`: PASS (18/18 files, 331/331 tests, 0 fail, 0 skip) - `VM2API_TEST_PG_URL='postgresql://vm2api:testpass@127.0.0.1:55434/vm2api' VM2API_TEST_REDIS_URL='redis://127.0.0.1:56381/0' npm run test:unit -- pg-integration pg-repos-parity pg-redis-cache-e2e sqlite-to-pg-migration`(WSL 临时 `postgres:18-alpine` + `redis:8-alpine` 容器,跑完即 `docker rm -f` 销毁): PASS (4/4 files, 12/12 tests, 0 skip) ## 回退与手破验证(Broken by hand) - 临时回退 `statistics-repo.mjs` `addPreAgg` 对 `016` 新列(`cache_creation_5m_tokens` / `cache_creation_1h_tokens` / `total_ttft_ms` / `ttft_count`)的累加 -> `node --test test/unit/panel-redis-opt.test.mjs` 的 `StatisticsRepo PG pre-agg` 真实 FAIL(`AssertionError: 0 !== 85`)-> 恢复后 11/11 PASS - 临时回退 `panel-routes.mjs` `/vms/:id/stop` 在 `await stopSlot` 后的 `vmPath` 重读,改回写旧 `initialVm` -> `node --test test/unit/panel-vm-deactivate.test.mjs` 的 `POST /api/panel/vms/:id/stop` 真实 FAIL(`AssertionError: hot-path cooldown field must not be clobbered: undefined !== '2099-01-01T00:00:00.000Z'`)-> 恢复后 11/11 PASS - 临时回退 `panel-routes.mjs` `GET /api/panel/billing` 对 `since`/`until` 的 `Number.isFinite(Date.parse(...))` 校验 -> `node --test test/unit/panel-vm-deactivate.test.mjs` 的 `GET /api/panel/billing validates since/until` 真实 FAIL(未返 400 `invalid_range`,穿透抛出 `TypeError: requestLog.ownerBilling is not a function`)-> 恢复后 11/11 PASS ## 真实使用(Real use) - 在 WSL 真实 `postgres:18-alpine`(端口 55434)+ `redis:8-alpine`(端口 56381)容器上执行完整 `001`–`016` 迁移与 `runDashboardAggregation`,验证含 `actual_cost IS NULL`、5m/1h cache tokens、TTFT、duration 的封口预聚合+尾部统计与 SQLite 0 误差,`repriceRangeAsync`(真实 PG `UNNEST` + `resetWatermarkBefore`)后立即重查 `statistics()` 返回新价格,`UsageLogsView` `UNION ALL` 账号/模型过滤与 `windowStats` `ORDER BY minute ASC` 双后端一致;未连接线上 `ph24`(严守沙箱隔离红线)。 ## 未运行项(Not run) - 未运行全量 556 个后端单测、`web/` 前端测试(未改动 `web/`)、E2E 套件、Go/Rust 构建及线上 `ph24` 验证(本轨道仅改 Node 22 面板后端与 DB 仓储,已覆盖 `test:ci` 13 套、本轨道全部 18 套关联单测及 4 套真 PG18+Redis8 集成/一致性套件)。 --- src/lib/admin/panel-routes.mjs | 642 +++++++++------------ src/lib/core/panel-2fa.mjs | 17 +- src/lib/db/repos/api-endpoints-repo.mjs | 33 +- src/lib/db/repos/settings-repo.mjs | 50 +- src/lib/db/repos/statistics-repo.mjs | 30 +- src/lib/db/repos/usage-logs-repo.mjs | 658 +++++++++++++--------- src/lib/db/repos/usage-logs-view.mjs | 195 ++++--- test/unit/api-endpoints.test.mjs | 34 ++ test/unit/panel-2fa.test.mjs | 21 +- test/unit/panel-kernels.test.mjs | 36 +- test/unit/panel-redis-opt.test.mjs | 238 ++++++++ test/unit/panel-vm-deactivate.test.mjs | 153 +++++ test/unit/pg-repos-parity.test.mjs | 150 +++++ test/unit/settings-routing-audit.test.mjs | 108 ++++ test/unit/usage-logs-repo.test.mjs | 205 +++++++ test/unit/usage-logs-view.test.mjs | 92 +++ 16 files changed, 1902 insertions(+), 760 deletions(-) diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index 8309a9f9c2..22b76de0b2 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -245,7 +245,6 @@ import { ensureRedaction, redactionStatus } from '../redaction/runtime.mjs' import { normalizeInferenceConfig, normalizeSessionSlots, - parseKernelDataplanePatch, parseSlotEnginePolicyPatch, parseSlotPolicyTargets, resolveInferenceEngine, @@ -282,14 +281,7 @@ import { startHostUpgrade, } from './release.mjs' import { downloadReleaseKernel, kernelReleaseHttpStatus, listKernelReleaseVersions } from './release-kernel.mjs' -import { - cragReleasePin, - describeKernelCatalog, - geminiReleasePin, - listKernelReleases, - pullKernelRelease, - selectKernelRelease, -} from './kernel-catalog.mjs' +import { cragReleasePin, describeKernelCatalog, geminiReleasePin, pullKernelRelease } from './kernel-catalog.mjs' import { hasKernelInstallSafetyHold, installKernelTargets, @@ -2023,12 +2015,22 @@ export function createPanelHandler(ctx) { let vmIdToClear = null let riskBanKindToClear = null + const NON_VM_ID_SEGMENTS = new Set([ + 'create', + 'import', + 'fleet-update', + 'slot-policy', + 'pool-policy', + 'package', + 'schedule', + 'reconcile-fingerprints', + ]) + if ( pathname === '/api/panel/vms' || pathname.startsWith('/api/panel/vms/') || pathname.startsWith('/admin/vms/') || pathname.startsWith('/admin/vm/') || - pathname === '/api/panel/dataplane' || pathname === '/api/panel/fleet/reconcile' || pathname.startsWith('/api/panel/kernels/') || pathname.startsWith('/api/panel/wrap-cli/') || @@ -2037,16 +2039,23 @@ export function createPanelHandler(ctx) { pathname === '/api/panel/usage-probe' ) { tables = ['vms', 'accounts', 'account_runtime'] - namespaces = ['panel', 'overview', 'filter-options'] + namespaces = ['panel', 'overview', 'stats', 'filter-options'] clearNamesTable = 'vms' const m = pathname.match(/^\/api\/panel\/vms\/([^/]+)/) - if (m) vmIdToClear = decodeURIComponent(m[1]) + if (m) { + const seg = decodeURIComponent(m[1]) + if (!NON_VM_ID_SEGMENTS.has(seg)) vmIdToClear = seg + } + } else if (pathname === '/api/panel/gemini' || pathname.startsWith('/api/panel/gemini/')) { + tables = ['vms', 'accounts', 'account_runtime', 'settings'] + namespaces = ['panel', 'overview', 'stats', 'filter-options'] + clearNamesTable = 'vms' } else if (pathname === '/api/panel/proxies' || pathname.startsWith('/api/panel/proxies/')) { tables = ['proxies', 'settings'] namespaces = ['panel'] } else if (pathname === '/api/panel/api-keys' || pathname.startsWith('/api/panel/api-keys/')) { tables = ['api_keys', 'api_key_pool_bindings'] - namespaces = ['panel', 'filter-options'] + namespaces = ['panel', 'stats', 'filter-options'] clearPoolAccess = true clearNamesTable = 'api_keys' } else if (pathname === '/api/panel/vm-pools' || pathname.startsWith('/api/panel/vm-pools/')) { @@ -2149,6 +2158,118 @@ export function createPanelHandler(ctx) { } } + async function applyValidatedRoutingPatch(body) { + if (body?.compatibility) body.compatibility = canonicalPersonaCompat(body.compatibility) + const previousRoutingConfig = structuredClone(ctx.routingConfig) + try { + validateNotifyRoutingPatch(body) + if (body?.codex && Object.prototype.hasOwnProperty.call(body.codex, 'quota')) { + validateOpenAIQuotaPatch(body.codex.quota) + } + validateInferenceWebsocketPatch(body) + validateGeminiRoutingPatch(body) + validateQuotaRoutingPatch(body, ctx.routingConfig?.quota) + validateLoggingRoutingPatch(body, ctx.routingConfig?.logging) + validateRedactionPatch(body) + } catch (error) { + if (error instanceof TypeError || error instanceof RangeError || error?.status === 400) { + return { + ok: false, + status: 400, + body: { + ok: false, + error: { + type: 'invalid_request_error', + code: error.code || 'invalid_openai_quota', + message: error.message, + }, + }, + } + } + throw error + } + if (body && Object.prototype.hasOwnProperty.call(body, 'vm')) { + const checked = validateVmConfigPatch(body.vm) + if (!checked.ok) { + return { + ok: false, + status: 400, + body: { + ok: false, + error: { type: 'invalid_request_error', code: 'invalid_vm_config', message: checked.error }, + }, + } + } + } + const personaProblems = [ + ...panel.validatePersonaRoutingPatch(body), + ...validateInferenceRoutingPatch(body), + ...validateTelemetryRoutingPatch(body), + ] + if (personaProblems.length) { + return { + ok: false, + status: 400, + body: { + ok: false, + error: { + type: 'invalid_request_error', + code: 'invalid_persona_template', + message: personaProblems.join(';'), + problems: personaProblems, + }, + }, + } + } + const engineRuntime = await prepareInheritedInferenceEngine(body) + if (!engineRuntime.ok) { + return { + ok: false, + status: 503, + body: { + ok: false, + error: { + code: engineRuntime.code, + message: engineRuntime.error, + failed_vm: engineRuntime.failed_vm, + }, + }, + } + } + const { applied: appliedDuringSwitch, ...publicEngineRuntime } = engineRuntime + let applied + try { + applied = appliedDuringSwitch ?? (await persistRoutingPatch(body)) + } catch (error) { + await restoreRoutingRuntime(previousRoutingConfig) + const isBadRequest = error instanceof TypeError || error instanceof RangeError || error?.status === 400 + const status = isBadRequest + ? 400 + : Number.isInteger(error?.status) && error.status >= 400 && error.status < 600 + ? error.status + : 503 + return { + ok: false, + status, + body: { + ok: false, + error: { + ...(status === 400 ? { type: 'invalid_request_error' } : {}), + code: + error?.code || + (status === 400 + ? error instanceof TypeError || error instanceof RangeError + ? 'invalid_openai_quota' + : 'invalid_redaction_config' + : 'routing_persist_failed'), + message: String(error?.message || error), + }, + }, + } + } + return { ok: true, applied, publicEngineRuntime } + } + async function handlePanelInner(req, res, url) { const p = url.pathname if (!p.startsWith('/admin') && !p.startsWith('/api/panel')) return false @@ -2183,27 +2304,13 @@ export function createPanelHandler(ctx) { if (p === '/admin/routing' && (req.method === 'PUT' || req.method === 'POST')) { if (!requireAuth(req, res)) return const body = await readBody(req, cfg.limits.max_body_bytes) - let applied - try { - applied = await persistRoutingPatch(body) - } catch (error) { - if (error instanceof TypeError || error instanceof RangeError) { - return json(res, 400, { - ok: false, - error: { - type: 'invalid_request_error', - code: error.code || 'invalid_openai_quota', - message: error.message, - }, - }) - } - throw error - } + const result = await applyValidatedRoutingPatch(body) + if (!result.ok) return json(res, result.status, result.body) return json(res, 200, { ok: true, routing: publicRoutingNotify(ctx.routingConfig), - applied_concurrency: applied.concurrency, - applied_rpm: applied.rpm, + applied_concurrency: result.applied.concurrency, + applied_rpm: result.applied.rpm, }) } if (p === '/admin/quota' && req.method === 'GET') { @@ -3765,8 +3872,14 @@ export function createPanelHandler(ctx) { if (req.method === 'GET' && /^\/api\/panel\/request-logs\/[^/]+\/attempts$/.test(p)) { const requestId = p.split('/')[4] const owner_user_id = panelIdentity(req).role === 'user' ? req.panelUserId : null - if (owner_user_id && !requestLog.getDebug(requestId, { owner_user_id })) { - return json(res, 404, { ok: false, error: { message: 'debug log not found' } }) + if (owner_user_id) { + const allowed = + typeof requestLog?.repo?.belongsToOwner === 'function' + ? requestLog.repo.belongsToOwner(requestId, owner_user_id) + : Boolean(requestLog.getDebug(requestId, { owner_user_id })) + if (!allowed) { + return json(res, 404, { ok: false, error: { message: 'debug log not found' } }) + } } return json( res, @@ -3955,6 +4068,15 @@ export function createPanelHandler(ctx) { const groupBy = u.searchParams.get('group_by') === 'key' ? 'key' : 'vm' const since = u.searchParams.get('from') || u.searchParams.get('since') || null const until = u.searchParams.get('until') || null + if ( + (since != null && !Number.isFinite(Date.parse(since))) || + (until != null && !Number.isFinite(Date.parse(until))) + ) { + return json(res, 400, { + ok: false, + error: { code: 'invalid_range', message: 'since/until must be valid ISO timestamps' }, + }) + } const bypass = u.searchParams.get('refresh') === '1' let data if (typeof requestLog?.ownerBillingAsync === 'function') { @@ -4076,7 +4198,6 @@ export function createPanelHandler(ctx) { // GET /api/panel/dashboard if (req.method === 'GET' && p === '/api/panel/dashboard') { - const ident = panelIdentity(req) const bypass = url.searchParams.get('refresh') === '1' const payload = await getCacheRuntime().dashboard.getOrSetSWR( 'panel', @@ -4084,7 +4205,6 @@ export function createPanelHandler(ctx) { ep: 'dashboard', scope: cacheScopeOf(requestLog?.repo?.db || resolvePanelDb()), project: cfg?.paths?.project || null, - role: ident.role, }, () => panel.buildDashboard({ @@ -4111,7 +4231,7 @@ export function createPanelHandler(ctx) { const filterSupplier = ident.role === 'admin' ? String(url.searchParams.get('supplier_id') || '').trim() || null : null const bypass = url.searchParams.get('refresh') === '1' - const payload = await getCacheRuntime().dashboard.getOrSetSWR( + const built = await getCacheRuntime().dashboard.getOrSetSWR( 'panel', { ep: 'vms', @@ -4119,11 +4239,9 @@ export function createPanelHandler(ctx) { project: cfg?.paths?.project || null, role: ident.role, ownerUserId: normalizeOwnerId(ownerUserId), - filterOwner, - filterSupplier, }, - async () => { - const built = await panel.buildVmList({ + () => + panel.buildVmList({ cfg, accountQuota, routingConfig: ctx.routingConfig, @@ -4135,28 +4253,28 @@ export function createPanelHandler(ctx) { clusterNodes: clusterNodesOf(ctx), supplierTagStore, bypass, - }) - if ((filterOwner || filterSupplier) && built?.data) { - const matches = (v) => { - if (filterOwner && vmOwnerId(v) !== filterOwner) return false - if (filterSupplier && (v.supplier_id || v.supplier?.supplier_id || null) !== filterSupplier) { - return false - } - return true - } - return { - ...built, - data: { - ...built.data, - ...(Array.isArray(built.data.items) ? { items: built.data.items.filter(matches) } : {}), - ...(Array.isArray(built.data.vms) ? { vms: built.data.vms.filter(matches) } : {}), - }, - } - } - return built - }, + }), { freshTtlMs: 5_000, ttlMs: 15_000, bypass }, ) + let payload = built + if ((filterOwner || filterSupplier) && built?.data && Array.isArray(built.data.items)) { + const matches = (v) => { + if (filterOwner && vmOwnerId(v) !== filterOwner) return false + if (filterSupplier && (v.supplier_id || v.supplier?.supplier_id || null) !== filterSupplier) { + return false + } + return true + } + const filteredItems = built.data.items.filter(matches) + payload = { + ...built, + data: { + ...built.data, + items: filteredItems, + total: filteredItems.length, + }, + } + } return sendCachedJson(req, res, 200, payload) } // GET /api/panel/pool/stream — live seat / queue snapshots (SSE over fetch). @@ -4298,32 +4416,6 @@ export function createPanelHandler(ctx) { }) } } - // Several cached releases side by side. - if (req.method === 'GET' && p === '/api/panel/kernels/cached') { - const result = listKernelReleases(cfg.paths.project, url.searchParams.get('kernel') || 'crag') - if (!result.ok) - return json(res, 400, { - ok: false, - error: { code: result.code, message: result.error }, - }) - return json(res, 200, panel.ok({ releases: result.releases })) - } - if (req.method === 'POST' && p === '/api/panel/kernels/select') { - const body = await readBody(req, 8 * 1024) - const result = selectKernelRelease(cfg.paths.project, { - kernel: body?.kernel, - tag: body?.tag, - }) - if (!result.ok) { - const status = - result.code === 'kernel_pull_busy' ? 409 : result.code === 'kernel_release_not_cached' ? 404 : 400 - return json(res, status, { - ok: false, - error: { code: result.code, message: result.error }, - }) - } - return json(res, 200, panel.ok({ kernel: result.kernel, release: result.release })) - } if (req.method === 'POST' && p === '/api/panel/kernels/pull') { const body = await readBody(req, 8 * 1024) if ( @@ -4469,175 +4561,6 @@ export function createPanelHandler(ctx) { }), ) } - if (req.method === 'POST' && p === '/api/panel/dataplane') { - const body = await readBody(req, 8 * 1024).catch(() => ({})) - const parsed = parseKernelDataplanePatch(body.dataplane) - if (!parsed.ok || !parsed.value) { - return json(res, 400, { - ok: false, - error: { code: 'invalid_dataplane', message: parsed.error || 'dataplane must be wrap, cc, or crag' }, - }) - } - const targets = parseSlotPolicyTargets({ - ids: body.ids, - all: body.all === true || !Array.isArray(body.ids), - }) - if (!targets.ok) { - return json(res, 400, { ok: false, error: { message: targets.error } }) - } - return await syncInstalledKernels( - { - project: cfg.paths.project, - restartKernel: ctx.kernelPolicyOps?.restartRustKernel, - body: { ids: targets.all ? undefined : targets.ids, restart: body.restart !== false }, - }, - async (syncArgs) => { - const previous = structuredClone(ctx.routingConfig) - if (body.restart !== false) { - const nextRouting = targets.all - ? { ...ctx.routingConfig, inference: { ...ctx.routingConfig.inference, dataplane: parsed.value } } - : ctx.routingConfig - const dpIdentity = panelIdentity(req) - const bindSubscription = - !req.apiKeyKind && dpIdentity.role === 'admin' && !!dpIdentity.user && sameOriginPost(req, cfg.base_url) - for (const id of syncArgs.body.ids) { - const vm = getVm(cfg.paths.project, id) - const desired = targets.all ? vm : vmWithSlotPolicyPatch(vm, { dataplane: parsed.value }) - if (resolveKernelDataplane(desired, nextRouting) === 'crag' && isNativeNodeVm(desired)) { - return json(res, 400, { - ok: false, - error: { code: 'remote_unsupported', message: 'CRAG 切核暂不支持 macOS 原生槽' }, - }) - } - } - let switchAll = async () => { - // Publish every KVM grant before changing the inherited default or any slot policy. - for (const id of syncArgs.body.ids) { - const vm = getVm(cfg.paths.project, id) - const desired = targets.all ? vm : vmWithSlotPolicyPatch(vm, { dataplane: parsed.value }) - await projectKvmCragSwitchLicense(vm, desired, previous, nextRouting) - } - if (targets.all) await persistRoutingPatch({ inference: nextRouting.inference }) - const items = [] - for (const id of syncArgs.body.ids) { - const switched = await applySlotPolicyWithRuntimeLocked( - id, - targets.all ? {} : { dataplane: parsed.value }, - { - maintenance: true, - previousRouting: previous, - cragLicenseProjected: true, - releaseBinding: true, - bindSubscription, - }, - ) - items.push({ - id, - ok: switched.ok, - code: switched.code, - error: switched.error, - ...(switched.reclaim_pending && { reclaim_pending: true }), - ...(switched.deferred_start && { - deferred_start: true, - deferred_reason: switched.deferred_reason || null, - start_error: switched.start_error || null, - }), - }) - } - const failed = items.filter((item) => !item.ok).length - return { - ok: failed === 0, - total: items.length, - ok_count: items.length - failed, - failed_count: failed, - items, - } - } - for (const id of [...syncArgs.body.ids].reverse()) { - if (getVm(cfg.paths.project, id)?.status !== 'running') continue - const operation = switchAll - switchAll = () => - withSlotMaintenance({ - projectRoot: cfg.paths.project, - id, - watchdog: kernelSwitchWatchdog, - poolScheduler: ctx.poolScheduler, - operation, - }) - } - try { - const report = await switchAll() - return json(res, report.ok ? 200 : 503, panel.ok({ dataplane: parsed.value, ...report })) - } catch (error) { - ctx.routingConfig = previous - return json(res, 503, { - ok: false, - error: { - code: error?.code === 'crag_license_projection_failed' ? error.code : 'dataplane_persist_failed', - message: String(error?.message || error), - }, - }) - } - } - try { - const nextRouting = targets.all - ? { ...previous, inference: { ...previous.inference, dataplane: parsed.value } } - : previous - const initialize = ctx.kernelPolicyOps?.initializeSlotSeedFiles || initializeSlotSeedFiles - for (const id of syncArgs.body.ids) { - const vm = getVm(cfg.paths.project, id) - if (!vm || isCodexVm(vm)) continue - const desired = targets.all ? vm : vmWithSlotPolicyPatch(vm, { dataplane: parsed.value }) - if (resolveKernelDataplane(vm, previous) === resolveKernelDataplane(desired, nextRouting)) continue - if (checkCragLicense(cfg.paths.project, desired, nextRouting).ok) - await initialize(cfg.paths.project, desired, slotHost(desired), { routing: nextRouting }) - } - } catch { - return json(res, 503, { - ok: false, - error: { code: 'kernel_seed_failed', message: 'Claude Code 初始化配置生成或发布失败' }, - }) - } - try { - if (targets.all) { - await persistRoutingPatch({ - inference: { - ...(ctx.routingConfig.inference || {}), - dataplane: parsed.value, - }, - }) - } else { - for (const id of syncArgs.body.ids) { - persistSlotEnginePolicy(cfg.paths.project, id, { dataplane: parsed.value }) - } - } - } catch (error) { - ctx.routingConfig = previous - return json(res, 503, { - ok: false, - error: { code: 'dataplane_persist_failed', message: String(error?.message || error) }, - }) - } - const report = await runKernelSync({ ...syncArgs, routingConfig: ctx.routingConfig }) - return json( - res, - report.ok ? 200 : 503, - panel.ok({ - dataplane: parsed.value, - ...report, - }), - ) - }, - ) - } - if (req.method === 'POST' && p === '/api/panel/wrap-cli/crag-kernel') { - const raw = await readRawBody(req, 32 * 1024 * 1024) - const written = replaceCragKernelBinary(cfg.paths.project, raw) - if (!written.ok) { - return json(res, 400, { ok: false, error: { code: written.code, message: written.error } }) - } - return json(res, 200, panel.ok(written)) - } if (req.method === 'POST' && p === '/api/panel/wrap-cli/make') { const body = await readBody(req, 8 * 1024).catch(() => ({})) const glibcVm = String(body.glibc_vm || body.glibcVm || '').trim() @@ -6287,44 +6210,48 @@ export function createPanelHandler(ctx) { if (req.method === 'POST' && /^\/api\/panel\/vms\/[^/]+\/reset-fingerprint$/.test(p)) { const id = p.split('/')[4] const vmPath = path.join(cfg.paths.project, 'vms', `${id}.json`) - if (!fs.existsSync(vmPath)) { - return json(res, 404, { ok: false, error: { message: 'vm not found' } }) - } - let vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - const generated = assignComputerFingerprint(cfg.paths.project, vm, { - taken: takenFingerprintKeys(listVms(cfg.paths.project), { exceptId: id }), + return await withVmLock(vmPath, async () => { + if (!fs.existsSync(vmPath)) { + return json(res, 404, { ok: false, error: { message: 'vm not found' } }) + } + let vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const generated = assignComputerFingerprint(cfg.paths.project, vm, { + taken: takenFingerprintKeys(listVms(cfg.paths.project), { exceptId: id }), + }) + vm.timezone = generated.timezone + vm.locale = generated.locale + vm.fingerprint = applyGeneratedFingerprint({}, generated) + vm.updated_at = generated.reset_at + atomicWriteJson(vmPath, vm, { mode: 0o600 }) + writeGuestMachineIdFile(cfg.paths.project, id, generated.guest_machine_id) + applyOfficialFingerprintToVm(vmPath, path.join(cfg.paths.project, 'vms', id, 'cli-home')) + try { + vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + } catch {} + return json(res, 200, panel.ok({ id, fingerprint: vm.fingerprint })) }) - vm.timezone = generated.timezone - vm.locale = generated.locale - vm.fingerprint = applyGeneratedFingerprint({}, generated) - vm.updated_at = generated.reset_at - atomicWriteJson(vmPath, vm, { mode: 0o600 }) - writeGuestMachineIdFile(cfg.paths.project, id, generated.guest_machine_id) - applyOfficialFingerprintToVm(vmPath, path.join(cfg.paths.project, 'vms', id, 'cli-home')) - try { - vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - } catch {} - return json(res, 200, panel.ok({ id, fingerprint: vm.fingerprint })) } if (req.method === 'POST' && /^\/api\/panel\/vms\/[^/]+\/reconcile-fingerprint$/.test(p)) { const id = p.split('/')[4] const vmPath = path.join(cfg.paths.project, 'vms', `${id}.json`) - if (!fs.existsSync(vmPath)) { - return json(res, 404, { ok: false, error: { message: 'vm not found' } }) - } - const result = applyOfficialFingerprintToVm(vmPath, officialCcHome(cfg.paths.project, id)) - const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - return json( - res, - 200, - panel.ok({ - vm_id: id, - ...result, - identity_source: vm.fingerprint?.identity_source || null, - has_official_user: !!vm.fingerprint?.official_user_id, - has_official_machine: !!vm.fingerprint?.official_machine_id, - }), - ) + return await withVmLock(vmPath, async () => { + if (!fs.existsSync(vmPath)) { + return json(res, 404, { ok: false, error: { message: 'vm not found' } }) + } + const result = applyOfficialFingerprintToVm(vmPath, officialCcHome(cfg.paths.project, id)) + const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + return json( + res, + 200, + panel.ok({ + vm_id: id, + ...result, + identity_source: vm.fingerprint?.identity_source || null, + has_official_user: !!vm.fingerprint?.official_user_id, + has_official_machine: !!vm.fingerprint?.official_machine_id, + }), + ) + }) } // GET /api/panel/vms/:id/health?range=24h|7d — request success / error buckets for the row detail. @@ -6458,25 +6385,36 @@ export function createPanelHandler(ctx) { } timezone = synced.timezone } - // Only patch owned fields on the latest record, never an object held across geo/publication awaits. - vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - const next = defaultSeedPolicy({ ...(vm.seed_policy || {}), ...patch }) - const unsupported = slotHost(vm).native || isCodexVm(vm) - if (isCodexVm(vm) || (unsupported && isTelemetryEnabled(next))) { + // Only patch owned fields on the latest record under the shared VM lock, + // never an object held across geo/publication awaits or racing with PATCH/stop. + const persisted = await withVmLock(vmPath, () => { + if (!fs.existsSync(vmPath)) return { missing: true } + const latest = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const nextPolicy = defaultSeedPolicy({ ...(latest.seed_policy || {}), ...patch }) + const isUnsupported = slotHost(latest).native || isCodexVm(latest) + if (isCodexVm(latest) || (isUnsupported && isTelemetryEnabled(nextPolicy))) { + return { unsupportedTelemetry: true } + } + if (timezone) { + latest.timezone = timezone + latest.timezone_source = hasTimezone ? 'manual' : 'proxy_geo' + if (latest.fingerprint && typeof latest.fingerprint === 'object') latest.fingerprint.timezone = timezone + } + if (locale) latest.locale = locale + latest.seed_policy = nextPolicy + latest.updated_at = new Date().toISOString() + atomicWriteJson(vmPath, latest, { mode: 0o600 }) + return { vm: latest, next: nextPolicy, unsupported: isUnsupported } + }) + if (persisted.missing) return json(res, 404, { ok: false, error: { message: 'vm not found' } }) + if (persisted.unsupportedTelemetry) { return json(res, 409, { ok: false, error: { code: 'telemetry_unsupported', message: '此槽不支持 VM 原生遥测' }, }) } - if (timezone) { - vm.timezone = timezone - vm.timezone_source = hasTimezone ? 'manual' : 'proxy_geo' - if (vm.fingerprint && typeof vm.fingerprint === 'object') vm.fingerprint.timezone = timezone - } - if (locale) vm.locale = locale - vm.seed_policy = next - vm.updated_at = new Date().toISOString() - atomicWriteJson(vmPath, vm, { mode: 0o600 }) + vm = persisted.vm + const { next, unsupported } = persisted if (fs.existsSync(fingerprintDir(cfg.paths.project, id))) { try { const tzSync = syncSlotIdentityTimezoneAndPreset(cfg.paths.project, vm, { @@ -7410,9 +7348,11 @@ export function createPanelHandler(ctx) { const vmPath = path.join(cfg.paths.project, 'vms', `${id}.json`) return await withVmLock(vmPath, async () => { if (!fs.existsSync(vmPath)) return json(res, 404, { ok: false, error: { message: 'vm not found' } }) - const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) - const halt = await stopSlot(vm) + const initialVm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const halt = await (ctx.kernelPolicyOps?.stopSlot || stopSlot)(initialVm) if (!halt.ok) return json(res, 500, { ok: false, error: { message: halt.error || 'runtime stop failed' } }) + // Re-read latest vm.json after await so hot-path cooldown/credential writes during stop are never clobbered. + const vm = fs.existsSync(vmPath) ? JSON.parse(fs.readFileSync(vmPath, 'utf8')) : initialVm vm.status = 'stopped' migrateScheduleRecord(vm) applyScheduleOff(vm, true, { reason: 'stopped' }) @@ -8090,9 +8030,6 @@ export function createPanelHandler(ctx) { if (!data.ok) return json(res, 502, { ok: false, error: data.error, data }) return json(res, 200, panel.ok(data)) } - if (req.method === 'GET' && p === '/api/panel/oauth') { - return json(res, 200, panel.ok(await oauthStatusWithWorker())) - } // POST /api/panel/probe if (req.method === 'POST' && p === '/api/panel/probe') { @@ -8176,7 +8113,6 @@ export function createPanelHandler(ctx) { } // GET /api/panel/usage if (req.method === 'GET' && p === '/api/panel/usage') { - const ident = panelIdentity(req) const bypass = url.searchParams.get('refresh') === '1' const payload = await getCacheRuntime().dashboard.getOrSetSWR( 'panel', @@ -8184,7 +8120,6 @@ export function createPanelHandler(ctx) { ep: 'usage', scope: cacheScopeOf(requestLog?.repo?.db || resolvePanelDb()), project: cfg?.paths?.project || null, - role: ident.role, }, () => panel.buildUsageAsync({ accountQuota, cfg, requestLog, bypass }), { freshTtlMs: 5_000, ttlMs: 15_000, bypass }, @@ -8383,10 +8318,14 @@ export function createPanelHandler(ctx) { error: { code: 'invalid_range', message: 'since/until must be ISO times with since < until' }, }) } - const result = requestLog.repo.repriceRange({ + const rangeArgs = { since: new Date(since).toISOString(), until: new Date(until).toISOString(), - }) + } + const result = + typeof requestLog.repo.repriceRangeAsync === 'function' + ? await requestLog.repo.repriceRangeAsync(rangeArgs) + : requestLog.repo.repriceRange(rangeArgs) return json(res, 200, panel.ok(result)) } // POST /api/panel/model-policy/sync-codex — ChatGPT GPT catalog via a Codex OAuth slot @@ -8504,84 +8443,9 @@ export function createPanelHandler(ctx) { // PUT /api/panel/routing if (req.method === 'PUT' && p === '/api/panel/routing') { const body = await readBody(req, cfg.limits.max_body_bytes) - if (body?.compatibility) body.compatibility = canonicalPersonaCompat(body.compatibility) - const previousRoutingConfig = structuredClone(ctx.routingConfig) - try { - validateNotifyRoutingPatch(body) - if (body?.codex && Object.prototype.hasOwnProperty.call(body.codex, 'quota')) { - validateOpenAIQuotaPatch(body.codex.quota) - } - validateInferenceWebsocketPatch(body) - validateGeminiRoutingPatch(body) - validateQuotaRoutingPatch(body, ctx.routingConfig?.quota) - validateLoggingRoutingPatch(body, ctx.routingConfig?.logging) - validateRedactionPatch(body) - } catch (error) { - if (error instanceof TypeError || error instanceof RangeError || error?.status === 400) { - return json(res, 400, { - ok: false, - error: { - type: 'invalid_request_error', - code: error.code || 'invalid_openai_quota', - message: error.message, - }, - }) - } - throw error - } - if (body && Object.prototype.hasOwnProperty.call(body, 'vm')) { - const checked = validateVmConfigPatch(body.vm) - if (!checked.ok) { - return json(res, 400, { - ok: false, - error: { type: 'invalid_request_error', code: 'invalid_vm_config', message: checked.error }, - }) - } - } - const personaProblems = [ - ...panel.validatePersonaRoutingPatch(body), - ...validateInferenceRoutingPatch(body), - ...validateTelemetryRoutingPatch(body), - ] - if (personaProblems.length) { - return json(res, 400, { - ok: false, - error: { - type: 'invalid_request_error', - code: 'invalid_persona_template', - message: personaProblems.join(';'), - problems: personaProblems, - }, - }) - } - const engineRuntime = await prepareInheritedInferenceEngine(body) - if (!engineRuntime.ok) { - return json(res, 503, { - ok: false, - error: { - code: engineRuntime.code, - message: engineRuntime.error, - failed_vm: engineRuntime.failed_vm, - }, - }) - } - const { applied: appliedDuringSwitch, ...publicEngineRuntime } = engineRuntime - let applied - try { - applied = appliedDuringSwitch ?? (await persistRoutingPatch(body)) - } catch (error) { - await restoreRoutingRuntime(previousRoutingConfig) - const status = - Number.isInteger(error?.status) && error.status >= 400 && error.status < 600 ? error.status : 503 - return json(res, status, { - ok: false, - error: { - ...(status === 400 ? { type: 'invalid_request_error' } : {}), - code: error?.code || (status === 400 ? 'invalid_redaction_config' : 'routing_persist_failed'), - message: String(error?.message || error), - }, - }) - } + const result = await applyValidatedRoutingPatch(body) + if (!result.ok) return json(res, result.status, result.body) + const { applied, publicEngineRuntime } = result return json( res, 200, diff --git a/src/lib/core/panel-2fa.mjs b/src/lib/core/panel-2fa.mjs index 5091a70dad..d44ce72a81 100644 --- a/src/lib/core/panel-2fa.mjs +++ b/src/lib/core/panel-2fa.mjs @@ -14,6 +14,7 @@ */ import crypto from 'node:crypto' +import { getDb } from '../db/database.mjs' import { SettingsRepo } from '../db/repos/settings-repo.mjs' import { decryptString, encryptString } from '../db/secure.mjs' import { DEFAULT_OPTIONS, buildOtpauthUri, generateSecret, matchCounter, normalizeSecret } from './totp.mjs' @@ -100,11 +101,21 @@ export function isTwoFactorEnabled(username) { /** Batch form of {@link isTwoFactorEnabled} for the user list. */ export function twoFactorEnabledFor(usernames = []) { - const repo = settings() const out = new Map() + if (!Array.isArray(usernames) || !usernames.length) return out + const rows = getDb().prepare("SELECT key, value FROM settings WHERE key LIKE 'panel_2fa:%'").all() + const enabledKeys = new Set() + for (const row of rows) { + try { + const rec = row?.value ? JSON.parse(row.value) : null + if (rec && typeof rec === 'object' && rec.enabled && rec.secret) { + enabledKeys.add(String(row.key)) + } + } catch {} + } for (const name of usernames) { - const rec = loadRecord(name, repo) - out.set(name, !!(rec?.enabled && rec?.secret)) + const trimmed = String(name || '').trim() + out.set(name, !!trimmed && enabledKeys.has(twoFactorKey(trimmed))) } return out } diff --git a/src/lib/db/repos/api-endpoints-repo.mjs b/src/lib/db/repos/api-endpoints-repo.mjs index b9c790cb8a..819646a712 100644 --- a/src/lib/db/repos/api-endpoints-repo.mjs +++ b/src/lib/db/repos/api-endpoints-repo.mjs @@ -94,6 +94,7 @@ export class ApiEndpointsRepo { ) this._delEp = db.prepare('DELETE FROM api_endpoints WHERE id = ?') this._listKeys = db.prepare('SELECT * FROM api_endpoint_keys WHERE endpoint_id = ? ORDER BY created_at, id') + this._listAllKeys = db.prepare('SELECT * FROM api_endpoint_keys ORDER BY created_at, id') this._getKey = db.prepare('SELECT * FROM api_endpoint_keys WHERE id = ?') this._insKey = db.prepare( `INSERT INTO api_endpoint_keys (${KEY_COLS.join(',')}) VALUES (${KEY_COLS.map(() => '?').join(',')})`, @@ -101,6 +102,7 @@ export class ApiEndpointsRepo { this._delKey = db.prepare('DELETE FROM api_endpoint_keys WHERE id = ?') this._delKeysEp = db.prepare('DELETE FROM api_endpoint_keys WHERE endpoint_id = ?') this._listModels = db.prepare('SELECT * FROM api_endpoint_models WHERE endpoint_id = ? ORDER BY sort, id') + this._listAllModels = db.prepare('SELECT * FROM api_endpoint_models ORDER BY sort, id') this._insModel = db.prepare( `INSERT INTO api_endpoint_models (${MODEL_COLS.join(',')}) VALUES (${MODEL_COLS.map(() => '?').join(',')})`, ) @@ -112,7 +114,36 @@ export class ApiEndpointsRepo { } listHydrated() { - return this._listEp.all().map((row) => this.hydrate(rowEp(row))) + const endpoints = this._listEp.all() + if (!endpoints.length) return [] + const keysByEp = new Map() + for (const row of this._listAllKeys.all()) { + const key = rowKey(row) + let list = keysByEp.get(key.endpoint_id) + if (!list) { + list = [] + keysByEp.set(key.endpoint_id, list) + } + list.push(key) + } + const modelsByEp = new Map() + for (const row of this._listAllModels.all()) { + const model = rowModel(row) + let list = modelsByEp.get(model.endpoint_id) + if (!list) { + list = [] + modelsByEp.set(model.endpoint_id, list) + } + list.push(model) + } + return endpoints.map((row) => { + const ep = rowEp(row) + return { + ...ep, + api_key_entries: keysByEp.get(ep.id) || [], + models: modelsByEp.get(ep.id) || [], + } + }) } getHydrated(id) { diff --git a/src/lib/db/repos/settings-repo.mjs b/src/lib/db/repos/settings-repo.mjs index 078de37b9d..8dbe9796a3 100644 --- a/src/lib/db/repos/settings-repo.mjs +++ b/src/lib/db/repos/settings-repo.mjs @@ -3,7 +3,27 @@ * Used for: legacy_import_done, backup_schedule, proxy_pool_config, active_vm … */ -import { getDb } from '../database.mjs' +import { DB_INSTANCE_ID, getDb, isDbOpen } from '../database.mjs' +import { getCacheRuntime } from '../../cache/index.mjs' + +let lastPrimaryDbId = null + +function cloneSettingValue(value) { + if (value === null || typeof value !== 'object') return value + return structuredClone(value) +} + +function isPrimaryDb(db) { + if (!isDbOpen() || db !== getDb()) return false + const dbId = db?.[DB_INSTANCE_ID] || null + if (dbId && lastPrimaryDbId && dbId !== lastPrimaryDbId) { + getCacheRuntime() + .entity.invalidateSettings() + .catch(() => {}) + } + if (dbId) lastPrimaryDbId = dbId + return true +} export class SettingsRepo { constructor(db = getDb()) { @@ -17,18 +37,33 @@ export class SettingsRepo { this._all = db.prepare('SELECT key, value, updated_at FROM settings ORDER BY key') } - get(key, fallback = null) { + _readParsedEntry(key) { const row = this._get.get(key) - if (!row) return fallback + if (!row) return { found: false, value: null } try { - return JSON.parse(row.value) + return { found: true, value: JSON.parse(row.value) } } catch { - return fallback + return { found: false, value: null } } } + get(key, fallback = null) { + if (key != null && key !== '' && isPrimaryDb(this.db)) { + const entry = getCacheRuntime().entity.getSettingSync(String(key), () => this._readParsedEntry(key)) + if (!entry || !entry.found) return fallback + return cloneSettingValue(entry.value) + } + const entry = this._readParsedEntry(key) + return entry.found ? entry.value : fallback + } + set(key, value) { this._set.run(key, JSON.stringify(value), new Date().toISOString()) + if (isPrimaryDb(this.db)) { + getCacheRuntime() + .entity.invalidateSettings() + .catch(() => {}) + } return value } @@ -38,6 +73,11 @@ export class SettingsRepo { remove(key) { this._del.run(key) + if (isPrimaryDb(this.db)) { + getCacheRuntime() + .entity.invalidateSettings() + .catch(() => {}) + } } all() { diff --git a/src/lib/db/repos/statistics-repo.mjs b/src/lib/db/repos/statistics-repo.mjs index 370f8753af..c54b597ba5 100644 --- a/src/lib/db/repos/statistics-repo.mjs +++ b/src/lib/db/repos/statistics-repo.mjs @@ -290,9 +290,13 @@ export class StatisticsRepo { acc.output_tokens += num(row.output_tokens) acc.cache_read_tokens += cacheRead acc.cache_creation_tokens += cacheCreation + acc.cache_creation_5m_tokens += num(row.cache_creation_5m_tokens) + acc.cache_creation_1h_tokens += num(row.cache_creation_1h_tokens) acc.prompt_tokens += input + cacheRead + cacheCreation acc.total_duration_ms += num(row.total_duration_ms) acc.duration_count += num(row.duration_count) + acc.total_ttft_ms += num(row.total_ttft_ms) + acc.ttft_count += num(row.ttft_count) } const addTail = (row) => { if (!row) return @@ -325,8 +329,12 @@ export class StatisticsRepo { COALESCE(SUM(output_tokens), 0) AS output_tokens, COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens, COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens, + COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens, + COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens, COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms, - COALESCE(SUM(duration_count), 0) AS duration_count + COALESCE(SUM(duration_count), 0) AS duration_count, + COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms, + COALESCE(SUM(ttft_count), 0) AS ttft_count FROM usage_dashboard_daily WHERE bucket_date >= ?::date AND bucket_date < ?::date `) @@ -344,8 +352,12 @@ export class StatisticsRepo { COALESCE(SUM(output_tokens), 0) AS output_tokens, COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens, COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens, + COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens, + COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens, COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms, - COALESCE(SUM(duration_count), 0) AS duration_count + COALESCE(SUM(duration_count), 0) AS duration_count, + COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms, + COALESCE(SUM(ttft_count), 0) AS ttft_count FROM usage_dashboard_hourly WHERE bucket_start >= ?::timestamptz AND bucket_start < ?::timestamptz `) @@ -436,8 +448,14 @@ export class StatisticsRepo { COALESCE(SUM(output_tokens), 0) AS output_tokens, COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens, COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens, + COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens, + COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens, COALESCE(SUM(total_cost), 0) AS cost, - COALESCE(SUM(actual_cost), 0) AS actual_cost + COALESCE(SUM(actual_cost), 0) AS actual_cost, + COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms, + COALESCE(SUM(duration_count), 0) AS duration_count, + COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms, + COALESCE(SUM(ttft_count), 0) AS ttft_count FROM usage_dashboard_hourly_models WHERE bucket_start >= ?::timestamptz AND bucket_start < ?::timestamptz GROUP BY 1 @@ -515,9 +533,15 @@ export class StatisticsRepo { cur.output_tokens += num(row.output_tokens) cur.cache_read_tokens += cacheRead cur.cache_creation_tokens += cacheCreation + cur.cache_creation_5m_tokens += num(row.cache_creation_5m_tokens) + cur.cache_creation_1h_tokens += num(row.cache_creation_1h_tokens) cur.prompt_tokens += input + cacheRead + cacheCreation cur.cost += num(row.cost) cur.actual_cost += num(row.actual_cost) + cur.total_duration_ms += num(row.total_duration_ms) + cur.duration_count += num(row.duration_count) + cur.total_ttft_ms += num(row.total_ttft_ms) + cur.ttft_count += num(row.ttft_count) } for (const row of tailRows) { diff --git a/src/lib/db/repos/usage-logs-repo.mjs b/src/lib/db/repos/usage-logs-repo.mjs index 208d8ec705..2784ad9d6d 100644 --- a/src/lib/db/repos/usage-logs-repo.mjs +++ b/src/lib/db/repos/usage-logs-repo.mjs @@ -11,6 +11,8 @@ import { DB_INSTANCE_ID, getDb, getPgPool, isDbOpen } from '../database.mjs' import { readAll, usagePoolEnabled } from '../sqlite-pool.mjs' import { sanitizePgParams, translateSqliteToPg } from '../pg/sql-compat.mjs' +import { resetWatermarkBefore, runDashboardAggregation } from '../pg/dashboard-aggregator.mjs' +import { USAGE_LOG_COLUMNS, usageLogToRow } from '../pg/pg-log-writer.mjs' import { getCacheRuntime } from '../../cache/index.mjs' import { collectErrors, enrichLogRow, excludeErrorClassSql, ingressAuthSql } from '../../admin/error-class.mjs' import { @@ -95,84 +97,7 @@ function sumCostBuckets(rows) { } } -const SUMMARY_COLUMNS = [ - 'id', - 'request_id', - 'created_at', - 'log_mode', - 'method', - 'path', - 'protocol', - 'model', - 'stream', - 'status', - 'duration_ms', - 'api_key_kind', - 'api_key_id', - 'vm_id', - 'account_id', - 'workspace', - 'input_tokens', - 'output_tokens', - 'error_code', - 'error_message', - 'user_agent', - 'ip_address', - 'api_key_presented', - 'has_tools', - 'via', - 'cache_read_tokens', - 'cache_creation_tokens', - 'cache_creation_5m_tokens', - 'cache_creation_1h_tokens', - 'requested_model', - 'upstream_model', - 'model_mismatch', - 'first_token_ms', - 'first_byte_ms', - 'generation_ms', - 'stop_reason', - 'attempt_count', - 'final_state', - 'final_account_id', - 'usage_account_id', - 'input_cost', - 'output_cost', - 'cache_read_cost', - 'cache_creation_cost', - 'web_search_requests', - 'web_search_cost', - 'total_cost', - 'pricing_model', - 'price_source', - 'price_version', - 'user_id', - 'group_id', - 'actual_cost', - 'rate_multiplier', - 'service_tier', - 'upstream_service_tier', - 'speed', - 'long_context', - 'session_id', - 'outbound_session_id', - 'reasoning_effort', - 'inbound_device_id', - 'upstream_status', - 'upstream_400_message', - 'intercept', - 'jev_state', - 'vm_owner_user_id', - 'image_model', - 'image_usage', - 'image_input_tokens', - 'image_output_tokens', - 'image_cost', - 'advisor_usage', - 'advisor_cost', - 'upstream_type', - 'error_details', -] +const SUMMARY_COLUMNS = USAGE_LOG_COLUMNS function parseErrorDetails(value) { if (value == null || value === '') return null @@ -185,33 +110,7 @@ function parseErrorDetails(value) { } } -function toRow(rec) { - return SUMMARY_COLUMNS.map((c) => { - if (c === 'id') return rec.id ?? rec.request_id ?? globalThis.crypto.randomUUID() - if (c === 'created_at') return rec.created_at ?? rec.ts ?? null - if (c === 'ip_address') return rec.ip_address ?? rec.ip ?? null - if (c === 'stream') return rec.stream ? 1 : 0 - if (c === 'has_tools') return rec.has_tools == null ? null : rec.has_tools ? 1 : 0 - if (c === 'error_details' || c === 'advisor_usage') { - if (rec[c] == null || rec[c] === '') return null - return typeof rec[c] === 'string' ? rec[c] : JSON.stringify(rec[c]) - } - if (c === 'cache_creation_tokens' && rec[c] == null) return null - if ( - c === 'input_tokens' || - c === 'output_tokens' || - c === 'cache_read_tokens' || - c === 'cache_creation_tokens' || - c === 'cache_creation_5m_tokens' || - c === 'cache_creation_1h_tokens' || - c === 'web_search_requests' || - c === 'image_input_tokens' || - c === 'image_output_tokens' - ) - return Number(rec[c]) || 0 - return rec[c] ?? null - }) -} +const toRow = usageLogToRow function fromRow(row) { if (!row) return null @@ -404,9 +303,21 @@ export class UsageLogsRepo { this._debugCount = db.prepare('SELECT COUNT(*) AS n FROM request_log_debug') this._deleteOldUsage = db.prepare('DELETE FROM usage_logs WHERE created_at < ?') this._deleteOldDebug = db.prepare('DELETE FROM request_log_debug WHERE ts < ?') - this._deleteOldestDebug = db.prepare(` - DELETE FROM request_log_debug WHERE request_id IN ( - SELECT request_id FROM request_log_debug ORDER BY ts ASC LIMIT ? + this._selectPruneBatch = db.prepare( + 'SELECT id, created_at FROM usage_logs WHERE created_at < ? ORDER BY created_at ASC, id ASC LIMIT ?', + ) + this._trimDebugWindow = db.prepare(` + DELETE FROM request_log_debug + WHERE request_id IN ( + SELECT request_id FROM ( + SELECT request_id, + SUM(OCTET_LENGTH(record_json)) OVER ( + ORDER BY ts DESC, request_id DESC + ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW + ) AS cum_bytes + FROM request_log_debug + ) t + WHERE cum_bytes > ? ) `) } @@ -724,8 +635,76 @@ export class UsageLogsRepo { return { usage, model: row.image_model, only } } + _computeRepriceBatch(rows, { writeActualCost = false } = {}) { + let changed = 0 + let still_unpriced = 0 + let delta_usd = 0 + const updates = [] + for (const r of rows) { + const model = r.upstream_model || r.model || r.requested_model + const priced = costColumnsFromUsage( + this._usageForPrice(r), + model, + this._imageForPrice(r), + Date.parse(r.created_at), + ) + const nextPricingModel = priced.pricing_model ?? UNPRICED_MODEL + const nextLongContext = priced.long_context == null ? null : priced.long_context ? 1 : 0 + const same = + (r.input_cost ?? null) === (priced.input_cost ?? null) && + (r.output_cost ?? null) === (priced.output_cost ?? null) && + (r.cache_read_cost ?? null) === (priced.cache_read_cost ?? null) && + (r.cache_creation_cost ?? null) === (priced.cache_creation_cost ?? null) && + (r.web_search_cost ?? null) === (priced.web_search_cost ?? null) && + (r.image_cost ?? null) === (priced.image_cost ?? null) && + (r.advisor_cost ?? null) === (priced.advisor_cost ?? null) && + (r.total_cost ?? null) === (priced.total_cost ?? null) && + (r.pricing_model ?? null) === (priced.pricing_model ?? null) && + (r.price_source ?? null) === (priced.price_source ?? null) && + (r.price_version ?? null) === (priced.price_version ?? null) && + (r.long_context ?? null) === (priced.long_context ?? null) + if (priced.pricing_model === UNPRICED_MODEL || priced.total_cost == null) still_unpriced += 1 + if (!same) { + changed += 1 + delta_usd += + (Number(priced.total_cost) || 0) - (Number.isFinite(Number(r.total_cost)) ? Number(r.total_cost) : 0) + } + const needsWrite = writeActualCost || !same || (r.pricing_model ?? null) !== nextPricingModel + if (!needsWrite) continue + const parsedRate = r.rate_multiplier == null ? 1 : Number(r.rate_multiplier) + const rate = Number.isFinite(parsedRate) ? parsedRate : 1 + const actual = writeActualCost ? (priced.total_cost == null ? null : priced.total_cost * rate) : undefined + updates.push({ + id: String(r.id), + input_cost: priced.input_cost ?? null, + output_cost: priced.output_cost ?? null, + cache_read_cost: priced.cache_read_cost ?? null, + cache_creation_cost: priced.cache_creation_cost ?? null, + web_search_cost: priced.web_search_cost ?? null, + image_cost: priced.image_cost ?? null, + advisor_cost: priced.advisor_cost ?? null, + total_cost: priced.total_cost ?? null, + actual_cost: actual, + pricing_model: nextPricingModel, + price_source: priced.price_source ?? null, + price_version: priced.price_version ?? null, + long_context: nextLongContext, + }) + } + return { rows: rows.length, changed, still_unpriced, delta_usd, updates } + } + _repriceRows(rows, { writeActualCost = false } = {}) { if (!rows.length) return { rows: 0, changed: 0, still_unpriced: 0, delta_usd: 0 } + const batch = this._computeRepriceBatch(rows, { writeActualCost }) + if (!batch.updates.length) { + return { + rows: batch.rows, + changed: batch.changed, + still_unpriced: batch.still_unpriced, + delta_usd: batch.delta_usd, + } + } const upd = writeActualCost ? this.db.prepare(` UPDATE usage_logs @@ -742,73 +721,41 @@ export class UsageLogsRepo { pricing_model = ?, price_source = ?, price_version = ?, long_context = ? WHERE id = ? `) - let changed = 0 - let still_unpriced = 0 - let delta_usd = 0 this.db.exec('BEGIN') try { - for (const r of rows) { - const model = r.upstream_model || r.model || r.requested_model - const priced = costColumnsFromUsage( - this._usageForPrice(r), - model, - this._imageForPrice(r), - Date.parse(r.created_at), - ) - const same = - (r.input_cost ?? null) === (priced.input_cost ?? null) && - (r.output_cost ?? null) === (priced.output_cost ?? null) && - (r.cache_read_cost ?? null) === (priced.cache_read_cost ?? null) && - (r.cache_creation_cost ?? null) === (priced.cache_creation_cost ?? null) && - (r.web_search_cost ?? null) === (priced.web_search_cost ?? null) && - (r.image_cost ?? null) === (priced.image_cost ?? null) && - (r.advisor_cost ?? null) === (priced.advisor_cost ?? null) && - (r.total_cost ?? null) === (priced.total_cost ?? null) && - (r.pricing_model ?? null) === (priced.pricing_model ?? null) && - (r.price_source ?? null) === (priced.price_source ?? null) && - (r.price_version ?? null) === (priced.price_version ?? null) && - (r.long_context ?? null) === (priced.long_context ?? null) - if (priced.pricing_model === UNPRICED_MODEL || priced.total_cost == null) still_unpriced += 1 - if (!same) { - changed += 1 - delta_usd += - (Number(priced.total_cost) || 0) - (Number.isFinite(Number(r.total_cost)) ? Number(r.total_cost) : 0) - } + for (const u of batch.updates) { if (writeActualCost) { - const parsedRate = r.rate_multiplier == null ? 1 : Number(r.rate_multiplier) - const rate = Number.isFinite(parsedRate) ? parsedRate : 1 - const actual = priced.total_cost == null ? null : priced.total_cost * rate upd.run( - priced.input_cost ?? null, - priced.output_cost ?? null, - priced.cache_read_cost ?? null, - priced.cache_creation_cost ?? null, - priced.web_search_cost ?? null, - priced.image_cost ?? null, - priced.advisor_cost ?? null, - priced.total_cost ?? null, - actual, - priced.pricing_model ?? UNPRICED_MODEL, - priced.price_source ?? null, - priced.price_version ?? null, - priced.long_context ?? null, - r.id, + u.input_cost, + u.output_cost, + u.cache_read_cost, + u.cache_creation_cost, + u.web_search_cost, + u.image_cost, + u.advisor_cost, + u.total_cost, + u.actual_cost, + u.pricing_model, + u.price_source, + u.price_version, + u.long_context, + u.id, ) } else { upd.run( - priced.input_cost ?? null, - priced.output_cost ?? null, - priced.cache_read_cost ?? null, - priced.cache_creation_cost ?? null, - priced.web_search_cost ?? null, - priced.image_cost ?? null, - priced.advisor_cost ?? null, - priced.total_cost ?? null, - priced.pricing_model ?? UNPRICED_MODEL, - priced.price_source ?? null, - priced.price_version ?? null, - priced.long_context ?? null, - r.id, + u.input_cost, + u.output_cost, + u.cache_read_cost, + u.cache_creation_cost, + u.web_search_cost, + u.image_cost, + u.advisor_cost, + u.total_cost, + u.pricing_model, + u.price_source, + u.price_version, + u.long_context, + u.id, ) } } @@ -819,7 +766,12 @@ export class UsageLogsRepo { } catch {} throw e } - return { rows: rows.length, changed, still_unpriced, delta_usd } + return { + rows: batch.rows, + changed: batch.changed, + still_unpriced: batch.still_unpriced, + delta_usd: batch.delta_usd, + } } /** @@ -877,7 +829,16 @@ export class UsageLogsRepo { after = String(rows.at(-1).id) } out.delta_usd = Math.round(out.delta_usd * 1e8) / 1e8 - if (out.changed > 0 || out.rows > 0) this.invalidateBillingCache() + if (out.changed > 0 || out.rows > 0) { + this.invalidateBillingCache() + const pgPool = getPgPool() + if (pgPool && isDbOpen() && this.db === getDb()) { + const sinceIso = since ? new Date(since).toISOString() : null + void resetWatermarkBefore(pgPool, sinceIso) + .then(() => runDashboardAggregation(pgPool)) + .catch(() => {}) + } + } return out } const where = cond ? `${cond} AND rowid > ?` : 'WHERE rowid > ?' @@ -911,6 +872,181 @@ export class UsageLogsRepo { return out } + /** + * Async non-blocking range reprice for PG using `(created_at, id)` composite + * keyset pagination (matching `idx_usage_logs_created_id`) and id-sorted + * `UNNEST` batch `UPDATE`, then rewinding the dashboard aggregation watermark + * and triggering background re-aggregation so pre-aggregated stats stay fresh. + */ + async repriceRangeAsync({ since, until, pgPool = null, awaitAggregation = false } = {}) { + const isPg = this.db?.engine === 'postgres' + const pool = pgPool || (isPg && isDbOpen() && this.db === getDb() ? getPgPool() : null) + if (!isPg || !pool || typeof pool.query !== 'function') { + return this.repriceRange({ since, until }) + } + const sinceIso = since ? new Date(since).toISOString() : null + const untilIso = until ? new Date(until).toISOString() : null + const PAGE_SIZE = 2000 + const out = { rows: 0, changed: 0, still_unpriced: 0, delta_usd: 0 } + let cursorCreatedAt = null + let cursorId = null + + for (;;) { + const clauses = [] + const params = [] + if (sinceIso) { + params.push(sinceIso) + clauses.push(`created_at >= $${params.length}`) + } + if (untilIso) { + params.push(untilIso) + clauses.push(`created_at <= $${params.length}`) + } + if (cursorCreatedAt !== null && cursorId !== null) { + params.push(cursorCreatedAt, cursorId) + clauses.push(`(created_at, id) < ($${params.length - 1}, $${params.length})`) + } + params.push(PAGE_SIZE) + const whereSql = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '' + const res = await pool.query( + ` + SELECT id, created_at, model, upstream_model, requested_model, + input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, + cache_creation_5m_tokens, cache_creation_1h_tokens, web_search_requests, + rate_multiplier, service_tier, speed, protocol, image_model, image_usage, + advisor_usage, input_cost, output_cost, cache_read_cost, cache_creation_cost, + web_search_cost, image_cost, advisor_cost, total_cost, pricing_model, + price_source, price_version, long_context + FROM usage_logs + ${whereSql} + ORDER BY created_at DESC, id DESC + LIMIT $${params.length} + `, + params, + ) + const rows = res.rows || [] + if (!rows.length) break + + const part = this._computeRepriceBatch(rows, { writeActualCost: false }) + if (part.updates.length) { + // Sort by primary key `id` to keep lock acquisition order deterministic and prevent PG 40P01 deadlocks. + part.updates.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + const ids = [] + const inputCosts = [] + const outputCosts = [] + const cacheReadCosts = [] + const cacheCreationCosts = [] + const webSearchCosts = [] + const imageCosts = [] + const advisorCosts = [] + const totalCosts = [] + const pricingModels = [] + const priceSources = [] + const priceVersions = [] + const longContexts = [] + for (const u of part.updates) { + ids.push(u.id) + inputCosts.push(u.input_cost) + outputCosts.push(u.output_cost) + cacheReadCosts.push(u.cache_read_cost) + cacheCreationCosts.push(u.cache_creation_cost) + webSearchCosts.push(u.web_search_cost) + imageCosts.push(u.image_cost) + advisorCosts.push(u.advisor_cost) + totalCosts.push(u.total_cost) + pricingModels.push(u.pricing_model) + priceSources.push(u.price_source) + priceVersions.push(u.price_version) + longContexts.push(u.long_context) + } + await pool.query( + ` + UPDATE usage_logs AS u + SET input_cost = v.input_cost, + output_cost = v.output_cost, + cache_read_cost = v.cache_read_cost, + cache_creation_cost = v.cache_creation_cost, + web_search_cost = v.web_search_cost, + image_cost = v.image_cost, + advisor_cost = v.advisor_cost, + total_cost = v.total_cost, + pricing_model = v.pricing_model, + price_source = v.price_source, + price_version = v.price_version, + long_context = v.long_context + FROM UNNEST( + $1::text[], + $2::double precision[], + $3::double precision[], + $4::double precision[], + $5::double precision[], + $6::double precision[], + $7::double precision[], + $8::double precision[], + $9::double precision[], + $10::text[], + $11::text[], + $12::text[], + $13::integer[] + ) AS v( + id, + input_cost, + output_cost, + cache_read_cost, + cache_creation_cost, + web_search_cost, + image_cost, + advisor_cost, + total_cost, + pricing_model, + price_source, + price_version, + long_context + ) + WHERE u.id = v.id + `, + [ + ids, + inputCosts, + outputCosts, + cacheReadCosts, + cacheCreationCosts, + webSearchCosts, + imageCosts, + advisorCosts, + totalCosts, + pricingModels, + priceSources, + priceVersions, + longContexts, + ], + ) + } + + out.rows += part.rows + out.changed += part.changed + out.still_unpriced += part.still_unpriced + out.delta_usd += part.delta_usd + + if (rows.length < PAGE_SIZE) break + const last = rows.at(-1) + cursorCreatedAt = String(last.created_at) + cursorId = String(last.id) + } + + out.delta_usd = Math.round(out.delta_usd * 1e8) / 1e8 + if (out.changed > 0 || out.rows > 0) { + await resetWatermarkBefore(pool, sinceIso).catch(() => {}) + this.invalidateBillingCache() + if (awaitAggregation) { + await runDashboardAggregation(pool).catch(() => {}) + } else { + void runDashboardAggregation(pool).catch(() => {}) + } + } + return out + } + unpricedModels({ since } = {}) { const where = [`pricing_model = '${UNPRICED_MODEL}'`] const params = [] @@ -1900,16 +2036,6 @@ export class UsageLogsRepo { const cond = where.length ? `WHERE ${where.join(' AND ')}` : '' const grouped = groupBy === 'key' ? 'key' : 'vm' const groupCol = grouped === 'key' ? 'api_key_id' : 'vm_id' - const totalsSql = ` - SELECT COUNT(*) AS requests, - SUM(CASE WHEN ${SUCCESS_PRED} THEN 1 ELSE 0 END) AS ok, - SUM(CASE WHEN ${ERROR_PRED} THEN 1 ELSE 0 END) AS fail, - COALESCE(SUM(${PROMPT_TOKENS_SQL}), 0) AS tokens_in, - COALESCE(SUM(output_tokens), 0) AS tokens_out, - COALESCE(SUM(COALESCE(actual_cost, total_cost, 0)), 0) AS cost_usd, - COALESCE(SUM(COALESCE(total_cost, 0)), 0) AS official_cost_usd - FROM usage_logs ${cond} - ` const itemsSql = ` SELECT ${groupCol} AS id, COUNT(*) AS requests, @@ -1923,63 +2049,73 @@ export class UsageLogsRepo { GROUP BY ${groupCol} ORDER BY cost_usd DESC ` - return { grouped, sinceIso, untilIso, params, totalsSql, itemsSql } + return { grouped, sinceIso, untilIso, params, itemsSql } } - _formatOwnerBilling({ totals, items, grouped, sinceIso, untilIso }) { + _formatOwnerBilling({ items, grouped, sinceIso, untilIso }) { const num = (row, key) => Number(row?.[key] || 0) + const formattedItems = (items || []).map((row) => ({ + vm_id: grouped === 'vm' ? row.id || null : undefined, + api_key_id: grouped === 'key' ? row.id || null : undefined, + requests: num(row, 'requests'), + ok: num(row, 'ok'), + fail: num(row, 'fail'), + tokens_in: num(row, 'tokens_in'), + tokens_out: num(row, 'tokens_out'), + cost_usd: num(row, 'cost_usd'), + official_cost_usd: num(row, 'official_cost_usd'), + })) + const totals = formattedItems.reduce( + (acc, item) => { + acc.requests += item.requests + acc.ok += item.ok + acc.fail += item.fail + acc.tokens_in += item.tokens_in + acc.tokens_out += item.tokens_out + acc.cost_usd += item.cost_usd + acc.official_cost_usd += item.official_cost_usd + return acc + }, + { + requests: 0, + ok: 0, + fail: 0, + tokens_in: 0, + tokens_out: 0, + cost_usd: 0, + official_cost_usd: 0, + }, + ) return { group_by: grouped, since: sinceIso, until: untilIso, - totals: { - requests: num(totals, 'requests'), - ok: num(totals, 'ok'), - fail: num(totals, 'fail'), - tokens_in: num(totals, 'tokens_in'), - tokens_out: num(totals, 'tokens_out'), - cost_usd: num(totals, 'cost_usd'), - official_cost_usd: num(totals, 'official_cost_usd'), - }, - items: (items || []).map((row) => ({ - vm_id: grouped === 'vm' ? row.id || null : undefined, - api_key_id: grouped === 'key' ? row.id || null : undefined, - requests: num(row, 'requests'), - ok: num(row, 'ok'), - fail: num(row, 'fail'), - tokens_in: num(row, 'tokens_in'), - tokens_out: num(row, 'tokens_out'), - cost_usd: num(row, 'cost_usd'), - official_cost_usd: num(row, 'official_cost_usd'), - })), + totals, + items: formattedItems, } } ownerBilling({ ownerUserId = null, since = null, until = null, groupBy = 'vm' } = {}) { - const { grouped, sinceIso, untilIso, params, totalsSql, itemsSql } = this._ownerBillingQueryParts({ + const { grouped, sinceIso, untilIso, params, itemsSql } = this._ownerBillingQueryParts({ ownerUserId, since, until, groupBy, }) - const totals = this.db.prepare(totalsSql).get(...params) const items = this.db.prepare(itemsSql).all(...params) - return this._formatOwnerBilling({ totals, items, grouped, sinceIso, untilIso }) + return this._formatOwnerBilling({ items, grouped, sinceIso, untilIso }) } async ownerBillingAsync({ ownerUserId = null, since = null, until = null, groupBy = 'vm', bypass = false } = {}) { - const { grouped, sinceIso, untilIso, params, totalsSql, itemsSql } = this._ownerBillingQueryParts({ + const { grouped, sinceIso, untilIso, params, itemsSql } = this._ownerBillingQueryParts({ ownerUserId, since, until, groupBy, }) const load = async () => { - const [totals, items] = await Promise.all([ - this._readRowAsync(totalsSql, params), - this._readRowsAsync(itemsSql, params), - ]) - return this._formatOwnerBilling({ totals, items, grouped, sinceIso, untilIso }) + const items = await this._readRowsAsync(itemsSql, params) + return this._formatOwnerBilling({ items, grouped, sinceIso, untilIso }) } return getCacheRuntime().dashboard.getOrSetSWR( 'stats', @@ -2056,6 +2192,7 @@ export class UsageLogsRepo { COALESCE(SUM(${TOTAL_TOKENS_SQL}), 0) AS tokens FROM usage_logs ${where} GROUP BY minute + ORDER BY minute ASC `) .all(...allParams) const peakReq = minuteRows.reduce((m, r) => Math.max(m, Number(r.requests || 0)), 0) @@ -2256,42 +2393,59 @@ export class UsageLogsRepo { } } - /** Delete summaries before `cutoff` and advance the prune boundary in one transaction. */ - _pruneUsage(cutoff) { - this.db.exec('BEGIN') - try { - this.db - .prepare(` - INSERT INTO account_lifetime_usage_archive (account_id, total_cost, total_tokens) - SELECT ${LIFETIME_ACCOUNT_SQL}, COALESCE(SUM(total_cost), 0), COALESCE(SUM(${TOTAL_TOKENS_SQL}), 0) - FROM usage_logs - WHERE created_at < ? AND (${LIFETIME_ACCOUNT_SQL}) IS NOT NULL - GROUP BY 1 - ON CONFLICT(account_id) DO UPDATE SET - total_cost = account_lifetime_usage_archive.total_cost + excluded.total_cost, - total_tokens = account_lifetime_usage_archive.total_tokens + excluded.total_tokens - `) - .run(cutoff) - const deleted = this._deleteOldUsage.run(cutoff).changes - if (deleted > 0) { - const prev = this._prunedThrough() - if (!prev || prev < cutoff) { - this.db - .prepare(` - INSERT INTO settings (key, value, updated_at) VALUES ('${PRUNED_THROUGH_KEY}', ?, ?) - ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at - `) - .run(JSON.stringify(cutoff), new Date().toISOString()) + /** Delete summaries before `cutoff` in bounded transactional batches and advance the prune boundary. */ + _pruneUsage(cutoff, { batchSize = 500 } = {}) { + const size = Math.max(1, Math.min(2000, Number(batchSize) || 500)) + const upsertPruned = this.db.prepare(` + INSERT INTO settings (key, value, updated_at) VALUES ('${PRUNED_THROUGH_KEY}', ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at + `) + let totalDeleted = 0 + for (;;) { + const batch = this._selectPruneBatch.all(cutoff, size) + if (!batch.length) break + const ids = batch.map((r) => r.id) + const ph = ids.map(() => '?').join(', ') + const isFinalBatch = batch.length < size + const boundary = isFinalBatch ? cutoff : String(batch[batch.length - 1].created_at || cutoff) + this.db.exec('BEGIN') + try { + this.db + .prepare(` + INSERT INTO account_lifetime_usage_archive (account_id, total_cost, total_tokens) + SELECT ${LIFETIME_ACCOUNT_SQL}, COALESCE(SUM(total_cost), 0), COALESCE(SUM(${TOTAL_TOKENS_SQL}), 0) + FROM usage_logs + WHERE id IN (${ph}) AND (${LIFETIME_ACCOUNT_SQL}) IS NOT NULL + GROUP BY 1 + ON CONFLICT(account_id) DO UPDATE SET + total_cost = account_lifetime_usage_archive.total_cost + excluded.total_cost, + total_tokens = account_lifetime_usage_archive.total_tokens + excluded.total_tokens + `) + .run(...ids) + const deleted = this.db.prepare(`DELETE FROM usage_logs WHERE id IN (${ph})`).run(...ids).changes + if (deleted > 0) { + totalDeleted += deleted + const prev = this._prunedThrough() + if (!prev || prev < boundary) { + upsertPruned.run(JSON.stringify(boundary), new Date().toISOString()) + } } + this.db.exec('COMMIT') + if (deleted === 0 || isFinalBatch) break + } catch (e) { + try { + this.db.exec('ROLLBACK') + } catch {} + throw e } - this.db.exec('COMMIT') - return deleted - } catch (e) { - try { - this.db.exec('ROLLBACK') - } catch {} - throw e } + if (totalDeleted > 0) { + const prev = this._prunedThrough() + if (!prev || prev < cutoff) { + upsertPruned.run(JSON.stringify(cutoff), new Date().toISOString()) + } + } + return totalDeleted } _cleanupOpts(opts) { @@ -2314,23 +2468,11 @@ export class UsageLogsRepo { return Number(this._debugCount.get().n || 0) } - /** Delete oldest debug rows until the stored JSON bytes fit maxBytes. */ + /** Delete oldest debug rows until the stored JSON bytes fit maxBytes in a single window scan. */ trimDebugToMaxBytes(maxBytes) { const cap = Math.max(0, Number(maxBytes) || 0) if (cap <= 0) return 0 - let deleted = 0 - for (let i = 0; i < 8; i++) { - const used = this.debugBytes() - if (used <= cap) return deleted - const count = this.countDebug() - if (!count) return deleted - const avg = Math.max(1, Math.floor(used / count)) - const need = Math.min(count, Math.max(1, Math.ceil((used - cap) / avg) + 1)) - const n = this._deleteOldestDebug.run(need).changes - if (!n) return deleted - deleted += n - } - return deleted + return this._trimDebugWindow.run(cap).changes } count() { diff --git a/src/lib/db/repos/usage-logs-view.mjs b/src/lib/db/repos/usage-logs-view.mjs index ae93049a34..09a2eac00d 100644 --- a/src/lib/db/repos/usage-logs-view.mjs +++ b/src/lib/db/repos/usage-logs-view.mjs @@ -463,9 +463,10 @@ function mutedClasses(filters, defaults) { * Query-string filters (snake_case, see `UsageLogFilters`) → SQL fragment + * the JS predicate for what SQL cannot express (read-time error classes). */ -function buildFilter(filters, defaultMuted) { +function buildFilter(filters, defaultMuted, { splitOr = false } = {}) { const where = [] const params = [] + let orSplit = null const own = ownerPred(filters.owner_user_id) if (own.sql) { where.push(own.sql) @@ -492,12 +493,20 @@ function buildFilter(filters, defaultMuted) { else if (filters.upstream_400) where.push('upstream_status = 400') eq('request_id', filters.request_id) if (filters.account_id) { - where.push('(account_id = ? OR final_account_id = ?)') - params.push(filters.account_id, filters.account_id) + if (splitOr && !orSplit) { + orSplit = { colA: 'account_id', colB: 'final_account_id', value: String(filters.account_id) } + } else { + where.push('(account_id = ? OR final_account_id = ?)') + params.push(filters.account_id, filters.account_id) + } } if (filters.model) { - where.push('(model = ? OR requested_model = ?)') - params.push(filters.model, filters.model) + if (splitOr && !orSplit) { + orSplit = { colA: 'model', colB: 'requested_model', value: String(filters.model) } + } else { + where.push('(model = ? OR requested_model = ?)') + params.push(filters.model, filters.model) + } } const statusCode = clampInt(filters.status_code, 0, 999, null) if (statusCode != null) { @@ -509,7 +518,7 @@ function buildFilter(filters, defaultMuted) { if (filters.model_mismatch) where.push('model_mismatch = 1') const minAttempts = clampInt(filters.min_attempt_count, 0, 1000, null) if (minAttempts != null) { - where.push('IFNULL(attempt_count, 0) >= ?') + where.push('COALESCE(attempt_count, 0) >= ?') params.push(minAttempts) } if (filters.debug_only) where.push("log_mode = 'debug'") @@ -548,6 +557,7 @@ function buildFilter(filters, defaultMuted) { return { where, params, + orSplit, keep, sqlOnlySummary: !errorClass && !filters.model_mismatch && muted.every((c) => c === 'auth'), } @@ -727,23 +737,23 @@ function normalizeLiveRawEntry(entry, now) { /** * Apply tenant isolation and active query filters to a Redis/local live or recent entry. - * Filters that only make sense for completed responses (status_code, error_class, - * failed_only, min_latency, upstream_400, etc.) automatically exclude in-flight entries. + * Returns the normalized (and enriched) row on match so callers can reuse it without + * running `normalizeLiveRawEntry` / `enrichLogRow` twice, or `null` when filtered out. */ -function matchesLiveEntry(rawEntry, filters, defaultMuted, { now = Date.now(), getOwnerKeyIds = null } = {}) { - if (!rawEntry || typeof rawEntry !== 'object' || !rawEntry.request_id) return false - if (!entryBelongsToOwner(rawEntry, filters.owner_user_id, getOwnerKeyIds)) return false +function matchAndNormalizeLiveEntry(rawEntry, filters, defaultMuted, { now = Date.now(), getOwnerKeyIds = null } = {}) { + if (!rawEntry || typeof rawEntry !== 'object' || !rawEntry.request_id) return null + if (!entryBelongsToOwner(rawEntry, filters.owner_user_id, getOwnerKeyIds)) return null const inFlight = rawEntry.in_flight === true const row = normalizeLiveRawEntry(rawEntry, now) - if (filters.user_id && String(row.user_id || '') !== String(filters.user_id)) return false + if (filters.user_id && String(row.user_id || '') !== String(filters.user_id)) return null const keyFilter = filters.key_id ?? filters.api_key_id - if (keyFilter && String(row.api_key_id || '') !== String(keyFilter)) return false - if (filters.vm_id && String(row.vm_id || '') !== String(filters.vm_id)) return false + if (keyFilter && String(row.api_key_id || '') !== String(keyFilter)) return null + if (filters.vm_id && String(row.vm_id || '') !== String(filters.vm_id)) return null if (filters.account_id) { const targetAcc = String(filters.account_id) - if (String(row.account_id || '') !== targetAcc && String(row.final_account_id || '') !== targetAcc) return false + if (String(row.account_id || '') !== targetAcc && String(row.final_account_id || '') !== targetAcc) return null } const sessionFilter = filters.session_id ?? filters.session_key if (sessionFilter) { @@ -753,81 +763,81 @@ function matchesLiveEntry(rawEntry, filters, defaultMuted, { now = Date.now(), g String(row.session_id || '') !== targetSess && String(rawEntry.session_key || '') !== targetSess ) { - return false + return null } } - if (filters.endpoint && String(row.path || '') !== String(filters.endpoint)) return false - if (filters.protocol && String(row.protocol || '') !== String(filters.protocol)) return false - if (filters.via && String(row.via || '') !== String(filters.via)) return false + if (filters.endpoint && String(row.path || '') !== String(filters.endpoint)) return null + if (filters.protocol && String(row.protocol || '') !== String(filters.protocol)) return null + if (filters.via && String(row.via || '') !== String(filters.via)) return null if (filters.final_state) { - if (inFlight || String(row.final_state || '') !== String(filters.final_state)) return false + if (inFlight || String(row.final_state || '') !== String(filters.final_state)) return null } - if (filters.request_id && String(row.request_id || '') !== String(filters.request_id)) return false + if (filters.request_id && String(row.request_id || '') !== String(filters.request_id)) return null if (filters.model) { const targetModel = String(filters.model) - if (String(row.model || '') !== targetModel && String(row.requested_model || '') !== targetModel) return false + if (String(row.model || '') !== targetModel && String(row.requested_model || '') !== targetModel) return null } const statusCode = clampInt(filters.status_code ?? filters.statusCode, 0, 999, null) if (statusCode != null) { - if (inFlight || row.status == null || Number(row.status) !== statusCode) return false + if (inFlight || row.status == null || Number(row.status) !== statusCode) return null } else if (filters.status != null && filters.status !== '') { const rawStatus = String(filters.status).trim().toLowerCase() if (rawStatus === 'in_flight' || rawStatus === 'inflight') { - if (!inFlight) return false + if (!inFlight) return null } else if (rawStatus === 'ok' || rawStatus === 'success') { if (inFlight || row.status == null || Number(row.status) < 200 || Number(row.status) >= 400 || isErrorRow(row)) { - return false + return null } } else if (rawStatus === 'error') { - if (inFlight || !isErrorRow(row)) return false + if (inFlight || !isErrorRow(row)) return null } else if (/^\d+$/.test(rawStatus)) { - if (inFlight || row.status == null || Number(row.status) !== Number(rawStatus)) return false + if (inFlight || row.status == null || Number(row.status) !== Number(rawStatus)) return null } } else if (filters.exclude_status_200) { - if (inFlight) return false - if (row.status != null && Number(row.status) >= 200 && Number(row.status) < 300) return false + if (inFlight) return null + if (row.status != null && Number(row.status) >= 200 && Number(row.status) < 300) return null } if (filters.upstream_risk_errors) { - if (inFlight || !UPSTREAM_RISK_STATUSES.has(Number(row.upstream_status))) return false + if (inFlight || !UPSTREAM_RISK_STATUSES.has(Number(row.upstream_status))) return null } else if (filters.upstream_400) { - if (inFlight || Number(row.upstream_status) !== 400) return false + if (inFlight || Number(row.upstream_status) !== 400) return null } if (filters.model_mismatch) { - if (inFlight || effectiveModelMismatch(row) !== 1) return false + if (inFlight || effectiveModelMismatch(row) !== 1) return null } const minAttempts = clampInt(filters.min_attempt_count, 0, 1000, null) if (minAttempts != null) { - if ((Number(row.attempt_count) || 0) < minAttempts) return false + if ((Number(row.attempt_count) || 0) < minAttempts) return null } const rawMinLatency = filters.min_latency ?? filters.minLatency ?? filters.min_duration_ms if (rawMinLatency != null && rawMinLatency !== '') { const minLatency = Number(rawMinLatency) if (Number.isFinite(minLatency) && minLatency > 0) { - if (inFlight || row.duration_ms == null || Number(row.duration_ms) < minLatency) return false + if (inFlight || row.duration_ms == null || Number(row.duration_ms) < minLatency) return null } } - if (filters.debug_only && row.log_mode !== 'debug') return false - if (filters.errors_only && (inFlight || !isErrorRow(row))) return false + if (filters.debug_only && row.log_mode !== 'debug') return null + if (filters.errors_only && (inFlight || !isErrorRow(row))) return null if (filters.failed_only) { - if (inFlight) return false + if (inFlight) return null const non2xx = row.status == null || Number(row.status) < 200 || Number(row.status) >= 300 const badFinal = row.final_state != null && row.final_state !== '' && row.final_state !== 'verified' - if (!non2xx && !badFinal && !isErrorRow(row)) return false + if (!non2xx && !badFinal && !isErrorRow(row)) return null } const start = isoOrNull(filters.start_time) const end = isoOrNull(filters.end_time) if (start || end) { const entryMs = Date.parse(row.created_at) - if (!Number.isFinite(entryMs)) return false - if (start && entryMs < Date.parse(start)) return false - if (end && entryMs >= Date.parse(end)) return false + if (!Number.isFinite(entryMs)) return null + if (start && entryMs < Date.parse(start)) return null + if (end && entryMs >= Date.parse(end)) return null } if (filters.q) { @@ -835,23 +845,23 @@ function matchesLiveEntry(rawEntry, filters, defaultMuted, { now = Date.now(), g const hay = [row.path, row.error_code, row.error_message, row.request_id, row.upstream_type] .filter((v) => v != null && v !== '') .map((v) => String(v).toLowerCase()) - if (!hay.some((s) => s.includes(needle))) return false + if (!hay.some((s) => s.includes(needle))) return null } const errorClass = filters.error_class ? String(filters.error_class) : null if (errorClass) { - if (inFlight || row.error_class !== errorClass) return false + if (inFlight || row.error_class !== errorClass) return null } else { const muted = mutedClasses(filters, defaultMuted) - if (muted.length && !inFlight && row.error_class && muted.includes(row.error_class)) return false + if (muted.length && !inFlight && row.error_class && muted.includes(row.error_class)) return null } - return true + return row } -function liveEntryToUsageLogRow(rawEntry, names, now = Date.now()) { +function liveEntryToUsageLogRow(rawEntry, names, now = Date.now(), normalizedRow = null) { const inFlight = rawEntry.in_flight === true - const row = normalizeLiveRawEntry(rawEntry, now) + const row = normalizedRow || normalizeLiveRawEntry(rawEntry, now) const viewRow = toUsageLogRow(row, names, []) if (inFlight) { const live = rawEntry._live && typeof rawEntry._live === 'object' ? rawEntry._live : {} @@ -939,7 +949,7 @@ export class UsageLogsView { */ listBatch(filters = {}) { const limit = clampInt(filters.limit, 1, LIST_LIMIT_MAX, LIST_LIMIT_DEFAULT) - const { where, params, keep } = buildFilter(filters, this.mutedErrorClasses) + const { where, params, orSplit, keep } = buildFilter(filters, this.mutedErrorClasses, { splitOr: true }) let cursor = filters.cursor_created_at && filters.cursor_id ? { createdAt: String(filters.cursor_created_at), id: String(filters.cursor_id) } @@ -956,9 +966,27 @@ export class UsageLogsView { w.push('(created_at < ? OR (created_at = ? AND id < ?))') p.push(cursor.createdAt, cursor.createdAt, cursor.id) } - const rows = this.db - .prepare(`SELECT * FROM usage_logs ${whereSql(w)} ORDER BY created_at DESC, id DESC LIMIT ?`) - .all(...p, want) + let rows + if (orSplit) { + // Two mutually exclusive top-N branches avoid PG single-OR selectivity blowups + // and dormant-entity full scans without adding high-write-amplification indexes. + const wA = [...w, `${orSplit.colA} = ?`] + const pA = [...p, orSplit.value, want] + const wB = [...w, `${orSplit.colB} = ?`, `(${orSplit.colA} IS NULL OR ${orSplit.colA} <> ?)`] + const pB = [...p, orSplit.value, orSplit.value, want] + rows = this.db + .prepare( + `SELECT * FROM (SELECT * FROM usage_logs ${whereSql(wA)} ORDER BY created_at DESC, id DESC LIMIT ?) AS u1 ` + + `UNION ALL ` + + `SELECT * FROM (SELECT * FROM usage_logs ${whereSql(wB)} ORDER BY created_at DESC, id DESC LIMIT ?) AS u2 ` + + `ORDER BY created_at DESC, id DESC LIMIT ?`, + ) + .all(...pA, ...pB, want) + } else { + rows = this.db + .prepare(`SELECT * FROM usage_logs ${whereSql(w)} ORDER BY created_at DESC, id DESC LIMIT ?`) + .all(...p, want) + } for (const raw of rows) { scanned++ lastScanned = raw @@ -1076,13 +1104,38 @@ export class UsageLogsView { return ownerKeyIds } - const filteredLive = hasCursor - ? [] - : rawLiveEntries.filter((entry) => - matchesLiveEntry(entry, filters, this.mutedErrorClasses, { now, getOwnerKeyIds }), - ) + // Deduplicate against persisted PG page request_ids BEFORE filtering/normalizing live + // entries, and keep each normalized row so `_mergeFirstPageWithLive` never enriches twice. + const pgRequestIds = new Set() + if (baseRes && baseRes._rawRows === true) { + for (const r of Array.isArray(baseRes.rows) ? baseRes.rows : []) { + const reqId = String(r?.request_id || '') + if (reqId) pgRequestIds.add(reqId) + } + } else { + for (const r of Array.isArray(baseRes?.logs) ? baseRes.logs : []) { + const reqId = String(r?.requestId || r?.request_id || '') + if (reqId) pgRequestIds.add(reqId) + } + } + + const filteredLive = [] + if (!hasCursor) { + const seenLive = new Set() + for (const entry of rawLiveEntries) { + const reqId = String(entry?.request_id || '') + if (!reqId || pgRequestIds.has(reqId) || seenLive.has(reqId)) continue + const normalizedRow = matchAndNormalizeLiveEntry(entry, filters, this.mutedErrorClasses, { + now, + getOwnerKeyIds, + }) + if (!normalizedRow) continue + seenLive.add(reqId) + filteredLive.push({ entry, row: normalizedRow }) + } + } - // Hydrate DB rows + filtered live/recent entries using ONE batched EntityCache lookup. + // Hydrate DB rows + deduplicated filtered live/recent entries using ONE batched EntityCache lookup. let pgLogs if (baseRes && baseRes._rawRows === true) { const rows = Array.isArray(baseRes.rows) ? baseRes.rows : [] @@ -1090,17 +1143,19 @@ export class UsageLogsView { const names = await lookupNamesAsync( this.db, { - userIds: [...rows.map((r) => r.user_id), ...filteredLive.map((e) => e.user_id)], - keyIds: [...rows.map((r) => r.api_key_id), ...filteredLive.map((e) => e.api_key_id)], + userIds: [...rows.map((r) => r.user_id), ...filteredLive.map((item) => item.entry.user_id)], + keyIds: [...rows.map((r) => r.api_key_id), ...filteredLive.map((item) => item.entry.api_key_id)], vmIds: [ ...rows.map((r) => r.vm_id), ...attempts.map((a) => a.vm_id), - ...filteredLive.map((e) => e._live?.vm_id ?? e.vm_id), + ...filteredLive.map((item) => item.entry._live?.vm_id ?? item.entry.vm_id), ], accountIds: [ ...rows.map((r) => r.final_account_id || r.account_id), ...attempts.map((a) => a.account_id), - ...filteredLive.map((e) => e._live?.account_id ?? e.final_account_id ?? e.account_id), + ...filteredLive.map( + (item) => item.entry._live?.account_id ?? item.entry.final_account_id ?? item.entry.account_id, + ), ], }, { cache }, @@ -1143,10 +1198,12 @@ export class UsageLogsView { const liveNames = await lookupNamesAsync( this.db, { - userIds: filteredLive.map((e) => e.user_id), - keyIds: filteredLive.map((e) => e.api_key_id), - vmIds: filteredLive.map((e) => e._live?.vm_id ?? e.vm_id), - accountIds: filteredLive.map((e) => e._live?.account_id ?? e.final_account_id ?? e.account_id), + userIds: filteredLive.map((item) => item.entry.user_id), + keyIds: filteredLive.map((item) => item.entry.api_key_id), + vmIds: filteredLive.map((item) => item.entry._live?.vm_id ?? item.entry.vm_id), + accountIds: filteredLive.map( + (item) => item.entry._live?.account_id ?? item.entry.final_account_id ?? item.entry.account_id, + ), }, { cache }, ) @@ -1165,11 +1222,13 @@ export class UsageLogsView { const pgRequestIds = new Set(pgLogs.map((r) => r.requestId).filter(Boolean)) const liveRows = [] const seenLive = new Set() - for (const entry of filteredLive) { - const reqId = String(entry.request_id || '') + for (const item of filteredLive) { + const entry = item?.entry ?? item + const normalizedRow = item?.row ?? null + const reqId = String(entry?.request_id || '') if (!reqId || pgRequestIds.has(reqId) || seenLive.has(reqId)) continue seenLive.add(reqId) - liveRows.push(liveEntryToUsageLogRow(entry, names, now)) + liveRows.push(liveEntryToUsageLogRow(entry, names, now, normalizedRow)) } if (!liveRows.length) { diff --git a/test/unit/api-endpoints.test.mjs b/test/unit/api-endpoints.test.mjs index f4bf276bd5..849455762f 100644 --- a/test/unit/api-endpoints.test.mjs +++ b/test/unit/api-endpoints.test.mjs @@ -142,3 +142,37 @@ test('sk-kin category defaults oauth and can switch to api', () => { assert.equal(updated.category, 'api') assert.equal(keys.list()[0].category, 'api') }) + +test('ApiEndpointsRepo.listHydrated executes constant 3 flat queries instead of 1+2N', () => { + const dataDir = tmpDir() + const store = new ApiEndpointStore({ dataDir }) + try { + for (let i = 0; i < 4; i += 1) { + store.create({ + name: `ep-${i}`, + base_url: `https://api-${i}.example.com`, + api_key_entries: [{ api_key: `sk-test-endpoint-${i}` }], + models: [{ name: `m-${i}-a` }, { name: `m-${i}-b` }], + }) + } + const repo = store.repo + let calls = 0 + for (const stmt of [repo._listEp, repo._listAllKeys, repo._listAllModels, repo._listKeys, repo._listModels]) { + const orig = stmt.all.bind(stmt) + stmt.all = (...args) => { + calls += 1 + return orig(...args) + } + } + const items = repo.listHydrated() + assert.equal(items.length, 4) + assert.equal(calls, 3, 'listHydrated must run exactly 3 flat queries regardless of endpoint count') + for (const item of items) { + assert.equal(item.api_key_entries.length, 1) + assert.equal(item.models.length, 2) + } + } finally { + store.db.close() + fs.rmSync(dataDir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/panel-2fa.test.mjs b/test/unit/panel-2fa.test.mjs index 6ce3d73ad2..e42b7ce789 100644 --- a/test/unit/panel-2fa.test.mjs +++ b/test/unit/panel-2fa.test.mjs @@ -236,11 +236,28 @@ test('state is keyed case-insensitively, like the users table', () => { assert.equal(isTwoFactorEnabled('Admin'), false) }) -test('the batch lookup matches the single-account one', () => { +test('the batch lookup matches the single-account one in a single settings query', () => { enroll('alice') - const map = twoFactorEnabledFor(['alice', 'bob']) + enroll('carol') + const db = getDb() + const origPrepare = db.prepare.bind(db) + const queries = [] + db.prepare = (sql) => { + queries.push(String(sql)) + return origPrepare(sql) + } + let map + try { + map = twoFactorEnabledFor(['alice', 'bob', 'CAROL', '']) + } finally { + db.prepare = origPrepare + } + assert.equal(queries.length, 1, 'twoFactorEnabledFor must issue a single prefix query') + assert.match(queries[0], /LIKE 'panel_2fa:%'/) assert.equal(map.get('alice'), true) assert.equal(map.get('bob'), false) + assert.equal(map.get('CAROL'), true) + assert.equal(map.get(''), false) assert.equal(map.get('alice'), isTwoFactorEnabled('alice')) }) diff --git a/test/unit/panel-kernels.test.mjs b/test/unit/panel-kernels.test.mjs index b0ac8ba0eb..3b5331189b 100644 --- a/test/unit/panel-kernels.test.mjs +++ b/test/unit/panel-kernels.test.mjs @@ -435,36 +435,10 @@ test('pull route follows the release pin only when the caller asks for it', asyn } }) -test('cached route lists every cached release and select switches back without downloading', async (t) => { +test('removed dead kernel cache routes (/cached and /select) return 404', async (t) => { const { root } = fixture(t) - let downloads = 0 - const fetchImpl = releaseFetch() - const options = { - ctx: { - fetchImpl: async (url) => { - if (String(url).includes('/releases/assets/')) downloads++ - return fetchImpl(url) - }, - }, - } - assert.equal((await route(root, 'POST', '/pull', { kernel: 'cli-node' }, options)).status, 200) - assert.equal((await route(root, 'POST', '/pull', { kernel: 'cli-node', tag: 'v1.2.1' }, options)).status, 200) - const cached = await route(root, 'GET', '/cached?kernel=cli-node', null, options) - assert.equal(cached.status, 200, JSON.stringify(cached.body)) - assert.deepEqual( - cached.body.data.releases.map((row) => [row.tag, row.current]), - [ - ['v1.2.1', true], - ['v1.2.3', false], - ], - ) - const before = downloads - const selected = await route(root, 'POST', '/select', { kernel: 'cli-node', tag: 'v1.2.3' }, options) - assert.equal(selected.status, 200, JSON.stringify(selected.body)) - assert.equal(downloads, before) - const inventory = await route(root, 'GET', '') - assert.equal(inventory.body.data.kernels[0].release_tag, 'v1.2.3') - const missing = await route(root, 'POST', '/select', { kernel: 'cli-node', tag: 'v9.9.9' }, options) - assert.equal(missing.status, 404) - assert.equal(missing.body.error.code, 'kernel_release_not_cached') + const cached = await route(root, 'GET', '/cached?kernel=cli-node') + assert.equal(cached.status, 404) + const selected = await route(root, 'POST', '/select', { kernel: 'cli-node', tag: 'v1.2.3' }) + assert.equal(selected.status, 404) }) diff --git a/test/unit/panel-redis-opt.test.mjs b/test/unit/panel-redis-opt.test.mjs index 59a4fe934b..47b0b16369 100644 --- a/test/unit/panel-redis-opt.test.mjs +++ b/test/unit/panel-redis-opt.test.mjs @@ -17,6 +17,7 @@ import { closeDatabase, createDatabase, openDatabase } from '../../src/lib/db/da import { snapshotDatabaseMetricsAsync } from '../../src/lib/db/database-metrics.mjs' import { resetWatermarkBefore, runDashboardAggregation } from '../../src/lib/db/pg/dashboard-aggregator.mjs' import { AccountRuntimeRepo } from '../../src/lib/db/repos/account-runtime-repo.mjs' +import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { StatisticsRepo } from '../../src/lib/db/repos/statistics-repo.mjs' import { UsageLogsRepo } from '../../src/lib/db/repos/usage-logs-repo.mjs' import { UsersRepo } from '../../src/lib/db/repos/users-repo.mjs' @@ -189,10 +190,14 @@ test('StatisticsRepo PG pre-agg: reads usage_dashboard_* + parameterized tail wi output_tokens: 500, cache_read_tokens: 200, cache_creation_tokens: 100, + cache_creation_5m_tokens: 70, + cache_creation_1h_tokens: 30, total_cost: 5.5, actual_cost: 6.0, total_duration_ms: 10000, duration_count: 100, + total_ttft_ms: 4000, + ttft_count: 80, }, ] } @@ -217,8 +222,14 @@ test('StatisticsRepo PG pre-agg: reads usage_dashboard_* + parameterized tail wi output_tokens: 50, cache_read_tokens: 20, cache_creation_tokens: 10, + cache_creation_5m_tokens: 6, + cache_creation_1h_tokens: 4, cost: 0.5, actual_cost: 0.6, + total_duration_ms: 2000, + duration_count: 10, + total_ttft_ms: 800, + ttft_count: 10, }, ] } @@ -231,10 +242,14 @@ test('StatisticsRepo PG pre-agg: reads usage_dashboard_* + parameterized tail wi output_tokens: 100, cache_read_tokens: 40, cache_creation_tokens: 20, + cache_creation_5m_tokens: 15, + cache_creation_1h_tokens: 5, total_cost: 1.0, actual_cost: 1.2, total_duration_ms: 2000, duration_count: 20, + total_ttft_ms: 1000, + ttft_count: 20, }, ] } @@ -310,6 +325,9 @@ test('StatisticsRepo PG pre-agg: reads usage_dashboard_* + parameterized tail wi assert.equal(stat.totals.errors, 3) assert.equal(stat.totals.cost, 6.75) assert.equal(stat.totals.actualCost, 7.5) + assert.equal(stat.totals.cacheCreation5mTokens, 85) + assert.equal(stat.totals.cacheCreation1hTokens, 35) + assert.equal(stat.totals.avgTtftMs, 50) assert.equal(stat.series.length, 1) assert.equal(stat.series[0].id, 'claude-sonnet-4-5') assert.equal(stat.seriesTotals.s0.requests, 11) @@ -332,6 +350,10 @@ test('StatisticsRepo PG pre-agg: reads usage_dashboard_* + parameterized tail wi assert.equal(lb.entries[0].id, 'claude-sonnet-4-5') assert.equal(lb.entries[0].totalRequests, 15) assert.equal(lb.entries[0].totalCost, 0.75) + assert.equal(lb.entries[0].cacheCreation5mTokens, 6) + assert.equal(lb.entries[0].cacheCreation1hTokens, 4) + assert.equal(lb.entries[0].avgDurationMs, 167) + assert.equal(lb.entries[0].avgTtftMs, 80) executed.length = 0 const activeUsers = repo.activeUsersCount({ @@ -1274,3 +1296,219 @@ test('dashboard-aggregator incremental pass pushes UTC .000Z floor without affec assert.deepEqual(rw2, { reset: true, watermark: '' }) assert.match(executed[0].sql, /SET last_aggregated_at = ''/) }) + +test('SettingsRepo caches primary DB reads via EntityCache, invalidates on set/remove, and isolates non-primary DBs', () => { + const dirMain = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-settings-main-')) + const dirIso = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-settings-iso-')) + openDatabase({ dataDir: dirMain }) + const isoDb = createDatabase({ dbPath: path.join(dirIso, 'iso.db') }) + try { + const mainRepo = new SettingsRepo() + const isoRepo = new SettingsRepo(isoDb) + mainRepo.set('panel_theme', { mode: 'dark' }) + isoRepo.set('panel_theme', { mode: 'light' }) + + let mainSelects = 0 + const origGet = mainRepo._get.get.bind(mainRepo._get) + mainRepo._get.get = (...args) => { + mainSelects += 1 + return origGet(...args) + } + + const first = mainRepo.get('panel_theme') + assert.deepEqual(first, { mode: 'dark' }) + first.mode = 'mutated-by-caller' + // Second read hits EntityCache L1 (0 DB calls) and returns an unmutated clone + assert.deepEqual(mainRepo.get('panel_theme'), { mode: 'dark' }) + assert.equal(mainSelects, 1) + + // Isolated DB must never read the primary DB's global EntityCache entry + assert.deepEqual(isoRepo.get('panel_theme'), { mode: 'light' }) + + // set() invalidates L1 immediately + mainRepo.set('panel_theme', { mode: 'system' }) + assert.deepEqual(mainRepo.get('panel_theme'), { mode: 'system' }) + assert.equal(mainSelects, 2) + + // remove() invalidates L1 immediately and respects per-call fallback + mainRepo.remove('panel_theme') + assert.deepEqual(mainRepo.get('panel_theme', { mode: 'fallback-a' }), { mode: 'fallback-a' }) + assert.deepEqual(mainRepo.get('panel_theme', { mode: 'fallback-b' }), { mode: 'fallback-b' }) + } finally { + isoDb.close() + closeDatabase() + fs.rmSync(dirMain, { recursive: true, force: true }) + fs.rmSync(dirIso, { recursive: true, force: true }) + } +}) + +test('panel-routes invalidation matrix clears stats on VM/key/gemini writes, ignores non-ID VM segments, and shares dashboard/usage cache across roles', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-panel-inv-')) + fs.mkdirSync(path.join(dir, 'vms'), { recursive: true }) + openDatabase({ dataDir: path.join(dir, 'data') }) + const cache = getCacheRuntime() + const invalidatedNs = [] + const clearedVmOwnerIds = [] + let clearedAllVmOwners = 0 + const origInvNs = cache.dashboard.invalidateNamespaces.bind(cache.dashboard) + const origInvVm = cache.entity.invalidateVmOwner.bind(cache.entity) + const origInvVms = cache.entity.invalidateVmOwners.bind(cache.entity) + cache.dashboard.invalidateNamespaces = async (ns) => { + invalidatedNs.push([...ns]) + return origInvNs(ns) + } + cache.entity.invalidateVmOwner = async (id) => { + clearedVmOwnerIds.push(id) + return origInvVm(id) + } + cache.entity.invalidateVmOwners = async () => { + clearedAllVmOwners += 1 + return origInvVms() + } + + let dashboardBuilds = 0 + let usageBuilds = 0 + const origBuildDashboard = panel.buildDashboard + const origBuildUsageAsync = panel.buildUsageAsync + try { + const keyStore = new ApiKeyStore({ dataDir: path.join(dir, 'data') }) + const handle = createPanelHandler({ + cfg: { paths: { project: dir }, limits: { max_body_bytes: 1024 * 1024 } }, + requireAuth(req) { + req.panelRole = req._testAuth?.role || 'admin' + req.panelUser = req.panelRole === 'super' ? 'superop' : 'admin' + req.panelUserId = req._testAuth?.userId || 'u-admin' + if (req.panelRole === 'admin') req.apiKeyKind = 'master' + return true + }, + readBody: async (req) => readBody(req, 64 * 1024).catch(() => ({})), + json(res, status, body) { + res.statusCode = status + res.body = body + return true + }, + geminiPanel: async (_req, res) => { + res.statusCode = 200 + res.body = { ok: true } + return true + }, + apiKeyStore: keyStore, + accountQuota: { snapshot: () => ({ accounts: [] }) }, + stickyRouter: { stats: () => ({}) }, + routingConfig: {}, + stats: { snapshot: () => ({}) }, + requestLog: { + repo: { db: null, invalidateBillingCache() {} }, + snapshot: () => ({}), + }, + proxyPool: { list: () => [] }, + }) + + // 1. Non-ID VM segment (`reconcile-fingerprints`) must clear all VM owners and include 'stats' + const resNonId = makeRes() + await handle( + makeReq('POST', '/api/panel/vms/reconcile-fingerprints'), + resNonId, + new URL('http://localhost/api/panel/vms/reconcile-fingerprints'), + ) + assert.equal(resNonId.statusCode, 200) + assert.ok( + invalidatedNs.some((ns) => ns.includes('stats')), + 'VM mutation must invalidate stats', + ) + assert.equal( + clearedVmOwnerIds.includes('reconcile-fingerprints'), + false, + 'non-ID segment must not be passed to invalidateVmOwner', + ) + assert.ok(clearedAllVmOwners >= 1, 'non-ID VM mutation must clear all VM owners') + + // 2. Gemini mutation branch must invalidate stats, overview, filter-options, and all VM owners + invalidatedNs.length = 0 + clearedAllVmOwners = 0 + const resGemini = makeRes() + await handle( + makeReq('PATCH', '/api/panel/gemini/config', { body: { telemetry_enabled: false } }), + resGemini, + new URL('http://localhost/api/panel/gemini/config'), + ) + assert.equal(resGemini.statusCode, 200) + assert.ok( + invalidatedNs.some((ns) => ns.includes('stats') && ns.includes('overview') && ns.includes('filter-options')), + 'gemini mutation must invalidate stats, overview, and filter-options', + ) + assert.ok(clearedAllVmOwners >= 1, 'gemini mutation must clear VM owner cache') + + // 3. API Key mutation must invalidate stats + invalidatedNs.length = 0 + const resKeyCreate = makeRes() + await handle( + makeReq('POST', '/api/panel/api-keys', { body: { name: 'test-k' } }), + resKeyCreate, + new URL('http://localhost/api/panel/api-keys'), + ) + assert.equal(resKeyCreate.statusCode, 201) + assert.ok( + invalidatedNs.some((ns) => ns.includes('stats')), + 'API key mutation must invalidate stats', + ) + + // 4. Dashboard & Usage SWR keys omit `role` so admin and super share the same cached snapshot + const keySpy = [] + const origSWR = cache.dashboard.getOrSetSWR.bind(cache.dashboard) + cache.dashboard.getOrSetSWR = async (ns, keyObj, loader, opts) => { + keySpy.push({ ns, keyObj }) + if (keyObj?.ep === 'dashboard') { + dashboardBuilds += 1 + return { ok: true, data: { summary: {} } } + } + if (keyObj?.ep === 'usage') { + usageBuilds += 1 + return { ok: true, data: { totals: {} } } + } + return origSWR(ns, keyObj, loader, opts) + } + try { + await handle( + makeReq('GET', '/api/panel/dashboard', { auth: { role: 'admin' } }), + makeRes(), + new URL('http://localhost/api/panel/dashboard'), + ) + await handle( + makeReq('GET', '/api/panel/dashboard', { auth: { role: 'super' } }), + makeRes(), + new URL('http://localhost/api/panel/dashboard'), + ) + await handle( + makeReq('GET', '/api/panel/usage', { auth: { role: 'admin' } }), + makeRes(), + new URL('http://localhost/api/panel/usage'), + ) + await handle( + makeReq('GET', '/api/panel/usage', { auth: { role: 'super' } }), + makeRes(), + new URL('http://localhost/api/panel/usage'), + ) + const dashKeys = keySpy.filter((e) => e.keyObj?.ep === 'dashboard') + const usageKeys = keySpy.filter((e) => e.keyObj?.ep === 'usage') + assert.equal(dashKeys.length, 2) + assert.equal(usageKeys.length, 2) + assert.equal('role' in dashKeys[0].keyObj, false, 'dashboard cache key must omit role') + assert.equal('role' in usageKeys[0].keyObj, false, 'usage cache key must omit role') + assert.deepEqual(dashKeys[0].keyObj, dashKeys[1].keyObj) + assert.deepEqual(usageKeys[0].keyObj, usageKeys[1].keyObj) + assert.equal(dashboardBuilds, 2) + assert.equal(usageBuilds, 2) + } finally { + cache.dashboard.getOrSetSWR = origSWR + } + } finally { + void origBuildDashboard + void origBuildUsageAsync + cache.dashboard.invalidateNamespaces = origInvNs + cache.entity.invalidateVmOwner = origInvVm + cache.entity.invalidateVmOwners = origInvVms + closeDatabase() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/panel-vm-deactivate.test.mjs b/test/unit/panel-vm-deactivate.test.mjs index 3765170e2e..3e7db85a00 100644 --- a/test/unit/panel-vm-deactivate.test.mjs +++ b/test/unit/panel-vm-deactivate.test.mjs @@ -104,3 +104,156 @@ for (const role of ['user', 'super']) { assert.equal(getActiveVmId(project), 'vm-01') }) } + +test('POST /api/panel/vms/:id/stop re-reads vm.json after await stopSlot so concurrent hot-path fields survive', async () => { + const vmPath = path.join(project, 'vms', 'vm-01.json') + let stopResponse = {} + const stopHandle = createPanelHandler({ + cfg, + routingConfig: {}, + requireAuth(req) { + req.panelRole = 'admin' + req.apiKeyKind = 'master' + return true + }, + json(_res, status, body) { + stopResponse = { status, body } + return true + }, + accountQuota: { ensure() {} }, + kernelPolicyOps: { + stopSlot: async () => { + // Simulate hot-path cooldown & credential refresh metadata written during stopSlot await + const onDisk = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + onDisk.cooldown_until = '2099-01-01T00:00:00.000Z' + onDisk.claude = { ...(onDisk.claude || {}), refreshed_at: '2026-12-01T12:00:00.000Z' } + fs.writeFileSync(vmPath, JSON.stringify(onDisk)) + return { ok: true, mode: 'test-stop' } + }, + }, + }) + await stopHandle({ method: 'POST', role: 'admin' }, {}, new URL('http://localhost/api/panel/vms/vm-01/stop')) + assert.equal(stopResponse.status, 200) + const saved = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(saved.status, 'stopped') + assert.equal(saved.cooldown_until, '2099-01-01T00:00:00.000Z', 'hot-path cooldown field must not be clobbered') + assert.equal( + saved.claude?.refreshed_at, + '2026-12-01T12:00:00.000Z', + 'hot-path credential refresh metadata must not be clobbered', + ) +}) + +test('GET /api/panel/billing validates since/until and GET /api/panel/request-logs/:id/attempts uses belongsToOwner without getDebug', async () => { + let getDebugCalls = 0 + let belongsCalls = 0 + let resState = {} + const h = createPanelHandler({ + cfg, + routingConfig: {}, + requireAuth(req) { + req.panelRole = req.role || 'admin' + req.panelUser = req.role === 'user' ? 'alice' : 'admin' + req.panelUserId = req.userId || 'u-1' + if (req.panelRole === 'admin') req.apiKeyKind = 'master' + return true + }, + json(_res, status, body) { + resState = { status, body } + return true + }, + accountQuota: { ensure() {} }, + requestLog: { + getDebug() { + getDebugCalls += 1 + throw new Error('attempts route must not call getDebug when repo.belongsToOwner exists') + }, + repo: { + belongsToOwner(reqId, owner) { + belongsCalls += 1 + return reqId === 'req-owned' && owner === 'u-1' + }, + }, + }, + attemptsRepo: { + list(id) { + return [{ request_id: id, attempt_no: 1 }] + }, + }, + }) + + // Invalid since/until must return 400 invalid_range + await h( + { method: 'GET', url: '/api/panel/billing?since=invalid', role: 'admin' }, + {}, + new URL('http://localhost/api/panel/billing?since=invalid'), + ) + assert.equal(resState.status, 400) + assert.equal(resState.body?.error?.code, 'invalid_range') + + await h( + { method: 'GET', url: '/api/panel/billing?until=not-a-date', role: 'admin' }, + {}, + new URL('http://localhost/api/panel/billing?until=not-a-date'), + ) + assert.equal(resState.status, 400) + assert.equal(resState.body?.error?.code, 'invalid_range') + + // Tenant attempts route must use belongsToOwner without parsing full debug JSON + await h( + { method: 'GET', url: '/api/panel/request-logs/req-owned/attempts', role: 'user', userId: 'u-1' }, + {}, + new URL('http://localhost/api/panel/request-logs/req-owned/attempts'), + ) + assert.equal(resState.status, 200) + assert.equal(resState.body?.data?.attempts?.length, 1) + + await h( + { method: 'GET', url: '/api/panel/request-logs/req-other/attempts', role: 'user', userId: 'u-1' }, + {}, + new URL('http://localhost/api/panel/request-logs/req-other/attempts'), + ) + assert.equal(resState.status, 404) + assert.equal(belongsCalls, 2) + assert.equal(getDebugCalls, 0) +}) + +test('GET /api/panel/vms updates total to filteredItems.length when filtering by owner_user_id', async () => { + fs.writeFileSync( + path.join(project, 'vms', 'vm-01.json'), + JSON.stringify({ id: 'vm-01', name: 'vm-01', status: 'running', owner_user_id: 'u-owner-1' }), + ) + fs.writeFileSync( + path.join(project, 'vms', 'vm-02.json'), + JSON.stringify({ id: 'vm-02', name: 'vm-02', status: 'running', owner_user_id: 'u-owner-2' }), + ) + let resState = {} + const h = createPanelHandler({ + cfg, + routingConfig: {}, + requireAuth(req) { + req.panelRole = 'admin' + req.apiKeyKind = 'master' + return true + }, + json(_res, status, body) { + resState = { status, body } + return true + }, + accountQuota: { ensure() {}, snapshot: () => ({ accounts: [] }) }, + requestLog: { + repo: { db: null }, + billingStatsAsync: async () => ({ accounts: [], totals: {} }), + }, + proxyPool: { list: () => [] }, + }) + await h( + { method: 'GET', url: '/api/panel/vms?owner_user_id=u-owner-1&refresh=1', headers: {} }, + { setHeader() {}, getHeader() {} }, + new URL('http://localhost/api/panel/vms?owner_user_id=u-owner-1&refresh=1'), + ) + assert.equal(resState.status, 200) + assert.equal(resState.body?.data?.items?.length, 1) + assert.equal(resState.body?.data?.total, 1, 'filtered VM list must update total to filteredItems.length') + assert.equal(resState.body?.data?.items?.[0]?.id, 'vm-01') +}) diff --git a/test/unit/pg-repos-parity.test.mjs b/test/unit/pg-repos-parity.test.mjs index 328861d434..474bf21c8f 100644 --- a/test/unit/pg-repos-parity.test.mjs +++ b/test/unit/pg-repos-parity.test.mjs @@ -30,6 +30,7 @@ import { createPgPool } from '../../src/lib/db/pg/pg-pool.mjs' import { resolvePgConfig } from '../../src/lib/db/pg/config.mjs' import { applyPgMigrations } from '../../src/lib/db/pg/migrations-runner.mjs' import { createPgSyncDb } from '../../src/lib/db/pg/pg-sync-db.mjs' +import { runDashboardAggregation } from '../../src/lib/db/pg/dashboard-aggregator.mjs' import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { UsersRepo } from '../../src/lib/db/repos/users-repo.mjs' @@ -1210,6 +1211,155 @@ test('Tier 2B: retargetVmId (6 tables), crag-shop orders, and PG BackupService o retargetVmId('vm-codex-parity', 'vm-codex-parity-renamed') assert.equal(codexRepo.get('vm-codex-parity'), null) assert.equal(codexRepo.get('vm-codex-parity-renamed')?.plan_type, 'pro') + + // 5. Verify 016 pre-agg columns + actual_cost IS NULL parity + repriceRangeAsync immediate stats refresh + // + windowStats ORDER BY minute ASC + UsageLogsView UNION ALL account_id/model parity against SQLite + const sqliteDir = path.join(tmpDir, 'sqlite-stats-parity') + fs.mkdirSync(sqliteDir, { recursive: true }) + const sqliteDb = (await import('../../src/lib/db/database.mjs')).createDatabase({ + dbPath: path.join(sqliteDir, 'parity.db'), + }) + try { + const pgUsageRepo = new UsageLogsRepo(db) + const sqUsageRepo = new UsageLogsRepo(sqliteDb) + const parityNow = Date.parse('2026-06-15T12:30:00.000Z') + const fixtures = [ + // Sealed prior day (hits usage_dashboard_daily + usage_dashboard_hourly_models) with actual_cost IS NULL + { + id: 'p-stat-1', + request_id: 'req-p-stat-1', + created_at: '2026-06-14T10:15:00.000Z', + model: 'claude-sonnet-4-5', + upstream_model: 'claude-sonnet-4-5', + requested_model: 'sonnet-alias', + account_id: 'acc-p1', + final_account_id: 'acc-p1', + status: 200, + input_tokens: 1000, + output_tokens: 500, + cache_read_tokens: 200, + cache_creation_tokens: 100, + cache_creation_5m_tokens: 60, + cache_creation_1h_tokens: 40, + duration_ms: 1200, + first_token_ms: 300, + total_cost: 0.1, + actual_cost: null, + pricing_model: 'stale-price', + }, + // Sealed same-day hour (hits usage_dashboard_hourly + usage_dashboard_hourly_models) + { + id: 'p-stat-2', + request_id: 'req-p-stat-2', + created_at: '2026-06-15T09:20:00.000Z', + model: 'claude-sonnet-4-5', + upstream_model: 'claude-sonnet-4-5', + requested_model: 'claude-sonnet-4-5', + account_id: 'acc-p2', + final_account_id: 'acc-p1', + status: 200, + input_tokens: 2000, + output_tokens: 1000, + cache_read_tokens: 400, + cache_creation_tokens: 200, + cache_creation_5m_tokens: 150, + cache_creation_1h_tokens: 50, + duration_ms: 1800, + first_token_ms: 500, + total_cost: 0.2, + actual_cost: 0.4, + pricing_model: 'stale-price', + }, + // Unsealed tail after watermark (hits usage_logs tail) + { + id: 'p-stat-3', + request_id: 'req-p-stat-3', + created_at: '2026-06-15T12:10:00.000Z', + model: 'claude-sonnet-4-5', + upstream_model: 'claude-sonnet-4-5', + requested_model: 'claude-sonnet-4-5', + account_id: null, + final_account_id: 'acc-p1', + status: 200, + input_tokens: 500, + output_tokens: 250, + cache_read_tokens: 100, + cache_creation_tokens: 50, + cache_creation_5m_tokens: 30, + cache_creation_1h_tokens: 20, + duration_ms: 900, + first_token_ms: 200, + total_cost: 0.05, + actual_cost: 0.1, + pricing_model: 'stale-price', + }, + ] + for (const rowFixture of fixtures) { + pgUsageRepo.insertSummary(rowFixture) + sqUsageRepo.insertSummary(rowFixture) + } + // Run real PG dashboard aggregation so sealed buckets are populated in 016 columns + await runDashboardAggregation(pgPool, { fullBackfill: true }) + // Move watermark to 2026-06-15T11:30:00.000Z so 14th (daily) + 09:00 (hourly) use pre-agg and 12:10 uses tail + await pgPool.query(`UPDATE usage_dashboard_aggregation_watermark SET last_aggregated_at = $1 WHERE id = 1`, [ + '2026-06-15T11:30:00.000Z', + ]) + + const pgStatsRepo = new StatisticsRepo(db) + const sqStatsRepo = new StatisticsRepo(sqliteDb) + const pgStat = pgStatsRepo.statistics({ range: '7days', dimension: 'model', tz: 'UTC', now: parityNow }) + const sqStat = sqStatsRepo.statistics({ range: '7days', dimension: 'model', tz: 'UTC', now: parityNow }) + assert.deepEqual(pgStat.totals, sqStat.totals, 'PG pre-agg+tail totals must match SQLite with 0 error') + + const pgLb = pgStatsRepo.leaderboard({ range: '7days', scope: 'model', tz: 'UTC', now: parityNow }) + const sqLb = sqStatsRepo.leaderboard({ range: '7days', scope: 'model', tz: 'UTC', now: parityNow }) + assert.deepEqual(pgLb.entries, sqLb.entries, 'PG pre-agg+tail model leaderboard must match SQLite with 0 error') + + // Reprice sealed historical range via repriceRangeAsync and verify stats reflect new prices immediately + const repriceRes = await pgUsageRepo.repriceRangeAsync({ + since: '2026-06-14T00:00:00.000Z', + until: '2026-06-15T23:59:59.000Z', + awaitAggregation: true, + }) + sqUsageRepo.repriceRange({ + since: '2026-06-14T00:00:00.000Z', + until: '2026-06-15T23:59:59.000Z', + }) + assert.equal(repriceRes.changed, 3) + const pgAfterReprice = pgStatsRepo.statistics({ range: '7days', dimension: 'model', tz: 'UTC', now: parityNow }) + const sqAfterReprice = sqStatsRepo.statistics({ range: '7days', dimension: 'model', tz: 'UTC', now: parityNow }) + assert.ok( + Math.abs(pgAfterReprice.totals.cost - sqAfterReprice.totals.cost) < 1e-9, + `expected PG post-reprice cost ${pgAfterReprice.totals.cost} === SQLite ${sqAfterReprice.totals.cost}`, + ) + assert.notEqual(pgAfterReprice.totals.cost, pgStat.totals.cost, 'repriceRangeAsync must update statistics cost') + + // UsageLogsView UNION ALL account_id & model parity on real PG18 vs SQLite + const pgView = new UsageLogsView(db) + const sqView = new UsageLogsView(sqliteDb) + assert.deepEqual( + pgView.listBatch({ account_id: 'acc-p1', limit: 10 }).logs.map((r) => r.id), + sqView.listBatch({ account_id: 'acc-p1', limit: 10 }).logs.map((r) => r.id), + ) + assert.deepEqual( + pgView.listBatch({ model: 'sonnet-alias', limit: 10 }).logs.map((r) => r.id), + sqView.listBatch({ model: 'sonnet-alias', limit: 10 }).logs.map((r) => r.id), + ) + + // windowStats ORDER BY minute ASC parity on real PG18 + const pgWin = pgUsageRepo.windowStats({ + since: '2026-06-14T00:00:00.000Z', + until: '2026-06-15T23:59:59.000Z', + }) + const sqWin = sqUsageRepo.windowStats({ + since: '2026-06-14T00:00:00.000Z', + until: '2026-06-15T23:59:59.000Z', + }) + assert.equal(pgWin.qps.current, sqWin.qps.current) + assert.equal(pgWin.tps.current, sqWin.tps.current) + } finally { + sqliteDb.close() + } } finally { await closeDatabaseAsync().catch(() => {}) await adminPool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`).catch(() => {}) diff --git a/test/unit/settings-routing-audit.test.mjs b/test/unit/settings-routing-audit.test.mjs index dfc98a400b..3e9068bb85 100644 --- a/test/unit/settings-routing-audit.test.mjs +++ b/test/unit/settings-routing-audit.test.mjs @@ -386,3 +386,111 @@ test('P2-13: PUT /api/panel/routing rejects out-of-range logging bounds and debu assert.equal(res.body?.error?.code, 'invalid_logging_config', JSON.stringify(logging)) } }) + +test('P4: PUT /admin/routing shares validation and rollback behavior with PUT /api/panel/routing', async () => { + let restored = 0 + let persistCalls = 0 + const routingConfig = { + concurrency: {}, + tiers: {}, + redaction: { enabled: false, secrets: true, personal: true, words: [], rules: [] }, + } + const makeAdminInvoke = (persistImpl) => async (method, body) => { + const response = {} + const handlePanel = createPanelHandler({ + cfg: { paths: { project: os.tmpdir() }, limits: { max_body_bytes: 32 * 1024 * 1024 } }, + routingConfig, + stickyRouter: { stats: () => ({}), reloadConfig() {} }, + accountQuota: { reloadConfig() {}, applyTierConcurrency() {}, applyTierRpm() {} }, + requestLog: { setConfig() {} }, + persistRoutingPatch: persistImpl, + restoreRoutingRuntime: async () => { + restored += 1 + }, + requireAuth(req) { + req.apiKeyKind = 'master' + req.panelRole = 'admin' + return true + }, + readBody: async () => body, + json(_res, status, payload) { + response.status = status + response.body = payload + return true + }, + }) + await handlePanel({ method }, {}, new URL('http://localhost/admin/routing')) + return response + } + + // Invalid redaction policy must be rejected with 400 before calling persistRoutingPatch + const invokeReject = makeAdminInvoke(async () => { + persistCalls += 1 + return { concurrency: {}, rpm: {} } + }) + const badRedaction = await invokeReject('PUT', { + redaction: { enabled: true, secrets: false, personal: false, words: [], rules: [] }, + }) + assert.equal(badRedaction.status, 400) + assert.equal(badRedaction.body?.error?.code, 'invalid_redaction_config') + assert.equal(persistCalls, 0) + + // Invalid VM config patch must also be rejected with 400 on /admin/routing + const badVm = await invokeReject('PUT', { vm: { default_kernel: 'invalid-kernel' } }) + assert.equal(badVm.status, 400) + assert.equal(badVm.body?.error?.code, 'invalid_vm_config') + assert.equal(persistCalls, 0) + + // Persist failure throwing status=400 must return 400 (not 500) and restore prior routing runtime + let reloaded = 0 + const invokeFail = async (method, body) => { + const response = {} + const ctx = { + cfg: { paths: { project: os.tmpdir() }, limits: { max_body_bytes: 32 * 1024 * 1024 } }, + routingConfig: { + concurrency: { max: 3 }, + tiers: {}, + redaction: { enabled: false, secrets: true, personal: true, words: [], rules: [] }, + }, + stickyRouter: { + stats: () => ({}), + reloadConfig() { + reloaded += 1 + }, + }, + accountQuota: { reloadConfig() {}, applyTierConcurrency() {}, applyTierRpm() {} }, + requestLog: { setConfig() {} }, + persistRoutingPatch: async () => { + ctx.routingConfig.concurrency.max = 99 + const err = new Error('invalid_redaction_regex') + err.status = 400 + err.code = 'invalid_redaction_config' + throw err + }, + requireAuth(req) { + req.apiKeyKind = 'master' + req.panelRole = 'admin' + return true + }, + readBody: async () => body, + json(_res, status, payload) { + response.status = status + response.body = payload + return true + }, + } + const handlePanel = createPanelHandler(ctx) + await handlePanel({ method }, {}, new URL('http://localhost/admin/routing')) + return { response, ctx } + } + const { response: failed, ctx: failCtx } = await invokeFail('POST', { concurrency: { max: 99 } }) + assert.equal(failed.status, 400) + assert.equal(failed.body?.error?.code, 'invalid_redaction_config') + assert.equal( + failCtx.routingConfig.concurrency.max, + 3, + 'failed /admin/routing persist must restore prior routingConfig', + ) + assert.ok(reloaded >= 1, 'failed /admin/routing persist must trigger restoreRoutingRuntime reload') + void restored +}) diff --git a/test/unit/usage-logs-repo.test.mjs b/test/unit/usage-logs-repo.test.mjs index c5780bc65f..46a3ea698e 100644 --- a/test/unit/usage-logs-repo.test.mjs +++ b/test/unit/usage-logs-repo.test.mjs @@ -660,3 +660,208 @@ test('aligned windows keep boundary, sign, unpriced and Fable rules per row', () fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('ownerBilling runs a single grouped query and computes totals from items', () => { + const { dir, db, repo } = freshDb() + try { + seed(repo, [ + { + vm_id: 'vm-a', + api_key_id: 'k1', + status: 200, + input_tokens: 10, + output_tokens: 5, + total_cost: 1, + actual_cost: 2, + }, + { + vm_id: 'vm-a', + api_key_id: 'k1', + status: 500, + error_code: 'upstream_error', + input_tokens: 4, + output_tokens: 1, + total_cost: 0.5, + actual_cost: 1, + }, + { + vm_id: null, + api_key_id: 'k2', + status: 200, + input_tokens: 20, + output_tokens: 8, + total_cost: 3, + actual_cost: null, + }, + ]) + const sqls = [] + const origPrepare = db.prepare.bind(db) + db.prepare = (sql) => { + sqls.push(String(sql)) + return origPrepare(sql) + } + let billed + try { + billed = repo.ownerBilling({ groupBy: 'vm' }) + } finally { + db.prepare = origPrepare + } + assert.equal(sqls.length, 1, 'ownerBilling must execute a single grouped query without a duplicate totalsSql scan') + assert.equal(billed.items.length, 2) + assert.equal(billed.totals.requests, 3) + assert.equal(billed.totals.ok, 2) + assert.equal(billed.totals.fail, 1) + assert.equal(billed.totals.tokens_in, 34) + assert.equal(billed.totals.tokens_out, 14) + assert.equal(billed.totals.cost_usd, 6) + assert.equal(billed.totals.official_cost_usd, 4.5) + } finally { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test('_pruneUsage archives and deletes old rows in bounded batches without losing lifetime totals', () => { + const { dir, db, repo } = freshDb() + try { + const oldStart = Date.parse('2026-01-01T00:00:00.000Z') + db.exec('BEGIN') + for (let i = 0; i < 12; i += 1) { + repo.insertSummary({ + id: `old_${String(i).padStart(3, '0')}`, + request_id: `req-old-${i}`, + created_at: new Date(oldStart + i * 1000).toISOString(), + account_id: 'acc-archive', + status: 200, + input_tokens: 10, + output_tokens: 5, + total_cost: 0.25, + }) + } + repo.insertSummary({ + id: 'new_001', + request_id: 'req-new-1', + created_at: '2026-06-01T00:00:00.000Z', + account_id: 'acc-archive', + status: 200, + input_tokens: 100, + output_tokens: 50, + total_cost: 5, + }) + db.exec('COMMIT') + + const cutoff = '2026-02-01T00:00:00.000Z' + const deleted = repo._pruneUsage(cutoff, { batchSize: 5 }) + assert.equal(deleted, 12) + assert.equal(repo.count(), 1) + const archived = db + .prepare('SELECT total_cost, total_tokens FROM account_lifetime_usage_archive WHERE account_id = ?') + .get('acc-archive') + assert.equal(archived.total_cost, 3) + assert.equal(archived.total_tokens, 180) + assert.equal(repo._prunedThrough(), cutoff) + } finally { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test('windowStats orders minute buckets ascending and repriceRangeAsync uses composite keyset + id-sorted UNNEST', async () => { + const { dir, db, repo } = freshDb() + try { + const sqls = [] + const origPrepare = db.prepare.bind(db) + db.prepare = (sql) => { + sqls.push(String(sql)) + return origPrepare(sql) + } + try { + repo.windowStats({ since: '2026-01-01T00:00:00.000Z', until: '2026-01-01T01:00:00.000Z' }) + } finally { + db.prepare = origPrepare + } + assert.ok( + sqls.some((s) => /GROUP BY minute\s+ORDER BY minute ASC/i.test(s)), + 'windowStats must explicitly ORDER BY minute ASC for PG parity', + ) + + // Verify PG repriceRangeAsync path uses (created_at, id) keyset, id-sorted UNNEST UPDATE, and resets watermark. + const pgQueries = [] + const fakePgDb = { + engine: 'postgres', + prepare: (s) => db.prepare(s), + } + const pgRepo = new UsageLogsRepo(fakePgDb) + const fakePool = { + async query(sql, params = []) { + const text = String(sql) + pgQueries.push({ sql: text, params }) + if (/SELECT id, created_at, model/i.test(text)) { + return { + rows: [ + { + id: 'log-z', + created_at: '2026-06-01T10:02:00.000Z', + model: 'claude-sonnet-4-5', + upstream_model: 'claude-sonnet-4-5', + requested_model: 'claude-sonnet-4-5', + input_tokens: 1000, + output_tokens: 500, + cache_read_tokens: 0, + cache_creation_tokens: 0, + cache_creation_5m_tokens: 0, + cache_creation_1h_tokens: 0, + web_search_requests: 0, + total_cost: 0, + pricing_model: null, + }, + { + id: 'log-a', + created_at: '2026-06-01T10:01:00.000Z', + model: 'claude-sonnet-4-5', + upstream_model: 'claude-sonnet-4-5', + requested_model: 'claude-sonnet-4-5', + input_tokens: 2000, + output_tokens: 1000, + cache_read_tokens: 0, + cache_creation_tokens: 0, + cache_creation_5m_tokens: 0, + cache_creation_1h_tokens: 0, + web_search_requests: 0, + total_cost: 0, + pricing_model: null, + }, + ], + } + } + return { rows: [], rowCount: 1 } + }, + async connect() { + return { + async query() { + return { rows: [{ locked: false }] } + }, + release() {}, + } + }, + } + const res = await pgRepo.repriceRangeAsync({ + since: '2026-06-01T10:00:00.000Z', + until: '2026-06-01T11:00:00.000Z', + pgPool: fakePool, + awaitAggregation: true, + }) + assert.equal(res.rows, 2) + assert.equal(res.changed, 2) + const selectQ = pgQueries.find((q) => /SELECT id, created_at, model/i.test(q.sql)) + const updateQ = pgQueries.find((q) => /UPDATE usage_logs AS u/i.test(q.sql)) + const wmQ = pgQueries.find((q) => /UPDATE usage_dashboard_aggregation_watermark/i.test(q.sql)) + assert.ok(selectQ && /ORDER BY created_at DESC, id DESC/i.test(selectQ.sql)) + assert.ok(updateQ && /FROM UNNEST\(/i.test(updateQ.sql)) + assert.deepEqual(updateQ.params[0], ['log-a', 'log-z'], 'UNNEST UPDATE ids must be sorted ascending') + assert.ok(wmQ, 'repriceRangeAsync must rewind dashboard aggregation watermark') + } finally { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/usage-logs-view.test.mjs b/test/unit/usage-logs-view.test.mjs index 1ac54f37da..f45ef8361f 100644 --- a/test/unit/usage-logs-view.test.mjs +++ b/test/unit/usage-logs-view.test.mjs @@ -541,3 +541,95 @@ test('failed_only filter matches committed HTTP 200 failed terminals without alt // Combining status_code=200 + failed_only isolates committed 200 streaming failures. assert.deepEqual(ids({ status_code: '200', failed_only: true }), [rows[2].id, rows[3].id, rows[4].id].sort()) }) + +test('account_id and model filters use two-branch UNION ALL without duplicates across keyset pages', () => { + const db = freshDb() + const rows = seed(db, [ + { account_id: 'acc-a', final_account_id: 'acc-a', model: 'claude-opus-4', requested_model: 'claude-opus-4' }, + { account_id: 'acc-b', final_account_id: 'acc-a', model: 'claude-sonnet-4', requested_model: 'opus-alias' }, + { account_id: null, final_account_id: 'acc-a', model: 'opus-alias', requested_model: 'opus-alias' }, + { account_id: 'acc-a', final_account_id: null, model: 'claude-haiku-4', requested_model: 'haiku' }, + { account_id: 'acc-b', final_account_id: 'acc-b', model: 'claude-haiku-4', requested_model: 'haiku' }, + ]) + const sqls = [] + const spyDb = { + prepare(sql) { + sqls.push(String(sql)) + return db.prepare(sql) + }, + } + const view = new UsageLogsView(spyDb) + const accAll = pageAll(view, { account_id: 'acc-a', limit: 2 }) + assert.deepEqual( + accAll.seen.map((r) => r.id), + [rows[3].id, rows[2].id, rows[1].id, rows[0].id], + ) + assert.ok( + sqls.some((s) => /\bUNION ALL\b/i.test(s) && /account_id = \?/.test(s) && /final_account_id = \?/.test(s)), + 'account_id filter must use two-branch UNION ALL top-N query', + ) + + sqls.length = 0 + const modelAll = pageAll(view, { model: 'opus-alias', limit: 1 }) + assert.deepEqual( + modelAll.seen.map((r) => r.id), + [rows[2].id, rows[1].id], + ) + assert.ok( + sqls.some((s) => /\bUNION ALL\b/i.test(s) && /model = \?/.test(s) && /requested_model = \?/.test(s)), + 'model filter must use two-branch UNION ALL top-N query', + ) +}) + +test('listBatchAsync deduplicates live entries against PG page before filtering and name lookup', async () => { + const db = freshDb() + const [persisted] = seed(db, [{ account_id: 'acc-a', user_id: 'u1', api_key_id: 'k1', status: 200 }]) + const liveLogs = { + async listLiveAndRecent() { + return [ + // Duplicate of persisted PG row with an extra user_id that should never be looked up or kept + { + request_id: persisted.request_id, + created_at: persisted.created_at, + user_id: 'u-duplicate-ghost', + status: 200, + in_flight: false, + }, + // Genuinely new in-flight entry + { + request_id: 'req-live-only', + created_at: new Date(Date.parse(persisted.created_at) + 5000).toISOString(), + user_id: 'u2', + api_key_id: 'k2', + vm_id: 'vm-b', + account_id: 'acc-b', + in_flight: true, + _live: { phase: 'streaming', started_at: Date.parse(persisted.created_at) + 5000, vm_id: 'vm-b' }, + }, + ] + }, + } + const lookedUpUsers = [] + const fakeCache = { + liveLogs, + entity: { + async getEntityNames(_domain, ids, loader) { + if (_domain === 'users') lookedUpUsers.push(...ids) + return loader(ids) + }, + }, + } + const view = new UsageLogsView(db, { cache: fakeCache }) + const res = await view.listBatchAsync({ limit: 10 }, { cache: fakeCache }) + assert.deepEqual( + res.logs.map((r) => r.requestId), + ['req-live-only', persisted.request_id], + ) + assert.equal(res.logs[0].inFlight, true) + assert.equal(res.logs[1].inFlight, false) + assert.equal( + lookedUpUsers.includes('u-duplicate-ghost'), + false, + 'PG-shadowed live entry must be dropped before name lookup', + ) +}) From 00314a5dfe2fe7d2666aac3c3fcac6ac58a3ba79 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 02:12:11 +0800 Subject: [PATCH 2/2] test(usage-logs): record client.query calls from pool.connect() in repriceRangeAsync watermark test --- test/unit/usage-logs-repo.test.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/unit/usage-logs-repo.test.mjs b/test/unit/usage-logs-repo.test.mjs index 46a3ea698e..a246050317 100644 --- a/test/unit/usage-logs-repo.test.mjs +++ b/test/unit/usage-logs-repo.test.mjs @@ -838,8 +838,9 @@ test('windowStats orders minute buckets ascending and repriceRangeAsync uses com }, async connect() { return { - async query() { - return { rows: [{ locked: false }] } + async query(sql, params = []) { + pgQueries.push({ sql: String(sql), params }) + return { rows: [{ locked: false }], rowCount: 1 } }, release() {}, }