From 90c7aff671136e951c30a298fd7cf39946722ce2 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 17:17:31 +0800 Subject: [PATCH 1/3] feat(quota): add Anthropic daily VM session creation gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前:Anthropic/Claude 槽位仅按 5h/7d 配额利用率与并发席位调度,缺乏按自然日(可配 IANA 时区)限制单 Anthropic 账号新建主会话数的硬闸门;无法按账号聚合每日新建会话计数、跨进程重启恢复、同步阻断同账号兄弟槽或在面板按分档与单槽 3 态覆盖管理。 - 改后: - 存储与配置:新增 SQLite 增量迁移 `075_vm_daily_session_creations.sql` 与 PostgreSQL 18 迁移 `014_vm_daily_session_creations.sql`、双库仓储 `src/lib/db/repos/daily-session-gate-repo.mjs`(PG 走非阻塞 `pgPool`)、以及 `migrate-sqlite-to-pg.mjs` / `seed-mock-sqlite.mjs` 对接;在 `routing.quota.daily_session_gate` 增加开关(默认关闭)、`reset_timezone`(默认 `UTC`,支持任意合法 IANA 时区)与 6 档 `tier_limits`(`default`/`pro`/`max_5x`/`max_20x`/`team`/`enterprise`),支持单槽 `quota_override.daily_session_limit`(`null` 跟随分档 / `0` 不限 / `1..100000` 上限)。 - 核心闸门与调度:`src/lib/pool/daily-session-gate.mjs` 实现按 `account_uuid`(无 UUID 回退 `vm_id`)的日历日切换、DST、时区热切换、预占/幂等提交/预提交释放与并发重复会话零泄漏清理;接入 M3 Rust 调度器运行时(`scheduler-runtime.mjs` / `failover-runner.mjs` / `pool-scheduler.mjs`,含同账号兄弟槽 `new_sessions_blocked` 遥测同步与 `explainDispatch` 一致性)、Agent Sessions(`handle-agent-sessions.mjs`,按租户隔离 `kernelSessionId` 建键且延迟 sticky 绑定至提交点)以及 `src/server.mjs`(含 `activateStandby` 回填与备份恢复重绑)。 - 错误码与状态映射:`errors.mjs`、`handle-protocol.mjs` 与 `error-class.mjs` 端到端保留 HTTP 429 `daily_session_limit` + `Retry-After`(归类 `rate_limit` 并计入 `SLA_OK_ERROR_CODES`);`schedule-state.mjs` 映射 `restricted` / `new_session` / `今日新会话上限`;更新 `docs/PANEL_API.md`。 - 前端面板:在「设置 → 配额」新增每日新会话闸门卡片与 6 档弹窗、修复 `TimezonePicker` 自定义 IANA 时区入口;在 VM 调度区抽出 `vm-scheduling-model.ts` 支持 3 态 `daily_session_limit` 覆盖并在详情状态板/列表展示实时用量、在途数与重置时间。 - 未改 / 延后:不限制 Codex 槽位、续接已提交会话、子代理请求、探针与管理员 `pinVmId`;未修改 `scheduler/` Rust 源码(树哈希保持 `cac6c91fea2c1f4f5a798bd3a4c6d5d37a55f445`);未修改 `CHANGELOG.md`。 ## 验收记录(Run) - 环境与基线:WSL2 Linux + Windows `git.exe`,基于 `origin/dev` `7870fa8d52c7dcc4f2af6701a45f23f6a6a37248` rebase 后在独立工作树 `/mnt/x/vm2api-wt-anthropic-daily-session-gate` 完成全套复验(已解决 `test/unit/routing-runtime-load.test.mjs` 导入块冲突并按 Prettier 规范格式化 `web/src/features/vm/vm-list-table.test.tsx`)。 - 已跑命令与结果: - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`:PASS(exit 0) - `./node_modules/.bin/biome format`(29 个变更/新增后端 `.mjs` 文件,check-only):PASS(Checked 29 files, 0 diffs) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler npm run test:ci`:PASS(13/13 isolated files, exit 0) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler node --test test/unit/{routing-runtime-load,errors-map,error-class,vm-quota-override,scheduler-m3-runtime,rust-kernel-health,failover-runner,pool-scheduler,availability,sqlite-to-pg-migration,scheduler-m0-migrations,bg-migration-guard,database}.test.mjs`:PASS(395 pass / 0 fail / 2 skipped live-PG) - `node --test test/unit/schedule-state.test.mjs`:11 pass / 1 fail(全部新增 `daily_session_limit` 断言通过;唯一失败项为 `origin/dev` 基线既有 `crag_prompt_replace_empty_unsupported, license_invalid`) - `pnpm -C web exec prettier --check`(19 个变更/新增前端文件):PASS(exit 0) - `pnpm -C web test:ci`:PASS(9/9 files, 99/99 tests) - `pnpm -C web exec vitest run src/features/vm/proxy-timezone-copy.test.tsx src/features/settings/settings-routing-audit.test.tsx src/features/settings/index.test.tsx src/lib/vm-status.test.ts src/features/vm/vm-list-table.test.tsx src/features/vm/status-today.test.tsx src/features/pools/pools.test.ts`:PASS(7/7 files, 129/129 tests) - `pnpm -C web typecheck`:PASS(`tsc -b`, exit 0) - `pnpm -C web build`:PASS(`tsc -b && vite build`, 4523 modules, built in 15.52s, exit 0) ## 回退与手破验证(Broken by hand) - 后端 `src/lib/pool/daily-session-gate.mjs` 关闭上限阻塞判断 -> `test/unit/vm-quota-override.test.mjs` FAIL(`true !== false`,10/11)-> 恢复原实现后 PASS(11/11) - 后端 `src/lib/scheduler/scheduler-runtime.mjs` 跳过 `commitLease` 内 `dailyGate.commitReservation` -> `test/unit/scheduler-m3-runtime.test.mjs` FAIL(`0 !== 1`,12/13)-> 恢复原实现后 PASS(13/13) - 后端 `src/lib/protocol/handle-agent-sessions.mjs` 跳过 `if (gate)` 每日会话过滤 -> `test/unit/rust-kernel-health.test.mjs` FAIL(`0 !== 1`,26/27)-> 恢复原实现后 PASS(27/27) - 后端 `src/lib/core/errors.mjs` 禁用 `inboundCode === ErrorCode.DAILY_SESSION_LIMIT` 分支 -> `test/unit/errors-map.test.mjs` FAIL(`'upstream_rate_limit' !== 'daily_session_limit'`,40/41)-> 恢复原实现后 PASS(41/41) - 后端 `src/lib/protocol/handle-agent-sessions.mjs` 将 `boundCommitted` 弱化为 `Boolean(boundVm)` -> `test/unit/rust-kernel-health.test.mjs` FAIL(重试漏计数 `0 !== 1`,27/28)-> 恢复原实现后 PASS(28/28) - 前端 `web/src/features/settings/routing-draft.ts` 将 `dailySessions` 待应用检测改为比较整个 `quota` 对象 -> `web/src/features/settings/settings-routing-audit.test.tsx` FAIL(`P3-02` 期望 `dailySessions: false` 实得 `true`,19/20)-> 恢复原实现后 PASS(20/20) - 前端 `web/src/features/vm/vm-scheduling.tsx` 在 `patchOf` 跳过 `kind === 'int'` 且值为 `0` -> `web/src/features/vm/vm-list-table.test.tsx` FAIL(期望 `{ quota_override: { daily_session_limit: 0 } }` 实得 `{}`,28/29)-> 恢复原实现后 PASS(29/29) - 前端 `web/src/features/vm/create-options.ts` 回退 `resolveTimezonePickerState` 为旧逻辑 `showCustom = custom && !preset` -> `web/src/features/vm/proxy-timezone-copy.test.tsx` FAIL(`'UTC'` 切换自定义返回 `showCustom: false`,1/3)-> 恢复原实现后 PASS(3/3) ## 真实使用(Real use) - 未执行真实线上 `ph24` 流量或真实浏览器交互点击实测:本次按沙箱与本地提交要求执行,未连接生产环境;后端通过真实 Rust `kin-scheduler` 二进制(`cac6c91fea2c1f4f5a798bd3a4c6d5d37a55f445`)在单测中拉起真实调度进程跑通预占/提交/释放/遥测链路,前端通过 Vitest SSR、状态钩子测试及 Vite 生产包构建验收。 ## 未运行项(Not run) - 真实 PostgreSQL 18 集成测试:未配置 `VM2API_TEST_PG_URL`,2 个 live-PG 用例自动跳过(PG 异步仓储与 SQLite→PG 迁移表映射已通过单测与 mock 覆盖)。 - 全量 556 个后端单测文件、真实浏览器 E2E 点击流程与 ARM64 镜像/生产发布:本次仅按用户指令完成本地原子提交,未推送远端、未开 PR、未部署。 --- docs/PANEL_API.md | 17 +- scripts/migrate-sqlite-to-pg.mjs | 1 + scripts/seed-mock-sqlite.mjs | 9 + src/lib/admin/error-class.mjs | 2 + src/lib/admin/panel-api.mjs | 64 +- src/lib/admin/panel-routes.mjs | 20 + src/lib/admin/routing-runtime.mjs | 20 +- src/lib/core/errors.mjs | 14 + .../075_vm_daily_session_creations.sql | 15 + .../014_vm_daily_session_creations.sql | 16 + src/lib/db/repos/daily-session-gate-repo.mjs | 319 +++++++ src/lib/pool/availability.mjs | 2 + src/lib/pool/daily-session-gate.mjs | 867 ++++++++++++++++++ src/lib/pool/failover-runner.mjs | 1 + src/lib/pool/pool-scheduler.mjs | 4 + src/lib/pool/schedule-state.mjs | 9 + src/lib/pool/vm-quota-override.mjs | 41 +- src/lib/protocol/handle-agent-sessions.mjs | 136 ++- src/lib/protocol/handle-protocol.mjs | 21 + src/lib/scheduler/scheduler-runtime.mjs | 297 +++++- src/server.mjs | 53 ++ test/unit/bg-migration-guard.test.mjs | 3 + test/unit/error-class.test.mjs | 71 ++ test/unit/errors-map.test.mjs | 31 + test/unit/pool-scheduler.test.mjs | 69 ++ test/unit/routing-runtime-load.test.mjs | 304 +++++- test/unit/rust-kernel-health.test.mjs | 217 ++++- test/unit/schedule-state.test.mjs | 47 + test/unit/scheduler-m0-migrations.test.mjs | 9 +- test/unit/scheduler-m3-runtime.test.mjs | 293 ++++++ test/unit/sqlite-to-pg-migration.test.mjs | 14 + test/unit/vm-quota-override.test.mjs | 504 +++++++++- web/src/features/pools/pool-rules.ts | 3 + web/src/features/pools/pools.test.ts | 8 + web/src/features/settings/index.tsx | 39 +- web/src/features/settings/quota-controls.tsx | 14 +- web/src/features/settings/quota-tier-pane.tsx | 221 ++++- web/src/features/settings/quota-values.ts | 150 ++- web/src/features/settings/routing-draft.ts | 47 +- .../settings/settings-routing-audit.test.tsx | 354 ++++++- web/src/features/vm/create-options.ts | 17 + web/src/features/vm/detail-status-board.tsx | 41 + .../features/vm/proxy-timezone-copy.test.tsx | 207 ++++- web/src/features/vm/status-today.test.tsx | 52 ++ web/src/features/vm/timezone-picker.tsx | 13 +- web/src/features/vm/vm-list-table.test.tsx | 178 +++- web/src/features/vm/vm-scheduling-model.ts | 280 ++++++ web/src/features/vm/vm-scheduling.tsx | 335 ++----- web/src/lib/vm-status.test.ts | 36 + web/src/lib/vm-status.ts | 9 +- web/src/types/panel-vm.ts | 37 +- 51 files changed, 5216 insertions(+), 315 deletions(-) create mode 100644 src/lib/db/migrations/075_vm_daily_session_creations.sql create mode 100644 src/lib/db/pg/pg-migrations/014_vm_daily_session_creations.sql create mode 100644 src/lib/db/repos/daily-session-gate-repo.mjs create mode 100644 src/lib/pool/daily-session-gate.mjs create mode 100644 web/src/features/vm/vm-scheduling-model.ts diff --git a/docs/PANEL_API.md b/docs/PANEL_API.md index 592932f7eb..cc7e546de4 100644 --- a/docs/PANEL_API.md +++ b/docs/PANEL_API.md @@ -197,7 +197,7 @@ 受限另带 `restriction_text`(文案)、`restriction_scope` 与 `restriction_soft`: -- `restriction_scope: "new_session"`:只拦新会话,已入座会话照常(`seats_full` 席位满、`sessions_full` GPT 对话窗口满、`gate_5h_draining` / `gate_7d_draining` 临近闸线)。 +- `restriction_scope: "new_session"`:只拦新会话,已入座会话照常(`seats_full` 席位满、`sessions_full` GPT 对话窗口满、`gate_5h_draining` / `gate_7d_draining` 临近闸线、`daily_session_limit` 今日新会话上限)。 - `restriction_soft: true`:全池没有 `on` 的槽时新会话仍可落上来(只有临近闸线)。 优先级:`off` > `unschedulable` > `restricted`(额度 → 熔断 → 冷却 → 临近闸线 → 席位满)> `on`。调度关的槽若同时有不可调度原因,仍显示调度关,原因保留在 `unschedulable_*`。 @@ -224,6 +224,8 @@ OpenAI 另支持 `PATCH {"max_sessions": 0..256 | null}`:数字钉住活跃对 Claude PATCH `max_sessions` 返回 400 `claude_max_sessions_forbidden`;OpenAI PATCH `session_slots` / `quota_override` 分别返回 400 `gpt_session_slots_forbidden` / `gpt_quota_override_forbidden`。非法新限额返回 400 `invalid_scheduling_value`。混合字段先校验,再写入,拒绝的字段不会使同一请求中的其它限额部分生效。 +Claude 的 `PATCH /api/panel/vms/:id` 亦支持 `quota_override.daily_session_limit`(整数 `0`–`100000` 或 `null`):`null` / 省略跟随全局按等级上限,`0` 显式免限(即使全局开启也放行),`>= 1` 为本槽独立每日新建主会话上限(即使全局关闭也生效)。列表与详情返回 `quota_policy.daily_session_limit`、`quota_inherited.daily_session_limit` 与运行态只读字段 `daily_sessions: { enabled, active, used, pending, limit, remaining, blocked, day_key, timezone, reset_at, reset_at_ms, tier_key, source }`(Codex 槽为 `null`);触顶时槽位进入 `schedule_state: "restricted"`、`restriction_scope: "new_session"`、`restriction_reason: "daily_session_limit"`、`restriction_text: "今日新会话上限"`、`restriction_until: reset_at_ms`,已有会话与子代理继续放行。 + `POST /vms/create` 指定 `platform: "openai"`,省略并发/RPM/会话上限即跟随已保存的 OpenAI 全局值;显式值钉住本槽。OpenAI 凭证导入/重导入保留既有覆盖和权重,未覆盖字段采用当前 OpenAI 全局值;不新增跨平台切换入口。 ### Docker 槽可选 CPU 上限 @@ -353,6 +355,19 @@ H1 删除已绑定槽时,控制面保留最小私有回收记录,只有严 `PUT` 热更新。`tiers` 必须回传:该块是整体替换而非 patch,缺字段即置空。Claude 分档保存只传播到未手动覆盖的 Claude 槽。OpenAI `codex.quota` 按字段合并,不覆盖其它 Codex 协议/客户端配置,只更新跟随的 OpenAI 限额。 +### Anthropic 每日新会话闸门(`quota.daily_session_gate`) + +`GET/PUT /api/panel/routing` 在 `quota.daily_session_gate` 下配置 Anthropic 平台单账号每日新建主会话上限(按字段深合并,非法配置返回 400 `invalid_quota_config`): + +```json +{"quota":{"daily_session_gate":{"enabled":false,"reset_timezone":"UTC","tier_limits":{"default":0,"pro":0,"max_5x":0,"max_20x":0,"team":0,"enterprise":0}}}} +``` + +- `enabled`:布尔,默认 `false`;开启后按账号等级限制 Anthropic 槽位每个自然日的新建主会话数(已有粘性会话、子代理、临时探测及管理员 pin 诊断不拦截)。 +- `reset_timezone`:标准 IANA 时区名(默认 `"UTC"`,拒绝纯偏移量如 `"+08:00"`),按该时区自然日零点重置。 +- `tier_limits`:`default` / `pro` / `max_5x` / `max_20x` / `team` / `enterprise` 六档整数 `0`–`100000`;`0` 始终表示该档不限(不回退 `default`),未识别或 Free 账号使用 `default`。 +- 全池因该闸门无法承接新主会话时返回 HTTP `429`(`type: "rate_limit_error"`,`code: "daily_session_limit"`,带 `Retry-After` 至最早重置时刻)。 + ### OpenAI 传输与隐私 设置页的「调度 → OpenAI」和「槽位 → OpenAI」进入同一个 `#/settings/openai` 页面。GPT 协议、客户端准入、目录版本及全局配额集中在这里;Claude 配置仍在原页。保存使用现有 `PUT /api/panel/routing`。 diff --git a/scripts/migrate-sqlite-to-pg.mjs b/scripts/migrate-sqlite-to-pg.mjs index 3b2bffc4a0..289f6e9bbc 100755 --- a/scripts/migrate-sqlite-to-pg.mjs +++ b/scripts/migrate-sqlite-to-pg.mjs @@ -65,6 +65,7 @@ export const MIGRATION_TABLES = [ 'scheduler_node_penalties', 'vms', 'codex_slot_runtime', + 'vm_daily_session_creations', 'thinking_signature_owners', 'usage_logs', 'request_log_debug', diff --git a/scripts/seed-mock-sqlite.mjs b/scripts/seed-mock-sqlite.mjs index 7fbce62e1a..b9eec66ada 100755 --- a/scripts/seed-mock-sqlite.mjs +++ b/scripts/seed-mock-sqlite.mjs @@ -343,6 +343,15 @@ export function seedMockSqlite({ outPath, usageCount = 400, hashSecret = 'mock-v nowIso, ) + // 5c. vm_daily_session_creations (Anthropic per-account daily new session creation ledger) + const todayUtcKey = new Date(nowMs).toISOString().slice(0, 10) + const insDailySession = db.prepare(` + INSERT INTO vm_daily_session_creations (platform, account_key, day_key, session_id, vm_id, created_at) + VALUES (?, ?, ?, ?, ?, ?) + `) + insDailySession.run('anthropic', 'acct-mock-01', todayUtcKey, 'sess-daily-01', 'vm-01', nowMs - hourMs) + insDailySession.run('anthropic', 'acct-mock-01', todayUtcKey, 'sess-daily-02', 'vm-01', nowMs - 10 * 60 * 1000) + // 6. vm_pools & 7. vm_pool_members (often empty in prod!) const insPool = db.prepare( 'INSERT INTO vm_pools (id, name, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, ?)', diff --git a/src/lib/admin/error-class.mjs b/src/lib/admin/error-class.mjs index 0790a77e0b..0d9922d52c 100644 --- a/src/lib/admin/error-class.mjs +++ b/src/lib/admin/error-class.mjs @@ -65,6 +65,7 @@ const CODE_MAP = { pool_overload_cooldown: 'overloaded', pool_rate_limited: 'rate_limit', fable_requires_max: 'rate_limit', + daily_session_limit: 'rate_limit', user_concurrency_limit: 'quota', account_pool_exhausted: 'unavailable', api_pool_exhausted: 'unavailable', @@ -180,6 +181,7 @@ export const SLA_OK_ERROR_CODES = new Set([ 'quota_5h_safety', 'quota_7d_safety', 'quota_guard_request_too_large', + 'daily_session_limit', 'api_key_quota_exhausted', 'concurrency_limit', 'api_key_concurrency_limit', diff --git a/src/lib/admin/panel-api.mjs b/src/lib/admin/panel-api.mjs index 32bb3cb7aa..79e322045f 100644 --- a/src/lib/admin/panel-api.mjs +++ b/src/lib/admin/panel-api.mjs @@ -61,6 +61,13 @@ import { accountTierKey, isNearLimit, normalizeTiers, resolveTierPolicy } from ' import { isOrganizationDisabledUsageResult } from '../pool/upstream-error-policy.mjs' import { mergeBatchGroupConfig } from '../pool/batch-group.mjs' import { applyVmQuotaConfig, applyVmQuotaPolicy, vmQuotaOverrideOf, vmQuotaView } from '../pool/vm-quota-override.mjs' +import { + isAnthropicSessionVm, + normalizeDailySessionGate, + resolveDayWindow, + resolveEffectiveDailySessionPolicy, + resolveInheritedDailySessionLimit, +} from '../pool/daily-session-gate.mjs' import { GATE_OPEN, gatePolicyFields, gateZone, quotaGateOf } from '../pool/quota-gate.mjs' import { guardUsageTier, inferClaudeTier } from '../pool/claude-tier.mjs' import { fableRequiresMaxEnabled, slotDeniesFableForPlan } from '../pool/slot-model-gate.mjs' @@ -812,6 +819,7 @@ export async function buildDashboard({ proxyPool = null, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, bypass = false, }) { // Expired runtime windows are cleared asynchronously by `pool-scheduler.maintain()`; @@ -853,6 +861,7 @@ export async function buildDashboard({ codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, supplierTag: supplierById?.get(v.id) || null, + dailySessionGate, }), ) const accounts = liveAccounts(snap.accounts, listed) @@ -955,6 +964,7 @@ export async function buildVmList({ requestLog = null, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, bypass = false, } = {}) { const active = getActiveVmId(cfg.paths.project) @@ -984,6 +994,7 @@ export async function buildVmList({ codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, supplierTag: supplierById?.get(v.id) || null, + dailySessionGate, }), ) const accounts = snap?.accounts || [] @@ -1022,6 +1033,7 @@ export async function buildVmDetail({ slotProcessStatus = readSlotProcessStatus, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, role = 'admin', bypass = false, }) { @@ -1061,6 +1073,7 @@ export async function buildVmDetail({ codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, supplierTag: supplierTagStore?.get?.('vm', id) || null, + dailySessionGate, }) const acc = findAccount(accountQuota, summary, snap) const billing = await (async () => { @@ -1830,7 +1843,10 @@ export function buildRouting({ routingConfig, stickyRouter }) { const tiers = normalizeTiers(routingConfig?.tiers, routingConfig?.quota, routingConfig?.concurrency) return ok({ sticky: routingConfig?.sticky || {}, - quota: routingConfig?.quota || {}, + quota: { + ...(routingConfig?.quota || {}), + daily_session_gate: normalizeDailySessionGate(routingConfig?.quota?.daily_session_gate), + }, concurrency: routingConfig?.concurrency || {}, tiers, logging: routingConfig?.logging || {}, @@ -1866,6 +1882,7 @@ export async function snapshotAccountPool({ poolScheduler = null, proxyPool = null, requestLog = null, + dailySessionGate = null, bypass = false, }) { const active = getActiveVmId(cfg.paths.project) @@ -1898,6 +1915,7 @@ export async function snapshotAccountPool({ runtimeById, codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, + dailySessionGate, }), ) const accounts = snap?.accounts || [] @@ -2363,6 +2381,39 @@ function enrichVm(v, accountQuota, active, extras = {}) { : limits.subagents == null ? resolveSessionSlots(v, extras.routingConfig || {}) : limits.seats + const now = Date.now() + const isAnthropicVm = !isCodex && isAnthropicSessionVm(v) + const dailyVm = + isAnthropicVm && !v.account_uuid && acc?.account_id && acc.account_id !== v.id + ? { ...v, account_uuid: acc.account_id } + : v + const gateConfig = extras.routingConfig?.quota?.daily_session_gate + const inheritedDailySessionLimit = isAnthropicVm ? resolveInheritedDailySessionLimit(dailyVm, gateConfig) : 0 + let dailySessions = null + if (isAnthropicVm) { + if (typeof extras.dailySessionGate?.statusForVm === 'function') { + dailySessions = extras.dailySessionGate.statusForVm(dailyVm, now) + } else { + const gate = normalizeDailySessionGate(gateConfig) + const pol = resolveEffectiveDailySessionPolicy(dailyVm, gate) + const win = resolveDayWindow(now, gate.reset_timezone) + dailySessions = { + enabled: pol.enabled, + active: pol.active, + used: 0, + pending: 0, + limit: pol.limit, + remaining: pol.active ? pol.limit : null, + blocked: false, + day_key: win.dayKey, + timezone: win.timezone, + reset_at: win.resetAt, + reset_at_ms: win.resetAtMs, + tier_key: pol.tier_key, + source: pol.source, + } + } + } const triad = resolveScheduleState({ vm: v, availability, @@ -2372,6 +2423,8 @@ function enrichVm(v, accountQuota, active, extras = {}) { circuit, seats: isCodex ? null : { used: Number(seatRow?.seats_used) || 0, max: seatsMax }, sessions: isCodex ? { active: codexSessions?.active, max: codexSessions?.max } : null, + dailySessions, + now, }) return { id: v.id, @@ -2454,8 +2507,13 @@ function enrichVm(v, accountQuota, active, extras = {}) { fatalWindowHours: extras.routingConfig?.warmup?.fatal_window_hours ?? 0, }), quota_override: quotaOverride, - quota_policy: isCodex ? null : vmQuotaView(policy, vmQuotaConfig), - quota_inherited: isCodex ? null : vmQuotaView(inheritedPolicy, globalQuotaConfig), + quota_policy: isCodex + ? null + : vmQuotaView(policy, vmQuotaConfig, { daily_session_limit: inheritedDailySessionLimit }), + quota_inherited: isCodex + ? null + : vmQuotaView(inheritedPolicy, globalQuotaConfig, { daily_session_limit: inheritedDailySessionLimit }), + daily_sessions: dailySessions, openai_quota_policy: isCodex ? v.quota_policy || null : null, rpm: isCodex ? Math.max( diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index 8309a9f9c2..c60295bac1 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -973,11 +973,20 @@ export function createPanelHandler(ctx) { if (typeof ctx.getSchedulerRuntime === 'function') return ctx.getSchedulerRuntime() return typeof ctx.schedulerRuntime === 'function' ? ctx.schedulerRuntime() : ctx.schedulerRuntime || null } + const resolveDailySessionGate = () => { + if (typeof ctx.getDailySessionGate === 'function') return ctx.getDailySessionGate() + return typeof ctx.dailySessionGate === 'function' ? ctx.dailySessionGate() : ctx.dailySessionGate || null + } const notifySchedulerConfigChanged = (reason) => { const rt = resolveSchedulerRuntime() if (!rt || typeof rt.syncConfigNow !== 'function') return void rt.syncConfigNow(reason).catch(() => {}) } + const notifySchedulerTelemetry = () => { + const rt = resolveSchedulerRuntime() + if (!rt || typeof rt.pushTelemetryNow !== 'function') return + void rt.pushTelemetryNow().catch(() => {}) + } const handleSchedulerPools = createSchedulerPoolsHandler({ getDb: () => apiKeyStore?.db || ctx.getDb?.() || getDb(), getRouting: () => ctx.routingConfig || {}, @@ -1899,7 +1908,9 @@ export function createPanelHandler(ctx) { } stickyRouter.reloadConfig(ctx.routingConfig) accountQuota.reloadConfig(ctx.routingConfig) + resolveDailySessionGate()?.reloadConfig?.(ctx.routingConfig) ctx.poolScheduler?.reloadConfig?.(poolSchedulerConfig()) + notifySchedulerTelemetry() try { await ensureRedaction(ctx.routingConfig, { projectRoot: cfg.paths.project }) } catch {} @@ -2199,6 +2210,7 @@ export function createPanelHandler(ctx) { } throw error } + notifySchedulerTelemetry() return json(res, 200, { ok: true, routing: publicRoutingNotify(ctx.routingConfig), @@ -4098,6 +4110,7 @@ export function createPanelHandler(ctx) { proxyPool, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), bypass, }), { freshTtlMs: 5_000, ttlMs: 15_000, bypass }, @@ -4134,6 +4147,7 @@ export function createPanelHandler(ctx) { ownerUserId, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), bypass, }) if ((filterOwner || filterSupplier) && built?.data) { @@ -5128,6 +5142,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: ident.role, bypass, }) @@ -5165,6 +5180,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: panelIdentity(req).role, }) return json(res, 200, detail) @@ -5450,6 +5466,7 @@ export function createPanelHandler(ctx) { if (parsedQuotaOverride) { const vm = applyVmQuotaOverride(id, parsedQuotaOverride.value) if (!vm) return json(res, 404, { ok: false, error: { message: 'vm not found' } }) + notifySchedulerTelemetry() } if (hasModels) { const parsed = parseAllowedModelsPatch(body.allowed_models, { vm: currentVm }) @@ -5623,6 +5640,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: panelIdentity(req).role, }) if (slotPolicyResult && detail?.data) { @@ -8582,6 +8600,7 @@ export function createPanelHandler(ctx) { }, }) } + notifySchedulerTelemetry() return json( res, 200, @@ -8884,6 +8903,7 @@ export function createPanelHandler(ctx) { poolScheduler: ctx.poolScheduler, proxyPool, requestLog, + dailySessionGate: resolveDailySessionGate(), })), }) return json(res, 200, panel.ok(result)) diff --git a/src/lib/admin/routing-runtime.mjs b/src/lib/admin/routing-runtime.mjs index 5ecf061382..e92121cddf 100644 --- a/src/lib/admin/routing-runtime.mjs +++ b/src/lib/admin/routing-runtime.mjs @@ -26,6 +26,7 @@ import { maxRequestBytes, streamIdleTimeoutMs } from '../core/config.mjs' import { accountTierKey, mergeTierMaps, normalizeTiers } from '../pool/quota-tiers.mjs' import { mergeBatchGroupConfig } from '../pool/batch-group.mjs' import { vmQuotaOverrideOf } from '../pool/vm-quota-override.mjs' +import { mergeDailySessionGate, normalizeDailySessionGate } from '../pool/daily-session-gate.mjs' import { PoolScheduler, normalizePoolRouting, validateQuotaRoutingPatch } from '../pool/pool-scheduler.mjs' import { FailoverRunner } from '../pool/failover-runner.mjs' import { unitCircuit } from '../pool/unit-circuit.mjs' @@ -91,6 +92,8 @@ export function createRoutingRuntime(ctx) { const getWarmup = () => ctx.warmupMonitor const getCragZombieGuard = () => ctx.cragZombieGuard const getNotify = () => ctx.notifyMonitor + const getDailySessionGate = () => + typeof ctx.getDailySessionGate === 'function' ? ctx.getDailySessionGate() : ctx.dailySessionGate const setRuntimeRepo = (next) => { if (typeof ctx.setRuntimeRepo === 'function') ctx.setRuntimeRepo(next) else ctx.runtimeRepo = next @@ -607,6 +610,7 @@ export function createRoutingRuntime(ctx) { const prevCragZombieGuard = routingConfig.crag_zombie_guard const prevNotify = routingConfig.notify const prevTiers = routingConfig.tiers + const prevDailySessionGate = routingConfig.quota?.daily_session_gate const prevIdleMs = streamIdleTimeoutMs(routingConfig) const prevRequestBytes = maxRequestBytes(routingConfig) const prevUploadInterval = telemetryUploadInterval(routingConfig) @@ -614,7 +618,16 @@ export function createRoutingRuntime(ctx) { const prevDisableNonessential = telemetryDisableNonessentialTraffic(routingConfig) setRouting(routingConfig) if (body.sticky) routingConfig.sticky = { ...(routingConfig.sticky || {}), ...body.sticky } - if (body.quota) routingConfig.quota = { ...(routingConfig.quota || {}), ...body.quota } + if (body.quota) { + const nextDailyGate = Object.prototype.hasOwnProperty.call(body.quota, 'daily_session_gate') + ? mergeDailySessionGate(prevDailySessionGate, body.quota.daily_session_gate) + : normalizeDailySessionGate(prevDailySessionGate) + routingConfig.quota = { + ...(routingConfig.quota || {}), + ...body.quota, + daily_session_gate: nextDailyGate, + } + } if (body.concurrency) routingConfig.concurrency = { ...(routingConfig.concurrency || {}), ...body.concurrency } if (body.pool) { routingConfig.pool = normalizePoolRouting({ ...(routingConfig.pool || {}), ...body.pool }) @@ -731,6 +744,7 @@ export function createRoutingRuntime(ctx) { atomicWriteJson(ctx.routingConfigPath, routingConfig, { mode: 0o600 }) ctx.stickyRouter.reloadConfig(routingConfig) ctx.accountQuota.reloadConfig(routingConfig) + getDailySessionGate()?.reloadConfig?.(routingConfig) getPool()?.reloadConfig?.(poolSchedulerConfig()) const sessionSlotsApplied = body.inference && Object.hasOwn(body.inference, 'session_slots') @@ -836,6 +850,10 @@ export function createRoutingRuntime(ctx) { doc.gemini = normalizeGeminiRouting(doc.gemini) doc.pool = normalizePoolRouting(doc.pool) doc.vm = normalizeVmConfig(doc.vm) + doc.quota = { + ...(doc.quota && typeof doc.quota === 'object' && !Array.isArray(doc.quota) ? doc.quota : {}), + daily_session_gate: normalizeDailySessionGate(doc.quota?.daily_session_gate), + } if (!hasOpenAIQuota) migrateLegacyOpenAIPolicies(doc) if (doc.batch_group != null) doc.batch_group = mergeBatchGroupConfig(doc.batch_group) if (doc.redaction != null) doc.redaction = normalizeRedaction(doc.redaction) diff --git a/src/lib/core/errors.mjs b/src/lib/core/errors.mjs index f7ecea4cb6..14d96e6219 100644 --- a/src/lib/core/errors.mjs +++ b/src/lib/core/errors.mjs @@ -92,6 +92,7 @@ export const ErrorCode = { NO_AVAILABLE_ACCOUNT: 'no_available_account', SCHEDULER_UNAVAILABLE: 'scheduler_unavailable', FABLE_REQUIRES_MAX: 'fable_requires_max', + DAILY_SESSION_LIMIT: 'daily_session_limit', NATIVE_HANDOFF_MISSING: 'native_handoff_missing', NATIVE_HANDOFF_INVALID: 'native_handoff_invalid', NATIVE_HANDOFF_CONFLICT: 'native_handoff_conflict', @@ -1304,6 +1305,18 @@ export function mapUpstreamError(status, body, headers = {}) { status: 429, }) } + if (inboundCode === ErrorCode.DAILY_SESSION_LIMIT) { + const retryAfterSec = retryAfterSeconds(headers['retry-after']) + return { + ...makeError({ + type: ErrorType.RATE_LIMIT, + code: ErrorCode.DAILY_SESSION_LIMIT, + message: String(msg || 'Anthropic accounts have reached their daily new session limit'), + status: 429, + }), + ...(retryAfterSec ? { retryAfterSec } : {}), + } + } if (inboundCode === ErrorCode.QUOTA_GUARD_REQUEST_TOO_LARGE) { return makeError({ type: ErrorType.RATE_LIMIT, @@ -1644,6 +1657,7 @@ export function mapUpstreamError(status, body, headers = {}) { const STRICT_LOCAL_GATEWAY_CODES = new Set([ ErrorCode.FABLE_REQUIRES_MAX, + ErrorCode.DAILY_SESSION_LIMIT, ErrorCode.QUOTA_GUARD_REQUEST_TOO_LARGE, ErrorCode.SLOT_OAUTH_UNAVAILABLE, ErrorCode.CLUSTER_DELIVERY_UNCONFIRMED, diff --git a/src/lib/db/migrations/075_vm_daily_session_creations.sql b/src/lib/db/migrations/075_vm_daily_session_creations.sql new file mode 100644 index 0000000000..412361d048 --- /dev/null +++ b/src/lib/db/migrations/075_vm_daily_session_creations.sql @@ -0,0 +1,15 @@ +-- 075_vm_daily_session_creations — Persistent per-account daily new session creation ledger. +-- Mirrors PostgreSQL migration 014_vm_daily_session_creations.sql. + +CREATE TABLE IF NOT EXISTS vm_daily_session_creations ( + platform TEXT NOT NULL, + account_key TEXT NOT NULL, + day_key TEXT NOT NULL, + session_id TEXT NOT NULL, + vm_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (platform, account_key, day_key, session_id) +); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_creations_created + ON vm_daily_session_creations (platform, created_at); diff --git a/src/lib/db/pg/pg-migrations/014_vm_daily_session_creations.sql b/src/lib/db/pg/pg-migrations/014_vm_daily_session_creations.sql new file mode 100644 index 0000000000..c29c37617e --- /dev/null +++ b/src/lib/db/pg/pg-migrations/014_vm_daily_session_creations.sql @@ -0,0 +1,16 @@ +-- 014_vm_daily_session_creations.sql +-- Persistent per-account daily new session creation ledger for daily session creation gate. +-- Mirrors SQLite migration 075_vm_daily_session_creations.sql. + +CREATE TABLE IF NOT EXISTS vm_daily_session_creations ( + platform TEXT NOT NULL, + account_key TEXT NOT NULL, + day_key TEXT NOT NULL, + session_id TEXT NOT NULL, + vm_id TEXT NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY (platform, account_key, day_key, session_id) +); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_creations_created + ON vm_daily_session_creations (platform, created_at); diff --git a/src/lib/db/repos/daily-session-gate-repo.mjs b/src/lib/db/repos/daily-session-gate-repo.mjs new file mode 100644 index 0000000000..e1cf7a140b --- /dev/null +++ b/src/lib/db/repos/daily-session-gate-repo.mjs @@ -0,0 +1,319 @@ +/** + * Dual-DB repository for per-account daily new session creation records + * (`vm_daily_session_creations`). + * + * SQLite uses prepared synchronous statements. PostgreSQL 18 uses non-blocking + * `pgPool.query` (`0 Atomics.wait` on the hot path): startup/timezone hydration + * runs via `listSinceAsync`, and commit persistence fires asynchronously via + * `recordCreation` (or awaitably via `recordCreationAsync`). + */ +import { getDb, getPgPool, isDbOpen } from '../database.mjs' + +const SQLITE_LIST_SINCE_SQL = `SELECT platform, account_key, day_key, session_id, vm_id, created_at +FROM vm_daily_session_creations +WHERE platform = ? AND created_at >= ? +ORDER BY created_at ASC` + +const PG_LIST_SINCE_SQL = `SELECT platform, account_key, day_key, session_id, vm_id, created_at +FROM vm_daily_session_creations +WHERE platform = $1 AND created_at >= $2 +ORDER BY created_at ASC` + +const SQLITE_INSERT_SQL = `INSERT INTO vm_daily_session_creations ( + platform, account_key, day_key, session_id, vm_id, created_at +) VALUES (?, ?, ?, ?, ?, ?) +ON CONFLICT (platform, account_key, day_key, session_id) DO NOTHING` + +const PG_INSERT_SQL = `INSERT INTO vm_daily_session_creations ( + platform, account_key, day_key, session_id, vm_id, created_at +) VALUES ($1, $2, $3, $4, $5, $6) +ON CONFLICT (platform, account_key, day_key, session_id) DO NOTHING` + +const SQLITE_PRUNE_SQL = 'DELETE FROM vm_daily_session_creations WHERE platform = ? AND created_at < ?' +const PG_PRUNE_SQL = 'DELETE FROM vm_daily_session_creations WHERE platform = $1 AND created_at < $2' + +function cleanText(value) { + if (value == null) return '' + return String(value).trim() +} + +function cleanTimestampMs(value, fallback = null) { + if (value == null || value === '') return fallback + const n = Number(value) + if (!Number.isFinite(n) || n < 0) return fallback + return Math.floor(n) +} + +export function decodeDailySessionCreationRow(row) { + if (!row || typeof row !== 'object') return null + const platform = cleanText(row.platform) + const accountKey = cleanText(row.account_key) + const dayKey = cleanText(row.day_key) + const sessionId = cleanText(row.session_id) + const vmId = cleanText(row.vm_id) + const createdAt = cleanTimestampMs(row.created_at) + if (!platform || !accountKey || !dayKey || !sessionId || createdAt == null) return null + return { + platform, + account_key: accountKey, + day_key: dayKey, + session_id: sessionId, + vm_id: vmId || accountKey, + created_at: createdAt, + } +} + +export function normalizeDailySessionCreationRecord(record) { + if (!record || typeof record !== 'object') return null + const platform = cleanText(record.platform) + const accountKey = cleanText(record.accountKey ?? record.account_key) + const dayKey = cleanText(record.dayKey ?? record.day_key) + const sessionId = cleanText(record.sessionId ?? record.session_id) + const vmId = cleanText(record.vmId ?? record.vm_id) + const createdAt = cleanTimestampMs(record.createdAt ?? record.created_at, Date.now()) + if (!platform || !accountKey || !dayKey || !sessionId || createdAt == null) return null + return { + platform, + account_key: accountKey, + day_key: dayKey, + session_id: sessionId, + vm_id: vmId || accountKey, + created_at: createdAt, + } +} + +/** + * Async PostgreSQL loader for daily session creations since `sinceMs` (`0 Atomics.wait`). + * @param {import('pg').Pool | null} pgPool + * @param {string} platform + * @param {number} sinceMs + * @returns {Promise>} + */ +export async function listDailySessionCreationsSincePgAsync(pgPool, platform, sinceMs) { + if (!pgPool || typeof pgPool.query !== 'function') return [] + const plat = cleanText(platform) + const since = cleanTimestampMs(sinceMs, 0) + if (!plat) return [] + const res = await pgPool.query(PG_LIST_SINCE_SQL, [plat, since]) + const out = [] + for (const row of res?.rows || []) { + const decoded = decodeDailySessionCreationRow(row) + if (decoded) out.push(decoded) + } + return out +} + +/** + * Async PostgreSQL idempotent insert for a daily session creation (`0 Atomics.wait`). + * @param {import('pg').Pool | null} pgPool + * @param {object} record + * @returns {Promise<{ inserted: boolean }>} + */ +export async function recordDailySessionCreationPgAsync(pgPool, record) { + if (!pgPool || typeof pgPool.query !== 'function') return { inserted: false } + const norm = normalizeDailySessionCreationRecord(record) + if (!norm) return { inserted: false } + const res = await pgPool.query(PG_INSERT_SQL, [ + norm.platform, + norm.account_key, + norm.day_key, + norm.session_id, + norm.vm_id, + norm.created_at, + ]) + return { inserted: Number(res?.rowCount || 0) > 0 } +} + +/** + * Async PostgreSQL prune of expired daily session creation rows (`0 Atomics.wait`). + * @param {import('pg').Pool | null} pgPool + * @param {string} platform + * @param {number} beforeMs + * @returns {Promise} + */ +export async function pruneDailySessionCreationsBeforePgAsync(pgPool, platform, beforeMs) { + if (!pgPool || typeof pgPool.query !== 'function') return 0 + const plat = cleanText(platform) + const cutoff = cleanTimestampMs(beforeMs) + if (!plat || cutoff == null) return 0 + const res = await pgPool.query(PG_PRUNE_SQL, [plat, cutoff]) + return Number(res?.rowCount || 0) +} + +export class DailySessionGateRepo { + /** + * Accepts either `new DailySessionGateRepo(db, { pgPool, onError })` or + * `new DailySessionGateRepo({ db, pgPool, onError })`. + */ + constructor(dbOrOpts = undefined, opts = {}) { + if ( + dbOrOpts && + typeof dbOrOpts === 'object' && + typeof dbOrOpts.prepare !== 'function' && + ('db' in dbOrOpts || 'pgPool' in dbOrOpts || 'onError' in dbOrOpts) + ) { + this._explicitDb = dbOrOpts.db + this._explicitPgPool = dbOrOpts.pgPool + this._onError = typeof dbOrOpts.onError === 'function' ? dbOrOpts.onError : null + } else { + this._explicitDb = dbOrOpts + this._explicitPgPool = opts?.pgPool + this._onError = typeof opts?.onError === 'function' ? opts.onError : null + } + this._stmtDb = null + this._listSinceStmt = null + this._insertStmt = null + this._pruneStmt = null + } + + rebind(db, { pgPool } = {}) { + this._explicitDb = db + if (pgPool !== undefined) this._explicitPgPool = pgPool + this._stmtDb = null + this._listSinceStmt = null + this._insertStmt = null + this._pruneStmt = null + } + + _resolveDb() { + if (this._explicitDb !== undefined) return this._explicitDb + if (!isDbOpen()) return null + try { + return getDb() + } catch { + return null + } + } + + _resolvePgPool() { + if (this._explicitPgPool !== undefined) { + return this._explicitPgPool && typeof this._explicitPgPool.query === 'function' ? this._explicitPgPool : null + } + const db = this._resolveDb() + if (db && db.engine !== 'postgres') return null + try { + const pool = getPgPool() + return pool && typeof pool.query === 'function' ? pool : null + } catch { + return null + } + } + + get isPgAsyncMode() { + return this._resolvePgPool() !== null + } + + _ensureSqliteStatements() { + const db = this._resolveDb() + if (!db || db.engine === 'postgres' || typeof db.prepare !== 'function') return null + if (this._stmtDb !== db) { + this._stmtDb = db + this._listSinceStmt = db.prepare(SQLITE_LIST_SINCE_SQL) + this._insertStmt = db.prepare(SQLITE_INSERT_SQL) + this._pruneStmt = db.prepare(SQLITE_PRUNE_SQL) + } + return db + } + + _reportError(op, err) { + if (this._onError) { + try { + this._onError(op, err) + } catch {} + } + } + + /** + * Synchronous SQLite read. Returns `[]` in PostgreSQL async mode to guarantee + * zero `Atomics.wait` blocking on the event loop; use `listSinceAsync` for PG. + */ + listSince(platform, sinceMs) { + if (this.isPgAsyncMode) return [] + const plat = cleanText(platform) + const since = cleanTimestampMs(sinceMs, 0) + if (!plat) return [] + const db = this._ensureSqliteStatements() + if (!db) return [] + return this._listSinceStmt.all(plat, since).map(decodeDailySessionCreationRow).filter(Boolean) + } + + /** + * Async dual-DB read: uses `pgPool.query` when PostgreSQL is active, else SQLite. + */ + async listSinceAsync(platform, sinceMs) { + const pgPool = this._resolvePgPool() + if (pgPool) return listDailySessionCreationsSincePgAsync(pgPool, platform, sinceMs) + return this.listSince(platform, sinceMs) + } + + /** + * Persist a committed session creation. + * SQLite executes synchronously; PostgreSQL fires non-blocking `pgPool.query` + * so hot paths never block with `Atomics.wait`. + */ + recordCreation(record) { + const norm = normalizeDailySessionCreationRecord(record) + if (!norm) return { inserted: false, async: false } + const pgPool = this._resolvePgPool() + if (pgPool) { + recordDailySessionCreationPgAsync(pgPool, norm).catch((err) => this._reportError('recordCreation', err)) + return { inserted: true, async: true } + } + const db = this._ensureSqliteStatements() + if (!db) return { inserted: false, async: false } + const info = this._insertStmt.run( + norm.platform, + norm.account_key, + norm.day_key, + norm.session_id, + norm.vm_id, + norm.created_at, + ) + return { inserted: Number(info?.changes || 0) > 0, async: false } + } + + /** + * Awaitable dual-DB persistence for tests, startup verification, or callers that + * need durability confirmation on PostgreSQL. + */ + async recordCreationAsync(record) { + const norm = normalizeDailySessionCreationRecord(record) + if (!norm) return { inserted: false } + const pgPool = this._resolvePgPool() + if (pgPool) return recordDailySessionCreationPgAsync(pgPool, norm) + const res = this.recordCreation(norm) + return { inserted: res.inserted } + } + + /** + * Prune records older than `beforeMs`. Non-blocking on PostgreSQL, sync on SQLite. + */ + pruneBefore(platform, beforeMs) { + const plat = cleanText(platform) + const cutoff = cleanTimestampMs(beforeMs) + if (!plat || cutoff == null) return 0 + const pgPool = this._resolvePgPool() + if (pgPool) { + pruneDailySessionCreationsBeforePgAsync(pgPool, plat, cutoff).catch((err) => + this._reportError('pruneBefore', err), + ) + return 0 + } + const db = this._ensureSqliteStatements() + if (!db) return 0 + const info = this._pruneStmt.run(plat, cutoff) + return Number(info?.changes || 0) + } + + /** + * Awaitable dual-DB prune. + */ + async pruneBeforeAsync(platform, beforeMs) { + const plat = cleanText(platform) + const cutoff = cleanTimestampMs(beforeMs) + if (!plat || cutoff == null) return 0 + const pgPool = this._resolvePgPool() + if (pgPool) return pruneDailySessionCreationsBeforePgAsync(pgPool, plat, cutoff) + return this.pruneBefore(plat, cutoff) + } +} diff --git a/src/lib/pool/availability.mjs b/src/lib/pool/availability.mjs index 71cf5f716a..76861721b1 100644 --- a/src/lib/pool/availability.mjs +++ b/src/lib/pool/availability.mjs @@ -578,6 +578,7 @@ export function resolveScheduleState({ circuit = null, seats = null, sessions = null, + dailySessions = null, now = Date.now(), } = {}) { const record = vm || { @@ -594,6 +595,7 @@ export function resolveScheduleState({ circuit, seats, sessions, + dailySessions, now, }) } diff --git a/src/lib/pool/daily-session-gate.mjs b/src/lib/pool/daily-session-gate.mjs new file mode 100644 index 0000000000..f3047b5ff1 --- /dev/null +++ b/src/lib/pool/daily-session-gate.mjs @@ -0,0 +1,867 @@ +/** + * Per-account VM daily new session creation control gate (Anthropic-first). + * + * Single source of truth for: + * - `routing.quota.daily_session_gate` normalization, merge & strict validation + * - Anthropic account tier resolution (`resolveAnthropicSessionTier`) + * - Account session ledger key (`resolveAccountSessionKey`) + * - Effective per-VM daily policy (`resolveEffectiveDailySessionPolicy`) + * - Scheduler lease gating predicate (`shouldGateSchedulerLease`) + * - In-memory reservation + dual-DB persistent daily ledger (`DailySessionGate`) + */ +import crypto from 'node:crypto' +import { validTimezone, zonedDayStartMs, zonedParts } from '../core/timezone.mjs' +import { DailySessionGateRepo } from '../db/repos/daily-session-gate-repo.mjs' +import { normalizeSubscriptionType } from '../oauth/oauth-identity.mjs' +import { isCodexVm } from '../vm/vm-kind.mjs' +import { isProRateLimitTier } from './claude-tier.mjs' +import { vmQuotaOverrideOf } from './vm-quota-override.mjs' + +export const DAILY_SESSION_PLATFORM_ANTHROPIC = 'anthropic' +export const DAILY_SESSION_TIERS = Object.freeze(['default', 'pro', 'max_5x', 'max_20x', 'team', 'enterprise']) +export const DAILY_SESSION_LIMIT_MAX = 100_000 + +const DAILY_SESSION_TIER_SET = new Set(DAILY_SESSION_TIERS) +const ALLOWED_GATE_KEYS = new Set(['enabled', 'reset_timezone', 'tier_limits']) + +export const DEFAULT_DAILY_SESSION_GATE = Object.freeze({ + enabled: false, + reset_timezone: 'UTC', + tier_limits: Object.freeze({ + default: 0, + pro: 0, + max_5x: 0, + max_20x: 0, + team: 0, + enterprise: 0, + }), +}) + +const MAX_20X_TIER_RE = /(?:^|_)claude_max_20x(?:_|$)|(?:^|_)max_20x(?:_|$)|^20x$/i +const MAX_5X_TIER_RE = /(?:^|_)claude_max_5x(?:_|$)|(?:^|_)max_5x(?:_|$)|^5x$/i +const ENTERPRISE_TIER_RE = /(?:^|_)claude_enterprise(?:_|$)/i +const TEAM_TIER_RE = /(?:^|_)claude_team(?:_|$)/i + +const DEFAULT_RETENTION_DAYS = 7 +const DEFAULT_PENDING_TTL_MS = 180_000 +const PRUNE_MIN_INTERVAL_MS = 3_600_000 + +function quotaValidationError(message) { + const error = new TypeError(message) + error.code = 'invalid_quota_config' + return error +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +function normalizeLimitInt(value) { + if (typeof value !== 'number' || !Number.isInteger(value)) return 0 + if (value < 0 || value > DAILY_SESSION_LIMIT_MAX) return 0 + return value +} + +function pad2(n) { + return String(n).padStart(2, '0') +} + +function extractGateSource(raw) { + if (!isPlainObject(raw)) return {} + if (isPlainObject(raw.quota?.daily_session_gate)) return raw.quota.daily_session_gate + if (isPlainObject(raw.daily_session_gate)) return raw.daily_session_gate + return raw +} + +/** Whether `vm` belongs to Anthropic / Claude (skips Codex / OpenAI / Gemini). */ +export function isAnthropicSessionVm(vm) { + if (!vm || typeof vm !== 'object') return false + if (isCodexVm(vm)) return false + const provider = String(vm.provider || '') + .trim() + .toLowerCase() + if (provider && provider !== 'anthropic' && provider !== 'claude') return false + const platform = String(vm.platform || '') + .trim() + .toLowerCase() + if (platform && platform !== 'anthropic' && platform !== 'claude') return false + const family = String(vm.family || '') + .trim() + .toLowerCase() + if (family && family !== 'anthropic' && family !== 'claude') return false + return true +} + +/** Lenient canonicalization of `routing.quota.daily_session_gate`. */ +export function normalizeDailySessionGate(raw) { + const src = isPlainObject(raw) ? raw : {} + const rawLimits = isPlainObject(src.tier_limits) ? src.tier_limits : {} + const tierLimits = {} + for (const tier of DAILY_SESSION_TIERS) { + tierLimits[tier] = normalizeLimitInt(rawLimits[tier]) + } + return { + enabled: src.enabled === true, + reset_timezone: validTimezone(src.reset_timezone) || 'UTC', + tier_limits: tierLimits, + } +} + +/** Deep-merge a partial `daily_session_gate` patch over an existing config. */ +export function mergeDailySessionGate(prev, patch) { + const base = normalizeDailySessionGate(prev) + if (!isPlainObject(patch)) return base + const nextLimits = { ...base.tier_limits } + if (isPlainObject(patch.tier_limits)) { + for (const tier of DAILY_SESSION_TIERS) { + if (Object.hasOwn(patch.tier_limits, tier)) { + nextLimits[tier] = normalizeLimitInt(patch.tier_limits[tier]) + } + } + } + return { + enabled: Object.hasOwn(patch, 'enabled') ? patch.enabled === true : base.enabled, + reset_timezone: Object.hasOwn(patch, 'reset_timezone') + ? validTimezone(patch.reset_timezone) || base.reset_timezone + : base.reset_timezone, + tier_limits: nextLimits, + } +} + +/** + * Strict validator for `routing.quota.daily_session_gate` patches. + * Throws `TypeError` with `err.code = 'invalid_quota_config'` on any violation. + */ +export function validateDailySessionGatePatch(patch) { + if (!isPlainObject(patch)) { + throw quotaValidationError('quota.daily_session_gate 必须是对象') + } + for (const key of Object.keys(patch)) { + if (!ALLOWED_GATE_KEYS.has(key)) { + throw quotaValidationError(`quota.daily_session_gate.${key} 不受支持`) + } + } + if (Object.hasOwn(patch, 'enabled') && typeof patch.enabled !== 'boolean') { + throw quotaValidationError('quota.daily_session_gate.enabled 必须是布尔值') + } + if (Object.hasOwn(patch, 'reset_timezone')) { + if (typeof patch.reset_timezone !== 'string' || !validTimezone(patch.reset_timezone)) { + throw quotaValidationError('quota.daily_session_gate.reset_timezone 必须是有效的 IANA 时区') + } + } + if (Object.hasOwn(patch, 'tier_limits')) { + if (!isPlainObject(patch.tier_limits)) { + throw quotaValidationError('quota.daily_session_gate.tier_limits 必须是对象') + } + for (const [tier, value] of Object.entries(patch.tier_limits)) { + if (!DAILY_SESSION_TIER_SET.has(tier)) { + throw quotaValidationError(`quota.daily_session_gate.tier_limits.${tier} 不是有效的等级`) + } + if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > DAILY_SESSION_LIMIT_MAX) { + throw quotaValidationError( + `quota.daily_session_gate.tier_limits.${tier} 必须是 0 到 ${DAILY_SESSION_LIMIT_MAX} 之间的整数`, + ) + } + } + } +} + +/** + * Resolve an Anthropic account's session-gate tier key. + * Precedence: rate_limit_tier -> subscription_type -> default_claude_ai veto -> account_tier -> 'default'. + */ +export function resolveAnthropicSessionTier(vm) { + if (!vm || typeof vm !== 'object') return 'default' + + const rateLimitTier = String(vm?.claude?.rate_limit_tier || vm?.rate_limit_tier || '').trim() + if (rateLimitTier) { + if (MAX_20X_TIER_RE.test(rateLimitTier)) return 'max_20x' + if (MAX_5X_TIER_RE.test(rateLimitTier)) return 'max_5x' + if (ENTERPRISE_TIER_RE.test(rateLimitTier)) return 'enterprise' + if (TEAM_TIER_RE.test(rateLimitTier)) return 'team' + } + + const rawSub = vm?.claude?.subscription_type || vm?.subscription_type || '' + const sub = normalizeSubscriptionType(rawSub) || String(rawSub).trim().toLowerCase() + if (sub === 'enterprise') return 'enterprise' + if (sub === 'team') return 'team' + if (sub === 'pro') return 'pro' + if (sub === 'max') return 'max_5x' + if (sub === 'free') return 'default' + + if (isProRateLimitTier(rateLimitTier)) return 'pro' + + const accountTier = String(vm?.claude?.account_tier || vm?.account_tier || '') + .trim() + .toLowerCase() + if (accountTier === 'max') return 'max_5x' + if (accountTier === 'pro') return 'pro' + + return 'default' +} + +/** Canonical account key for daily session accounting (shared across VMs of the same Anthropic account). */ +export function resolveAccountSessionKey(vm) { + return String(vm?.claude?.account_uuid || vm?.account_uuid || '').trim() || String(vm?.id || '').trim() +} + +/** Resolve the inherited global tier cap for `vm` (ignoring per-VM override). */ +export function resolveInheritedDailySessionLimit(vm, gateConfig) { + if (!isAnthropicSessionVm(vm)) return 0 + const gate = normalizeDailySessionGate(gateConfig) + if (!gate.enabled) return 0 + const tierKey = resolveAnthropicSessionTier(vm) + return gate.tier_limits[tierKey] ?? 0 +} + +/** + * Resolve effective daily session creation policy for `vm`. + * - Per-VM `daily_session_limit === 0`: explicit unlimited override (exempts VM even when global gate enabled). + * - Per-VM `daily_session_limit >= 1`: explicit cap override (enforced even when global gate disabled). + * - Absent / `null`: inherit global `tier_limits[tier_key]` when global gate enabled (0 = unlimited, never falls back to `default`). + */ +export function resolveEffectiveDailySessionPolicy(vm, gateConfig) { + const gate = normalizeDailySessionGate(gateConfig) + if (!isAnthropicSessionVm(vm)) { + return { + enabled: gate.enabled, + active: false, + limit: 0, + tier_key: 'default', + source: 'unsupported', + } + } + const tierKey = resolveAnthropicSessionTier(vm) + const override = vmQuotaOverrideOf(vm) + const hasOverride = + override != null && Object.hasOwn(override, 'daily_session_limit') && override.daily_session_limit != null + if (hasOverride) { + const limit = override.daily_session_limit + return { + enabled: gate.enabled, + active: limit > 0, + limit, + tier_key: tierKey, + source: 'override', + } + } + if (!gate.enabled) { + return { + enabled: false, + active: false, + limit: 0, + tier_key: tierKey, + source: 'disabled', + } + } + const limit = gate.tier_limits[tierKey] ?? 0 + return { + enabled: true, + active: limit > 0, + limit, + tier_key: tierKey, + source: 'tier', + } +} + +/** Compute the calendar-day window in `resetTimezone` containing `now`. */ +export function resolveDayWindow(now = Date.now(), resetTimezone = 'UTC') { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const timezone = validTimezone(resetTimezone) || 'UTC' + const parts = zonedParts(ts, timezone) + const dayKey = `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}` + const dayStartMs = zonedDayStartMs(ts, timezone, 0) + const resetAtMs = zonedDayStartMs(ts, timezone, 1) + return { + dayKey, + dayStartMs, + resetAtMs, + resetAt: new Date(resetAtMs).toISOString(), + timezone, + } +} + +/** + * Determine whether a scheduler lease represents a new primary Anthropic session + * that should be governed by the daily session creation gate. + */ +export function shouldGateSchedulerLease(req, res) { + if (res?.selected_node?.node_type !== 'claude_vm') return false + if (req?.is_ephemeral_probe) return false + if (req?.parent_session_id) return false + const why = res?.explain?.affinity?.why + if (why === 'subagent_follow_parent') return false + if (why === 'session_hit') return false + if (why === 'session_hit_after_wait') return false + if (req?.is_admin_diagnostic && req?.pin_node_key) return false + const sessionId = typeof req?.session_id === 'string' ? req.session_id.trim() : req?.session_id + return Boolean(sessionId) +} + +export class DailySessionGate { + constructor(options = {}) { + this._platform = + String(options.platform || DAILY_SESSION_PLATFORM_ANTHROPIC).trim() || DAILY_SESSION_PLATFORM_ANTHROPIC + this._getRoutingConfig = typeof options.getRoutingConfig === 'function' ? options.getRoutingConfig : null + const initialSource = this._getRoutingConfig + ? extractGateSource(this._getRoutingConfig()) + : extractGateSource(options.config) + this._config = normalizeDailySessionGate(initialSource) + this._repo = + options.repo || + new DailySessionGateRepo({ + db: options.db, + pgPool: options.pgPool, + onError: options.onError, + }) + this._retentionMs = Math.max(1, Number(options.retentionDays ?? DEFAULT_RETENTION_DAYS)) * 86_400_000 + this._pendingTtlMs = Math.max(1_000, Number(options.pendingTtlMs ?? DEFAULT_PENDING_TTL_MS)) + this._window = null + /** @type {Map>} accountKey -> Map */ + this._committed = new Map() + /** @type {Map} */ + this._pending = new Map() + /** @type {Map>>} accountKey -> Map> (current window only) */ + this._pendingByAccount = new Map() + this._lastPrunedAt = 0 + this._hydrationPromise = null + } + + getConfig() { + this._syncConfig(Date.now()) + return { + enabled: this._config.enabled, + reset_timezone: this._config.reset_timezone, + tier_limits: { ...this._config.tier_limits }, + } + } + + whenReady() { + return this._hydrationPromise || Promise.resolve() + } + + rebind(db, { pgPool } = {}) { + this._repo?.rebind?.(db, { pgPool }) + this._committed.clear() + this._window = null + } + + _syncConfig(now) { + if (!this._getRoutingConfig) return false + const next = normalizeDailySessionGate(extractGateSource(this._getRoutingConfig())) + return this._applyConfig(next, now).timezoneChanged + } + + _applyConfig(nextConfig, now) { + const prev = this._config + const timezoneChanged = prev.reset_timezone !== nextConfig.reset_timezone + const changed = + timezoneChanged || + prev.enabled !== nextConfig.enabled || + DAILY_SESSION_TIERS.some((tier) => prev.tier_limits[tier] !== nextConfig.tier_limits[tier]) + this._config = nextConfig + if (timezoneChanged && this._window) { + this._handleTimezoneChange(now) + } + return { changed, timezoneChanged } + } + + reloadConfig(routingOrGate, now = Date.now()) { + const next = normalizeDailySessionGate(extractGateSource(routingOrGate)) + const { changed, timezoneChanged } = this._applyConfig(next, now) + return { + changed, + timezoneChanged, + config: { + enabled: this._config.enabled, + reset_timezone: this._config.reset_timezone, + tier_limits: { ...this._config.tier_limits }, + }, + } + } + + async reloadConfigAsync(routingOrGate, now = Date.now()) { + const res = this.reloadConfig(routingOrGate, now) + if (res.timezoneChanged && this._hydrationPromise) { + await this._hydrationPromise + } + return res + } + + _handleTimezoneChange(now) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const nextWindow = resolveDayWindow(ts, this._config.reset_timezone) + this._window = nextWindow + this._pruneInMemoryCommitted(nextWindow.dayStartMs) + this._rebuildPendingIndex(nextWindow.dayStartMs) + if (this._repo?.isPgAsyncMode) { + this._hydrationPromise = this.hydrateAsync(ts).catch(() => ({ loaded: 0, window: nextWindow })) + } else if (typeof this._repo?.listSince === 'function') { + try { + const rows = this._repo.listSince(this._platform, nextWindow.dayStartMs) + this._mergeRows(rows, nextWindow.dayStartMs) + } catch {} + } + } + + _ensureWindow(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + this._syncConfig(ts) + const nextWindow = resolveDayWindow(ts, this._config.reset_timezone) + this._sweepExpiredPending(ts) + if (!this._window) { + this._window = nextWindow + return this._window + } + if (this._window.timezone !== nextWindow.timezone) { + this._handleTimezoneChange(ts) + return this._window + } + if (this._window.dayStartMs !== nextWindow.dayStartMs) { + this._window = nextWindow + this._pruneInMemoryCommitted(nextWindow.dayStartMs) + this._rebuildPendingIndex(nextWindow.dayStartMs) + this._maybePruneDb(ts) + } + return this._window + } + + _pruneInMemoryCommitted(dayStartMs) { + for (const [accountKey, sessions] of this._committed.entries()) { + for (const [sessionId, createdAt] of sessions.entries()) { + if (createdAt < dayStartMs) sessions.delete(sessionId) + } + if (sessions.size === 0) this._committed.delete(accountKey) + } + } + + _rebuildPendingIndex(dayStartMs) { + this._pendingByAccount.clear() + for (const entry of this._pending.values()) { + if (entry.reservedAt < dayStartMs) continue + entry.dayStartMs = dayStartMs + if (this._isCommittedInMemory(entry.accountKey, entry.sessionId)) continue + this._indexPendingEntry(entry) + } + } + + _indexPendingEntry(entry) { + let bySession = this._pendingByAccount.get(entry.accountKey) + if (!bySession) { + bySession = new Map() + this._pendingByAccount.set(entry.accountKey, bySession) + } + let tokens = bySession.get(entry.sessionId) + if (!tokens) { + tokens = new Set() + bySession.set(entry.sessionId, tokens) + } + tokens.add(entry.leaseToken) + } + + _unindexPendingEntry(entry) { + const bySession = this._pendingByAccount.get(entry.accountKey) + if (!bySession) return + const tokens = bySession.get(entry.sessionId) + if (!tokens) return + tokens.delete(entry.leaseToken) + if (tokens.size === 0) bySession.delete(entry.sessionId) + if (bySession.size === 0) this._pendingByAccount.delete(entry.accountKey) + } + + _clearPendingSession(accountKey, sessionId) { + const bySession = this._pendingByAccount.get(accountKey) + if (!bySession) return + const tokens = bySession.get(sessionId) + if (tokens) { + for (const token of tokens) { + this._pending.delete(token) + } + } + bySession.delete(sessionId) + if (bySession.size === 0) this._pendingByAccount.delete(accountKey) + } + + _sweepExpiredPending(now) { + if (this._pending.size === 0) return + for (const [token, entry] of this._pending.entries()) { + if (now - entry.reservedAt >= this._pendingTtlMs) { + this._pending.delete(token) + this._unindexPendingEntry(entry) + } + } + } + + _maybePruneDb(now) { + if (!this._repo || typeof this._repo.pruneBefore !== 'function') return + if (this._lastPrunedAt && now - this._lastPrunedAt < PRUNE_MIN_INTERVAL_MS) return + this._lastPrunedAt = now + try { + this._repo.pruneBefore(this._platform, now - this._retentionMs) + } catch {} + } + + _isCommittedInMemory(accountKey, sessionId) { + return Boolean(this._committed.get(accountKey)?.has(sessionId)) + } + + _recordCommittedInMemory(accountKey, sessionId, createdAt) { + let sessions = this._committed.get(accountKey) + if (!sessions) { + sessions = new Map() + this._committed.set(accountKey, sessions) + } + if (sessions.has(sessionId)) return false + sessions.set(sessionId, createdAt) + return true + } + + _mergeRows(rows, dayStartMs) { + let loaded = 0 + for (const row of rows || []) { + const accountKey = String(row?.account_key || '').trim() + const sessionId = String(row?.session_id || '').trim() + const createdAt = Number(row?.created_at) + if (!accountKey || !sessionId || !Number.isFinite(createdAt)) continue + if (createdAt < dayStartMs) continue + if (this._recordCommittedInMemory(accountKey, sessionId, Math.floor(createdAt))) { + loaded += 1 + this._clearPendingSession(accountKey, sessionId) + } + } + return loaded + } + + /** Synchronous startup / re-hydration for SQLite. */ + hydrate(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + this._pruneInMemoryCommitted(window.dayStartMs) + if (!this._repo || typeof this._repo.listSince !== 'function') { + return { loaded: 0, window } + } + const rows = this._repo.listSince(this._platform, window.dayStartMs) + const loaded = this._mergeRows(rows, window.dayStartMs) + this._rebuildPendingIndex(window.dayStartMs) + return { loaded, window } + } + + /** Async startup / re-hydration for PostgreSQL 18 (and SQLite fallback). */ + async hydrateAsync(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + this._pruneInMemoryCommitted(window.dayStartMs) + if (!this._repo || typeof this._repo.listSinceAsync !== 'function') { + return { loaded: 0, window } + } + const rows = await this._repo.listSinceAsync(this._platform, window.dayStartMs) + const activeWindow = this._window || window + const loaded = this._mergeRows(rows, activeWindow.dayStartMs) + this._rebuildPendingIndex(activeWindow.dayStartMs) + return { loaded, window: activeWindow } + } + + _usedCount(accountKey) { + return this._committed.get(accountKey)?.size || 0 + } + + _pendingCount(accountKey) { + return this._pendingByAccount.get(accountKey)?.size || 0 + } + + _buildStatus(vm, window) { + const policy = resolveEffectiveDailySessionPolicy(vm, this._config) + if (policy.source === 'unsupported') { + return { + enabled: policy.enabled, + active: false, + used: 0, + pending: 0, + limit: 0, + remaining: null, + blocked: false, + day_key: window.dayKey, + timezone: window.timezone, + reset_at: window.resetAt, + reset_at_ms: window.resetAtMs, + tier_key: policy.tier_key, + source: 'unsupported', + } + } + const accountKey = resolveAccountSessionKey(vm) + const used = accountKey ? this._usedCount(accountKey) : 0 + const pending = accountKey ? this._pendingCount(accountKey) : 0 + const limit = policy.limit + const active = policy.active && limit > 0 + const remaining = active ? Math.max(0, limit - used - pending) : null + const blocked = active && used + pending >= limit + return { + enabled: policy.enabled, + active, + used, + pending, + limit, + remaining, + blocked, + day_key: window.dayKey, + timezone: window.timezone, + reset_at: window.resetAt, + reset_at_ms: window.resetAtMs, + tier_key: policy.tier_key, + source: policy.source, + } + } + + inheritedLimitForVm(vm) { + this._syncConfig(Date.now()) + return resolveInheritedDailySessionLimit(vm, this._config) + } + + statusForVm(vm, now = Date.now()) { + const window = this._ensureWindow(now) + return this._buildStatus(vm, window) + } + + isVmNewSessionsBlocked(vm, now = Date.now()) { + return this.statusForVm(vm, now).blocked + } + + hasCommittedSession(vm, sessionId, now = Date.now()) { + if (!isAnthropicSessionVm(vm)) return false + const sid = String(sessionId || '').trim() + if (!sid) return false + this._ensureWindow(now) + const accountKey = resolveAccountSessionKey(vm) + return accountKey ? this._isCommittedInMemory(accountKey, sid) : false + } + + canAcceptNewSession(vm, sessionId, now = Date.now()) { + const window = this._ensureWindow(now) + const status = this._buildStatus(vm, window) + if (!isAnthropicSessionVm(vm) || !status.active) { + return { ok: true, reason: null, status } + } + const sid = String(sessionId || '').trim() + const accountKey = resolveAccountSessionKey(vm) + if ( + sid && + accountKey && + (this._isCommittedInMemory(accountKey, sid) || this._pendingByAccount.get(accountKey)?.has(sid)) + ) { + return { ok: true, reason: null, status } + } + if (status.blocked) { + return { ok: false, reason: 'daily_session_limit', status } + } + return { ok: true, reason: null, status } + } + + /** + * Atomically check and reserve an in-memory pending slot for a new primary Anthropic session. + * - Already-committed or already-pending `sessionId` for the same account is allowed without consuming another slot. + * - When `limit === 0` or gate disabled, still tracks the lease token so `commitReservation` records the session for observability & mid-day enable. + */ + tryReserveNewSession({ vm, sessionId, leaseToken, now = Date.now() } = {}) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + if (!isAnthropicSessionVm(vm)) { + return { + ok: true, + reserved: false, + duplicate: false, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: leaseToken || null, + status: this._buildStatus(vm, window), + } + } + + const accountKey = resolveAccountSessionKey(vm) + const sid = String(sessionId || '').trim() + if (!accountKey || !sid) { + return { + ok: true, + reserved: false, + duplicate: false, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: leaseToken || null, + status: this._buildStatus(vm, window), + } + } + + const token = String(leaseToken || '').trim() || crypto.randomUUID() + const existingToken = this._pending.get(token) + if (existingToken && existingToken.accountKey === accountKey && existingToken.sessionId === sid) { + return { + ok: true, + reserved: false, + duplicate: true, + tracked: true, + reason: null, + newlyCapped: false, + leaseToken: token, + status: this._buildStatus(vm, window), + } + } + if (existingToken) { + this._pending.delete(token) + this._unindexPendingEntry(existingToken) + } + + const beforeStatus = this._buildStatus(vm, window) + + // Already committed today -> never double-count or reject. + if (this._isCommittedInMemory(accountKey, sid)) { + return { + ok: true, + reserved: false, + duplicate: true, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + + const alreadyPending = Boolean(this._pendingByAccount.get(accountKey)?.has(sid)) + if (beforeStatus.active && beforeStatus.blocked && !alreadyPending) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_limit', + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + + const entry = { + leaseToken: token, + accountKey, + vmId: String(vm?.id || accountKey), + sessionId: sid, + reservedAt: ts, + dayStartMs: window.dayStartMs, + vm, + } + this._pending.set(token, entry) + this._indexPendingEntry(entry) + + const afterStatus = this._buildStatus(vm, window) + return { + ok: true, + reserved: !alreadyPending, + duplicate: alreadyPending, + tracked: true, + reason: null, + newlyCapped: !beforeStatus.blocked && afterStatus.blocked, + leaseToken: token, + status: afterStatus, + } + } + + /** + * Commit a reserved (or directly supplied) new primary Anthropic session. + * Always records committed primary sessions even when `limit === 0` or global gate is disabled + * so observability and mid-day enabling remain accurate; O(1) idempotent dedup prevents duplicate DB writes. + */ + commitReservation(leaseToken, { vm = null, sessionId = null, now = Date.now() } = {}) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + const token = String(leaseToken || '').trim() + const pendingEntry = token ? this._pending.get(token) || null : null + const targetVm = vm || pendingEntry?.vm || null + + if (pendingEntry) { + this._pending.delete(token) + this._unindexPendingEntry(pendingEntry) + } + + if (targetVm && !isAnthropicSessionVm(targetVm)) { + return { + recorded: false, + duplicate: false, + newlyCapped: false, + vmId: targetVm?.id || null, + accountKey: null, + status: this._buildStatus(targetVm, window), + } + } + + const accountKey = (targetVm ? resolveAccountSessionKey(targetVm) : '') || pendingEntry?.accountKey || '' + const sid = String(sessionId || pendingEntry?.sessionId || '').trim() + const vmId = String(targetVm?.id || pendingEntry?.vmId || accountKey).trim() || null + + if (!accountKey || !sid) { + return { + recorded: false, + duplicate: false, + newlyCapped: false, + vmId, + accountKey: accountKey || null, + status: targetVm ? this._buildStatus(targetVm, window) : null, + } + } + + const beforeStatus = targetVm ? this._buildStatus(targetVm, window) : null + const inserted = this._recordCommittedInMemory(accountKey, sid, ts) + if (inserted) { + this._clearPendingSession(accountKey, sid) + try { + this._repo?.recordCreation?.({ + platform: this._platform, + accountKey, + dayKey: window.dayKey, + sessionId: sid, + vmId: vmId || accountKey, + createdAt: ts, + }) + } catch {} + } + + const afterStatus = targetVm ? this._buildStatus(targetVm, window) : null + return { + recorded: inserted, + duplicate: !inserted, + newlyCapped: Boolean(beforeStatus && afterStatus && !beforeStatus.blocked && afterStatus.blocked), + vmId, + accountKey, + status: afterStatus, + } + } + + /** Release a pre-commit pending reservation without counting it as a created session. */ + releaseReservation(leaseToken, now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + const token = String(leaseToken || '').trim() + if (!token) { + return { released: false, uncapped: false, vmId: null, accountKey: null, status: null } + } + const entry = this._pending.get(token) + if (!entry) { + return { released: false, uncapped: false, vmId: null, accountKey: null, status: null } + } + const beforeBlocked = entry.vm ? this._buildStatus(entry.vm, window).blocked : false + this._pending.delete(token) + this._unindexPendingEntry(entry) + const afterStatus = entry.vm ? this._buildStatus(entry.vm, window) : null + return { + released: true, + uncapped: Boolean(beforeBlocked && afterStatus && !afterStatus.blocked), + vmId: entry.vmId, + accountKey: entry.accountKey, + status: afterStatus, + } + } +} + +export function createDailySessionGate(options = {}) { + return new DailySessionGate(options) +} diff --git a/src/lib/pool/failover-runner.mjs b/src/lib/pool/failover-runner.mjs index 53b9b1a651..c7f2f8da2d 100644 --- a/src/lib/pool/failover-runner.mjs +++ b/src/lib/pool/failover-runner.mjs @@ -336,6 +336,7 @@ const TERMINAL_SWITCH_ERROR_CODES = new Set([ 'session_queue_timeout', 'session_node_busy', 'fable_requires_max', + 'daily_session_limit', 'pool_rate_limited', ]) diff --git a/src/lib/pool/pool-scheduler.mjs b/src/lib/pool/pool-scheduler.mjs index 37accf723b..c51f8cde16 100644 --- a/src/lib/pool/pool-scheduler.mjs +++ b/src/lib/pool/pool-scheduler.mjs @@ -26,6 +26,7 @@ import { import { listQuotaFromHeaders, noResetRejectExpired } from './quota-window.mjs' import { hardBlockOf } from './rate-limit-service.mjs' import { unitCircuit } from './unit-circuit.mjs' +import { validateDailySessionGatePatch } from './daily-session-gate.mjs' import { isCodexVm } from '../vm/vm-kind.mjs' import { setResetPriorityEnabled } from './credential-weight.mjs' import { PLATFORM_SCOPE } from '../admin/resource-owner.mjs' @@ -192,6 +193,9 @@ export function validateQuotaRoutingPatch(body = {}, currentQuota = {}) { if (!quota || typeof quota !== 'object' || Array.isArray(quota)) { throw quotaValidationError('quota 必须是对象') } + if (Object.prototype.hasOwnProperty.call(quota, 'daily_session_gate')) { + validateDailySessionGatePatch(quota.daily_session_gate) + } const hasNew = Object.prototype.hasOwnProperty.call(quota, 'exhaustion_guard_new_session') const hasStop = Object.prototype.hasOwnProperty.call(quota, 'exhaustion_guard_stop') if (!hasNew && !hasStop) return diff --git a/src/lib/pool/schedule-state.mjs b/src/lib/pool/schedule-state.mjs index a9f8ef8d1f..ff97bde752 100644 --- a/src/lib/pool/schedule-state.mjs +++ b/src/lib/pool/schedule-state.mjs @@ -80,6 +80,7 @@ const RESTRICTED_NEW_SESSION = [ { match: /^gate_(5h|7d)_draining$/, text: '临近闸线', soft: true }, { match: /^seats_full$/, text: '席位满', soft: false }, { match: /^sessions_full$/, text: '对话窗口满', soft: false }, + { match: /^daily_session_limit$/, text: '今日新会话上限', soft: false }, // Machine memory (host-memory-pressure.mjs): tight still takes new conversations when no machine has room. ] @@ -358,6 +359,7 @@ export function resolveSlotState({ circuit = null, seats = null, sessions = null, + dailySessions = null, now = Date.now(), } = {}) { const textOf = (reason) => stateOfReason(reason)?.text || null @@ -435,5 +437,12 @@ export function resolveSlotState({ if (sessionMax > 0 && (Number(sessions?.active) || 0) >= sessionMax) { return restricted('sessions_full', null, 'new_session') } + const dailyLimit = Number(dailySessions?.limit) || 0 + const dailyBlocked = + dailySessions?.blocked === true || + (dailyLimit > 0 && (Number(dailySessions?.used) || 0) + (Number(dailySessions?.pending) || 0) >= dailyLimit) + if (dailyBlocked) { + return restricted('daily_session_limit', dailySessions?.reset_at_ms || null, 'new_session', false) + } return { ...base, schedule_state: 'on' } } diff --git a/src/lib/pool/vm-quota-override.mjs b/src/lib/pool/vm-quota-override.mjs index 9caca5a3b4..f04182ce8d 100644 --- a/src/lib/pool/vm-quota-override.mjs +++ b/src/lib/pool/vm-quota-override.mjs @@ -14,6 +14,7 @@ const FIELDS = { block_on_5h: { kind: 'bool' }, block_on_7d: { kind: 'bool' }, weekly_split: { kind: 'bool' }, + daily_session_limit: { kind: 'int', min: 0, max: 100_000 }, } export const VM_QUOTA_FIELDS = Object.keys(FIELDS) @@ -23,6 +24,12 @@ function parseField(key, value) { if (spec.kind === 'bool') { return typeof value === 'boolean' ? { ok: true, value } : { ok: false, error: `${key} must be a boolean` } } + if (spec.kind === 'int') { + if (typeof value !== 'number' || !Number.isInteger(value) || value < spec.min || value > spec.max) { + return { ok: false, error: `${key} must be an integer from ${spec.min} to ${spec.max}` } + } + return { ok: true, value } + } const n = typeof value === 'number' ? value : Number.NaN if (!Number.isFinite(n) || n < 0.3 || n > 1) return { ok: false, error: `${key} must be a ratio from 0.3 to 1` } return { ok: true, value: n } @@ -50,7 +57,7 @@ export function parseVmQuotaOverride(raw) { /** Lenient read of the stored record: hand-edited invalid fields fall back to the global value. */ export function vmQuotaOverrideOf(vm) { - const raw = vm?.policy?.quota + const raw = vm?.policy?.quota ?? vm?.quota_override if (!raw || typeof raw !== 'object') return null const out = {} for (const key of VM_QUOTA_FIELDS) { @@ -74,10 +81,13 @@ export function applyVmQuotaPolicy(policy, override) { next.limit_7d = override.limit_7d next.weekly_safety_ratio = override.limit_7d } + if (override.daily_session_limit != null) { + next.daily_session_limit = override.daily_session_limit + } return next } -/** Global `quota` block with the VM's block switches / weekly split applied. */ +/** Global `quota` block with the VM's block switches / weekly split / daily session cap applied. */ export function applyVmQuotaConfig(quota, override) { const base = quota && typeof quota === 'object' ? quota : {} if (!override) return base @@ -90,16 +100,39 @@ export function applyVmQuotaConfig(quota, override) { enabled: override.weekly_split, } } + if (override.daily_session_limit != null) { + next.daily_session_limit = override.daily_session_limit + } return next } -/** Panel view of the fields a VM can override, resolved from a policy + quota block. */ -export function vmQuotaView(policy, quota) { +function cleanDailySessionLimit(value) { + if (typeof value !== 'number' || !Number.isInteger(value)) return null + if (value < FIELDS.daily_session_limit.min || value > FIELDS.daily_session_limit.max) return null + return value +} + +/** + * Panel view of the fields a VM can override, resolved from a policy + quota block. + * Optional `extra` accepts either a number (`inheritedDailySessionLimit`) or + * `{ daily_session_limit, inherited_daily_session_limit }` for the inherited fallback. + */ +export function vmQuotaView(policy, quota, extra = null) { + const extraLimit = + typeof extra === 'number' + ? cleanDailySessionLimit(extra) + : cleanDailySessionLimit(extra?.daily_session_limit ?? extra?.inherited_daily_session_limit) + const dailySessionLimit = + cleanDailySessionLimit(quota?.daily_session_limit) ?? + cleanDailySessionLimit(policy?.daily_session_limit) ?? + extraLimit ?? + 0 return { limit_5h: Number(policy?.limit_5h ?? policy?.safety_ratio ?? 0.85), limit_7d: Number(policy?.limit_7d ?? policy?.weekly_safety_ratio ?? 0.8), block_on_5h: quota?.block_on_5h !== false, block_on_7d: quota?.block_on_7d !== false, weekly_split: weeklySplitConfig(quota || {}).enabled, + daily_session_limit: dailySessionLimit, } } diff --git a/src/lib/protocol/handle-agent-sessions.mjs b/src/lib/protocol/handle-agent-sessions.mjs index 43cd4a8eee..b856e27c43 100644 --- a/src/lib/protocol/handle-agent-sessions.mjs +++ b/src/lib/protocol/handle-agent-sessions.mjs @@ -139,6 +139,9 @@ export function createHandleAgentSessions(deps = {}) { stats = { requests: 0, errors: 0 }, getRoutingConfig = () => ({}), getPoolScheduler = () => null, + dailySessionGate = null, + getDailySessionGate = null, + onDailySessionGateChange = null, admitCragInference = null, resyncCragLicense = null, licenseInvalidRetryDelayMs = undefined, @@ -153,6 +156,8 @@ export function createHandleAgentSessions(deps = {}) { let rrCursor = 0 const getRouting = () => (typeof getRoutingConfig === 'function' ? getRoutingConfig() : deps.routingConfig) || {} + const resolveDailySessionGate = () => + typeof getDailySessionGate === 'function' ? getDailySessionGate() : dailySessionGate || null function resolveGroupRate(req) { const projected = req?.apiKeyRecord?._authProjection?.groupRateMultiplier @@ -448,26 +453,140 @@ export function createHandleAgentSessions(deps = {}) { } catch {} } - const selectedVm = (bound?.vmId && readySlots.find((vm) => vm.id === bound.vmId)) || pickSlot(readySlots) + const gate = resolveDailySessionGate() + const now = Date.now() + const sendDailySessionLimit429 = (statuses) => { + let earliestMs = null + let earliestIso = null + for (const st of statuses || []) { + const ms = Number(st?.reset_at_ms) + if (!Number.isFinite(ms) || ms <= 0) continue + if (earliestMs == null || ms < earliestMs) { + earliestMs = ms + earliestIso = st?.reset_at || new Date(ms).toISOString() + } + } + const retryAfterSec = earliestMs != null ? Math.max(1, Math.ceil((earliestMs - now) / 1000)) : 60 + const message = earliestIso + ? `Anthropic accounts have reached their daily new session limit; resets at ${earliestIso}` + : 'Anthropic accounts have reached their daily new session limit' + stats.errors++ + logBag.error_code = 'daily_session_limit' + logBag.error_message = message + logBag.final_state = 'rejected' + res.setHeader?.('retry-after', String(retryAfterSec)) + return json( + res, + 429, + makeError({ + type: ErrorType.RATE_LIMIT, + code: 'daily_session_limit', + message, + status: 429, + }).body, + ) + } + + const boundVm = bound?.vmId ? readySlots.find((vm) => vm.id === bound.vmId) || null : null + const boundCommitted = Boolean(boundVm && (!gate || gate.hasCommittedSession(boundVm, kernelSessionId, now))) + const committedVm = + !boundCommitted && gate + ? readySlots.find((vm) => gate.hasCommittedSession(vm, kernelSessionId, now)) || null + : null + let selectedVm = boundCommitted ? boundVm : committedVm + let dailyLeaseToken = null + let dailyCommitted = false + + const notifyDailyGateChange = (vm, event, status) => { + if (typeof onDailySessionGateChange !== 'function') return + try { + onDailySessionGateChange(vm, { event, status }) + } catch {} + } + + if (!selectedVm) { + if (gate) { + const eligibleSlots = [] + const blockedStatuses = [] + for (const vm of readySlots) { + const check = gate.canAcceptNewSession(vm, kernelSessionId, now) + if (check.ok) eligibleSlots.push(vm) + else if (check.status) blockedStatuses.push(check.status) + } + if (!eligibleSlots.length && blockedStatuses.length) { + return sendDailySessionLimit429(blockedStatuses) + } + let remaining = [...eligibleSlots] + while (remaining.length) { + const candidate = boundVm && remaining.some((vm) => vm.id === boundVm.id) ? boundVm : pickSlot(remaining) + const leaseToken = `agent:${logCtx.request_id}:${crypto.randomUUID()}` + const reserve = gate.tryReserveNewSession({ vm: candidate, sessionId: kernelSessionId, leaseToken, now }) + if (reserve.ok) { + selectedVm = candidate + dailyLeaseToken = reserve.tracked ? reserve.leaseToken || leaseToken : null + if (reserve.newlyCapped) { + notifyDailyGateChange(candidate, 'newly_capped', reserve.status) + } + break + } + if (reserve.status) blockedStatuses.push(reserve.status) + notifyDailyGateChange(candidate, 'newly_capped', reserve.status) + remaining = remaining.filter((vm) => vm.id !== candidate.id) + } + if (!selectedVm) { + return sendDailySessionLimit429(blockedStatuses) + } + } else { + selectedVm = boundVm || pickSlot(readySlots) + } + } + const accountId = selectedVm.claude?.account_uuid || selectedVm.account_uuid || selectedVm.id logBag.vm_id = selectedVm.id logBag.account_id = accountId - if (stickyRouter?.bind) { + let stickyBound = false + const bindStickySession = () => { + if (stickyBound || !stickyRouter?.bind) return + stickyBound = true try { stickyRouter.bind(stickyKey, { accountId, vmId: selectedVm.id, sessionId }) } catch {} } + const commitDailySession = () => { + bindStickySession() + if (!gate || !dailyLeaseToken || dailyCommitted) return + dailyCommitted = true + const committed = gate.commitReservation(dailyLeaseToken, { + vm: selectedVm, + sessionId: kernelSessionId, + now: Date.now(), + }) + if (committed?.newlyCapped) { + notifyDailyGateChange(selectedVm, 'newly_capped', committed.status) + } + } + const releaseDailySession = () => { + if (!gate || !dailyLeaseToken || dailyCommitted) return + const token = dailyLeaseToken + dailyLeaseToken = null + const released = gate.releaseReservation(token, Date.now()) + if (released?.uncapped) { + notifyDailyGateChange(selectedVm, 'uncapped', released.status) + } + } + const managedKey = req.apiKeyRecord || null if (managedKey) { - const gate = await acquireManagedKey(managedKey) - if (!gate.ok) { + const keyGate = await acquireManagedKey(managedKey) + if (!keyGate.ok) { + releaseDailySession() stats.errors++ - logBag.error_code = gate.code - logBag.error_message = gate.message + logBag.error_code = keyGate.code + logBag.error_message = keyGate.message logBag.final_state = 'rejected' - const err = makeApiKeyGateError(gate) + const err = makeApiKeyGateError(keyGate) if (err.headers) { for (const [k, v] of Object.entries(err.headers)) { if (v != null) res.setHeader?.(k, v) @@ -522,6 +641,7 @@ export function createHandleAgentSessions(deps = {}) { onHeaders: (status, upstreamHeaders) => { if (streamingHeadersSent || responseClosed(res)) return streamingHeadersSent = true + if ((status || 200) < 400) commitDailySession() const contentType = upstreamHeaders?.['content-type'] || 'application/x-ndjson; charset=utf-8' streamingContentType = contentType const headers = corsHeaders( @@ -569,6 +689,7 @@ export function createHandleAgentSessions(deps = {}) { } logBag.upstream_status = result?.status || null + if (result?.ok) commitDailySession() if (result?.terminalUsage) { recordTerminalBilling(result.terminalUsage) } @@ -640,6 +761,7 @@ export function createHandleAgentSessions(deps = {}) { } if (!responseClosed(res)) res.end() } finally { + releaseDailySession() clientAbort.settle() releaseManagedKey(managedKey) } diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 2362f9d6a6..3e6e903a9e 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -143,6 +143,7 @@ import { finalizeAssembledAssistantHop, mergeAssembledAssistantHop, incompleteAssistantClientError, + retryAfterSeconds, ErrorType, ErrorCode, } from '../core/errors.mjs' @@ -705,6 +706,26 @@ export function createHandleProtocol(deps) { }, } } + if (explicitCode === ErrorCode.DAILY_SESSION_LIMIT) { + logBag.error_code = ErrorCode.DAILY_SESSION_LIMIT + logBag.error_message = originalMessage || 'Anthropic accounts have reached their daily new session limit' + const retryAfter = + Number(result?.retryAfterSec) > 0 + ? Math.max(1, Math.ceil(Number(result.retryAfterSec))) + : retryAfterSeconds(result?.headers?.['retry-after']) + return { + status: 429, + ...(retryAfter ? { retryAfterSec: retryAfter } : {}), + body: { + type: 'error', + error: { + type: ErrorType.RATE_LIMIT, + code: ErrorCode.DAILY_SESSION_LIMIT, + message: logBag.error_message, + }, + }, + } + } if ( explicitCode === 'session_in_flight' || explicitCode === 'session_queue_full' || diff --git a/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index fe591e8e22..6d16a5c547 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -63,6 +63,7 @@ import { activeHoursOf, evaluateActiveHours } from '../pool/active-hours.mjs' import { endpointMatchesModel, stripPrefix } from '../pool/api-scheduler.mjs' import { isLeftoverQuotaScheduleOff } from '../pool/availability.mjs' import { isCodexSlotParked } from '../pool/codex-slot-pool.mjs' +import { resolveAccountSessionKey, shouldGateSchedulerLease } from '../pool/daily-session-gate.mjs' import { normalizeOpenAIQuotaPolicy } from '../pool/openai-quota-policy.mjs' import { listQuotaFromHeaders } from '../pool/quota-window.mjs' import { resolveCredentialScheduleLevel } from '../pool/credential-weight.mjs' @@ -1079,6 +1080,7 @@ export class SchedulerRuntime { #apiEndpointStore #accountQuota #codexRuntimeStore + #dailySessionGate #poolScheduler #geminiScheduler #geminiSlotPrefs @@ -1121,6 +1123,7 @@ export class SchedulerRuntime { #geminiOwnersInflight = null #unsubAuxInvalidate = null #unsubLocalClearer = null + #dailySessionLeases = new Map() constructor(options = {}) { this.#cfg = options.cfg || {} @@ -1153,6 +1156,7 @@ export class SchedulerRuntime { this.#apiEndpointStore = options.apiEndpointStore || null this.#accountQuota = options.accountQuota || null this.#codexRuntimeStore = options.codexRuntimeStore || null + this.#dailySessionGate = options.dailySessionGate || null this.#poolScheduler = options.poolScheduler || null this.#geminiScheduler = options.geminiScheduler || null this.#geminiSlotPrefs = options.geminiSlotPrefs || null @@ -1336,6 +1340,109 @@ export class SchedulerRuntime { return this.#codexRuntimeStore || getActiveCodexRuntimeStore() || null } + #resolveDailySessionGate() { + return typeof this.#dailySessionGate === 'function' ? this.#dailySessionGate() : this.#dailySessionGate || null + } + + #resolveClaudeVmById(vmId) { + const id = String(vmId || '').trim() + if (!id) return null + const live = (this.#getVms() || []).find((vm) => vm?.id === id && !isCodexVm(vm)) + if (live) return live + const inv = this.#inventoryByKey.get(formatNodeKey('claude_vm', id))?.item + return inv && !isCodexVm(inv) ? inv : null + } + + #isClaudeQuotaGuardBlocking(vm, now = Date.now()) { + if (!vm?.id || isCodexVm(vm)) return false + const gateCtx = this.#claudeNodeGateContext(null) + if (!gateCtx.projectRoot) return false + const resolved = this.#resolveClaudeGateInputs(vm, gateCtx) + if (!resolved) return false + return this.#claudeQuotaGuardLevel(resolved, now) === 'continuing' + } + + #resolveClaudeSiblingVms(vm, fallbackNodeKey = '') { + const targets = new Map() + const targetAccountKey = vm ? resolveAccountSessionKey(vm) : '' + if (targetAccountKey) { + for (const candidate of this.#getVms() || []) { + if (!candidate?.id || isCodexVm(candidate)) continue + if (resolveAccountSessionKey(candidate) !== targetAccountKey) continue + targets.set(formatNodeKey('claude_vm', candidate.id), candidate) + } + for (const [key, rec] of this.#inventoryByKey.entries()) { + if (!key.startsWith('claude_vm:') || targets.has(key)) continue + const candidate = rec?.item + if (!candidate || isCodexVm(candidate)) continue + if (resolveAccountSessionKey(candidate) !== targetAccountKey) continue + targets.set(key, candidate) + } + } + if (fallbackNodeKey && !targets.has(fallbackNodeKey)) { + targets.set(fallbackNodeKey, vm || null) + } + return targets + } + + #notifyDailySessionBlock(vm, nodeKey, blocked, now = Date.now()) { + if (!nodeKey || this.#client?.stopped) return + const dailyGate = this.#resolveDailySessionGate() + const targets = this.#resolveClaudeSiblingVms(vm, nodeKey) + const updates = [] + for (const [targetKey, targetVm] of targets.entries()) { + const nextBlocked = + targetKey === nodeKey + ? Boolean(blocked) + : dailyGate && targetVm + ? Boolean(dailyGate.isVmNewSessionsBlocked(targetVm, now)) + : Boolean(blocked) + if (!nextBlocked && targetVm && this.#isClaudeQuotaGuardBlocking(targetVm, now)) continue + updates.push({ node_key: targetKey, new_sessions_blocked: nextBlocked }) + } + if (!updates.length) return + if (typeof this.#client?.enqueueTelemetry === 'function') { + try { + this.#client.enqueueTelemetry(updates) + return + } catch {} + } + if (typeof this.#client?.pushTelemetry === 'function') { + void this.#client.pushTelemetry(updates).catch(() => {}) + } + } + + #releaseTrackedDailySessionLease(leaseId, now = Date.now()) { + const id = String(leaseId || '').trim() + if (!id) return null + const entry = this.#dailySessionLeases.get(id) + if (!entry) return null + this.#dailySessionLeases.delete(id) + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate && (entry.tracked || entry.reserved)) { + const rel = dailyGate.releaseReservation(id, now) + if (rel?.uncapped) { + this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, false, now) + } + return rel + } + return null + } + + #clearTrackedDailySessionLeases(now = Date.now()) { + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate && this.#dailySessionLeases.size) { + for (const [leaseId, entry] of this.#dailySessionLeases.entries()) { + if (entry?.tracked || entry?.reserved) { + try { + dailyGate.releaseReservation(leaseId, now) + } catch {} + } + } + } + this.#dailySessionLeases.clear() + } + #resolveCodexRuntime(vmId, snapshot = null) { if (!vmId) return null const id = String(vmId) @@ -2349,6 +2456,10 @@ export class SchedulerRuntime { } if (schedulable && !codex) { + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate?.isVmNewSessionsBlocked?.(vm, now)) { + newSessionsBlocked = true + } const reason = claudeQuotaGate({ vm, account: acct, routing, now }) if (reason) { schedulable = false @@ -2756,6 +2867,7 @@ export class SchedulerRuntime { async shutdown({ drain = true, stopProcess = true, timeoutMs = 2_000 } = {}) { this.#stopTelemetryLoop() + this.#clearTrackedDailySessionLeases() this.#started = false try { this.#unsubAuxInvalidate?.() @@ -3271,7 +3383,68 @@ export class SchedulerRuntime { return req } - #rethrowGated(err, req) { + #dailySessionLimitError(statuses = [], explain = null, now = Date.now()) { + let earliestMs = null + let earliestIso = null + for (const st of statuses || []) { + const ms = Number(st?.reset_at_ms) + if (!Number.isFinite(ms) || ms <= 0) continue + if (earliestMs == null || ms < earliestMs) { + earliestMs = ms + earliestIso = st?.reset_at || new Date(ms).toISOString() + } + } + const retryAfterSec = earliestMs != null ? Math.max(1, Math.ceil((earliestMs - now) / 1000)) : 60 + const message = earliestIso + ? `Anthropic accounts have reached their daily new session limit; resets at ${earliestIso}` + : 'Anthropic accounts have reached their daily new session limit' + return new SchedulerApiError({ + status: 429, + code: 'daily_session_limit', + message, + retryAfterSec, + ...(explain != null ? { explain } : {}), + }) + } + + #dailySessionBlockedStatusesFromExplain(explain, req, extraStatuses = [], now = Date.now()) { + const dailyGate = this.#resolveDailySessionGate() + if (!dailyGate) return [] + if (req?.is_ephemeral_probe || req?.parent_session_id || (req?.is_admin_diagnostic && req?.pin_node_key)) { + return [] + } + const statuses = [...(extraStatuses || [])] + const excluded = Array.isArray(explain?.excluded) ? explain.excluded : null + if (excluded) { + const hasOtherTempBlock = excluded.some((e) => + ['node_cooldown', 'model_cooldown', 'capacity_full', 'rpm_exceeded', 'quota_exhausted'].includes( + String(e?.reason || ''), + ), + ) + if (hasOtherTempBlock && statuses.length === 0) return [] + for (const entry of excluded) { + if (entry?.reason !== 'new_session_blocked') continue + const nodeKey = String(entry?.node || entry?.node_key || '').trim() + if (!nodeKey.startsWith('claude_vm:')) continue + const vm = this.#resolveClaudeVmById(nodeKey.slice('claude_vm:'.length)) + if (!vm) continue + const st = dailyGate.statusForVm(vm, now) + if (st?.blocked) statuses.push(st) + } + if (hasOtherTempBlock && statuses.length === extraStatuses.length) return [] + } + return statuses + } + + #dailySessionExhaustedError(err, req, extraStatuses = [], now = Date.now()) { + if (!(err instanceof SchedulerApiError)) return null + if (err.code !== 'pool_exhausted' && err.status !== 503) return null + const statuses = this.#dailySessionBlockedStatusesFromExplain(err.explain, req, extraStatuses, now) + if (!statuses.length) return null + return this.#dailySessionLimitError(statuses, err.explain ?? null, now) + } + + #rethrowGated(err, req, dailyRejectedStatuses = []) { if ( err instanceof SchedulerApiError && err.code === 'pool_exhausted' && @@ -3279,9 +3452,74 @@ export class SchedulerRuntime { ) { throw fableRequiresMaxError(err.explain) } + const dailyErr = this.#dailySessionExhaustedError(err, req, dailyRejectedStatuses) + if (dailyErr) throw dailyErr throw err } + async #guardDailySessionLease(initialRes, req, callOpts, { requestedEffort } = {}) { + const dailyGate = this.#resolveDailySessionGate() + if (!dailyGate) return { res: initialRes, req } + let res = initialRes + let activeReq = req + const baseRequestId = String(req?.request_id || crypto.randomUUID()) + const raceRejectedStatuses = [] + const maxRetries = 16 + for (let attempt = 0; attempt <= maxRetries; attempt += 1) { + if (!shouldGateSchedulerLease(activeReq, res)) { + return { res, req: activeReq } + } + const nodeId = String(res?.selected_node?.node_id || '').trim() + const nodeKey = String(res?.selected_node?.node_key || formatNodeKey('claude_vm', nodeId)).trim() + const vm = nodeId ? this.#resolveClaudeVmById(nodeId) : null + if (!vm) return { res, req: activeReq } + const now = Date.now() + const reserve = dailyGate.tryReserveNewSession({ + vm, + sessionId: activeReq.session_id, + leaseToken: res.lease_id, + now, + }) + if (reserve.ok) { + this.#dailySessionLeases.set(res.lease_id, { + vm, + nodeKey, + sessionId: activeReq.session_id, + reserved: Boolean(reserve.reserved), + tracked: Boolean(reserve.tracked ?? reserve.reserved), + shouldTrack: true, + }) + if (reserve.newlyCapped) { + this.#notifyDailySessionBlock(vm, nodeKey, true, now) + } + return { res, req: activeReq } + } + raceRejectedStatuses.push(reserve.status) + await this.releaseLease(res.lease_id, 'aborted').catch(() => {}) + this.#notifyDailySessionBlock(vm, nodeKey, true, now) + if (attempt >= maxRetries) { + throw this.#dailySessionLimitError(raceRejectedStatuses, res?.explain ?? null, now) + } + const nextExclude = [...new Set([...(activeReq.exclude_nodes || []), nodeKey])] + // Fresh request_id avoids Rust's (request_id, attempt_no) idempotency cache returning the aborted lease. + activeReq = { + ...activeReq, + request_id: `${baseRequestId}:dsg:${attempt + 1}`, + exclude_nodes: nextExclude, + } + Object.defineProperty(activeReq, JS_GATE, { value: req?.[JS_GATE], enumerable: false }) + try { + res = await this.#client.acquire(activeReq, callOpts) + } catch (err) { + this.#rethrowGated(err, activeReq, raceRejectedStatuses) + } + if (!(activeReq.is_admin_diagnostic && activeReq.pin_node_key)) { + await this.#validateGeminiLeaseQuota(res, activeReq, requestedEffort) + } + } + throw this.#dailySessionLimitError(raceRejectedStatuses, res?.explain ?? null, Date.now()) + } + #poolTimeoutsFor(poolId, opts = {}) { const pool = this.#poolsById.get(String(poolId || '')) return { @@ -3308,11 +3546,15 @@ export class SchedulerRuntime { if (!(req.is_admin_diagnostic && req.pin_node_key)) { await this.#validateGeminiLeaseQuota(res, req, params.requestedEffort ?? params.requested_effort) } - return { ...res, _request: req } + const guarded = await this.#guardDailySessionLease(res, req, callOpts, { + requestedEffort: params.requestedEffort ?? params.requested_effort, + }) + return { ...guarded.res, _request: guarded.req } } async switchNode(params = {}, opts = {}) { const release_lease_id = String(params.releaseLeaseId ?? params.release_lease_id ?? '').trim() + this.#releaseTrackedDailySessionLease(release_lease_id) const rawFailure = params.failure || {} const http_status = Number(rawFailure.http_status ?? rawFailure.httpStatus ?? 0) || 0 const error_class = @@ -3355,7 +3597,10 @@ export class SchedulerRuntime { this.#rethrowGated(err, next_attempt) } await this.#validateGeminiLeaseQuota(res, next_attempt, rawNext.requestedEffort ?? rawNext.requested_effort) - return { ...res, _request: next_attempt } + const guarded = await this.#guardDailySessionLease(res, next_attempt, callOpts, { + requestedEffort: rawNext.requestedEffort ?? rawNext.requested_effort, + }) + return { ...guarded.res, _request: guarded.req } } switchLease(params = {}, opts = {}) { @@ -3365,7 +3610,26 @@ export class SchedulerRuntime { async commitLease(leaseId, opts = {}) { const id = typeof leaseId === 'string' ? leaseId.trim() : String(leaseId?.lease_id || '').trim() if (!id) return { ok: true, committed: false, already_committed: false, lease_found: false } - return this.#client.commit(id, opts) + try { + return await this.#client.commit(id, opts) + } finally { + const entry = this.#dailySessionLeases.get(id) + if (entry) { + this.#dailySessionLeases.delete(id) + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate && entry.shouldTrack) { + const now = Date.now() + const committed = dailyGate.commitReservation(id, { + vm: entry.vm, + sessionId: entry.sessionId, + now, + }) + if (committed?.newlyCapped) { + this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, true, now) + } + } + } + } } async releaseLease(leaseIdOrPayload, outcomeOrPayload = {}, maybeOpts = {}) { @@ -3409,8 +3673,10 @@ export class SchedulerRuntime { const retryAfter = raw.retry_after_sec ?? raw.retryAfterSec const ttftMs = raw.ttft_ms ?? raw.ttftMs const tokensUsed = raw.tokens_used ?? raw.tokensUsed + const leaseIdToRelease = String(raw.lease_id).trim() + this.#releaseTrackedDailySessionLease(leaseIdToRelease) const payload = { - lease_id: String(raw.lease_id).trim(), + lease_id: leaseIdToRelease, outcome, ...(parsedStatus != null ? { http_status: parsedStatus } : {}), ...(errorClass ? { error_class: errorClass } : {}), @@ -3440,13 +3706,20 @@ export class SchedulerRuntime { } catch (err) { this.#rethrowGated(err, req) } - if ( - res && - res.ok === false && - res.error_code === 'pool_exhausted' && - fableRequiresMaxFromExhausted(res.explain, req[JS_GATE]) - ) { - return { ...res, error_code: 'fable_requires_max' } + if (res && res.ok === false && res.error_code === 'pool_exhausted') { + if (fableRequiresMaxFromExhausted(res.explain, req[JS_GATE])) { + return { ...res, error_code: 'fable_requires_max' } + } + const dailyStatuses = this.#dailySessionBlockedStatusesFromExplain(res.explain, req) + if (dailyStatuses.length) { + const dailyErr = this.#dailySessionLimitError(dailyStatuses, res.explain ?? null) + return { + ...res, + error_code: 'daily_session_limit', + retry_after_sec: dailyErr.retryAfterSec, + message: dailyErr.message, + } + } } return res } diff --git a/src/server.mjs b/src/server.mjs index 023403357f..108671ee18 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -122,6 +122,7 @@ import { GroupsRepo } from './lib/db/repos/groups-repo.mjs' import { GeminiOwnersRepo } from './lib/db/repos/gemini-owners-repo.mjs' import { bootstrapSchedulerPools } from './lib/db/repos/scheduler-pools-repo.mjs' import { createSchedulerRuntime } from './lib/scheduler/scheduler-runtime.mjs' +import { createDailySessionGate } from './lib/pool/daily-session-gate.mjs' import { SettingsRepo } from './lib/db/repos/settings-repo.mjs' import { ApiEndpointStore } from './lib/admin/api-endpoints.mjs' import { ApiScheduler } from './lib/pool/api-scheduler.mjs' @@ -332,6 +333,21 @@ async function activateStandby(reason = 'signal') { console.warn(`[standby] ${name} failed`, e?.message || e) } } + if (dailySessionGate) { + try { + const hydrated = + getDbEngine() === 'postgres' && getPgPool?.() + ? await dailySessionGate.hydrateAsync() + : dailySessionGate.hydrate() + if (hydrated?.loaded) { + console.log( + `[standby] daily session gate re-hydrated: loaded=${hydrated.loaded} day=${hydrated.window?.dayKey} tz=${hydrated.window?.timezone}`, + ) + } + } catch (e) { + console.warn('[standby] daily session gate re-hydration failed', e?.message || e) + } + } if (schedulerRuntime) { try { await schedulerRuntime.promoteToLeader({ rebootstrap: true, startDrain: true }) @@ -473,6 +489,7 @@ let poolScheduler let failoverRunner let groupsRepo let schedulerRuntime = null +let dailySessionGate = null const routingRt = createRoutingRuntime({ get routingConfig() { @@ -496,6 +513,10 @@ const routingRt = createRoutingRuntime({ get accountQuota() { return accountQuota }, + get dailySessionGate() { + return dailySessionGate + }, + getDailySessionGate: () => dailySessionGate, get poolScheduler() { return poolScheduler }, @@ -583,6 +604,22 @@ routingConfig.crag_zombie_guard = normalizeCragZombieGuardConfig(routingConfig.c routingConfig.notify = normalizeNotifyConfig(routingConfig.notify) routingConfig.tiers = normalizeTiers(routingConfig.tiers, routingConfig.quota, routingConfig.concurrency) syncTierDefaultsIntoRouting() +dailySessionGate = createDailySessionGate({ + getRoutingConfig: () => routingConfig, + db: getDb(), + pgPool: getPgPool?.(), +}) +try { + const hydrated = + getDbEngine() === 'postgres' && getPgPool() ? await dailySessionGate.hydrateAsync() : dailySessionGate.hydrate() + if (hydrated.loaded) { + console.log( + `[db] daily session gate ready: loaded=${hydrated.loaded} day=${hydrated.window?.dayKey} tz=${hydrated.window?.timezone}`, + ) + } +} catch (err) { + console.warn('[db] daily session gate hydration failed:', err?.message || err) +} warmupMonitor = createWarmupMonitor({ config: routingConfig.warmup, projectRoot: cfg.paths.project, @@ -993,6 +1030,7 @@ notifyMonitor = createNotifyMonitor({ poolScheduler, proxyPool, requestLog, + dailySessionGate, }), }) @@ -1029,6 +1067,12 @@ backupService.onRestored(async (db) => { stickyRouter.reloadConfig(routingConfig) accountQuota.reloadConfig(routingConfig) accountQuota.loadVmQuotaOverrides(listVms(cfg.paths.project)) + dailySessionGate?.rebind?.(db, { pgPool: getPgPool?.() }) + dailySessionGate?.reloadConfig?.(routingConfig) + try { + if (getDbEngine() === 'postgres' && getPgPool()) await dailySessionGate?.hydrateAsync?.() + else dailySessionGate?.hydrate?.() + } catch {} requestLog.setConfig({ mode: process.env.KIN_REQUEST_LOG_MODE || routingConfig.logging?.mode, retainDays: routingConfig.logging?.retain_days, @@ -1047,6 +1091,7 @@ backupService.onRestored(async (db) => { initPoolRuntime() void schedulerRuntime?.syncConfigNow?.('backup_restore').catch(() => {}) + void schedulerRuntime?.pushTelemetryNow?.().catch(() => {}) reloadActiveVm(cfg) vmTestSchedule.reload() try { @@ -1507,6 +1552,11 @@ const { handleAgentSessions } = createHandleAgentSessions({ geminiOwnerMap: () => geminiOwnersProxy.ownerMap(), getRoutingConfig: () => routingConfig, getPoolScheduler: () => poolScheduler, + dailySessionGate, + getDailySessionGate: () => dailySessionGate, + onDailySessionGateChange: () => { + void schedulerRuntime?.pushTelemetryNow?.().catch(() => {}) + }, get groupsRepo() { return groupsRepo }, @@ -1832,6 +1882,7 @@ schedulerRuntime = createSchedulerRuntime({ apiEndpointStore, accountQuota, codexRuntimeStore, + dailySessionGate, poolScheduler: () => poolScheduler, geminiScheduler: () => geminiScheduler, geminiSlotPrefs, @@ -1881,6 +1932,8 @@ const handlePanel = createPanelHandler({ }, stickyRouter, accountQuota, + dailySessionGate, + getDailySessionGate: () => dailySessionGate, get poolScheduler() { return poolScheduler }, diff --git a/test/unit/bg-migration-guard.test.mjs b/test/unit/bg-migration-guard.test.mjs index a79a185c4e..2264bd0172 100644 --- a/test/unit/bg-migration-guard.test.mjs +++ b/test/unit/bg-migration-guard.test.mjs @@ -192,6 +192,9 @@ test('every shipped SQLite migration classifies without throwing', () => { assert.ok(['create_table', 'add_column', 'create_index', 'unsafe'].includes(c.kind), `${f}: ${stmt}`) } } + const mig075 = fs.readFileSync(path.join(SQLITE_DIR, '075_vm_daily_session_creations.sql'), 'utf8') + const v075 = checkAdditive({ ...sqlite('075_vm_daily_session_creations.sql', mig075), rowCount: () => 0 }) + assert.equal(v075.additive, true, JSON.stringify(v075.reasons)) }) // bg-deploy.sh 的调用方式:脚本经 stdin 交给 node,迁移文件名作参数 diff --git a/test/unit/error-class.test.mjs b/test/unit/error-class.test.mjs index bed8d523c6..3d7552912b 100644 --- a/test/unit/error-class.test.mjs +++ b/test/unit/error-class.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test' import assert from 'node:assert/strict' import { EventEmitter } from 'node:events' import { + SLA_OK_ERROR_CODES, classifyRequestError, collectErrors, enrichLogRow, @@ -62,6 +63,9 @@ test('classifyRequestError maps known codes and statuses', () => { assert.equal(classifyRequestError({ status: 503, error_code: 'kernel_unavailable' }).error_class, 'other') assert.equal(classifyRequestError({ status: 529, error_code: 'pool_overload_cooldown' }).error_class, 'overloaded') assert.equal(classifyRequestError({ status: 429, error_code: 'pool_rate_limited' }).error_class, 'rate_limit') + assert.equal(classifyRequestError({ status: 429, error_code: 'daily_session_limit' }).error_class, 'rate_limit') + assert.equal(classifyRequestError({ status: 503, error_code: 'daily_session_limit' }).error_class, 'rate_limit') + assert.equal(SLA_OK_ERROR_CODES.has('daily_session_limit'), true) assert.equal(classifyRequestError({ status: 403, error_message: 'Just a moment Cloudflare' }).error_class, 'proxy') assert.equal( classifyRequestError({ @@ -248,6 +252,73 @@ test('collectErrors groups by class and code', () => { assert.equal(enrichLogRow({ status: 503, error_code: 'server_overloaded' }).error_label, '过载排队') }) +test('mapProtocolClientError preserves daily_session_limit as HTTP 429 without upstream_* details', () => { + const { mapProtocolClientError } = createHandleProtocol({ + json() {}, + writeSSEHeaders() {}, + readBody: async () => ({}), + requireAuth: () => true, + cfg: { rewrite: { enabled: false }, intercept: { rules: [] }, distill: { enabled: false }, limits: {}, paths: {} }, + requestLog: {}, + stickyRouter: {}, + accountQuota: {}, + apiKeyStore: {}, + apiScheduler: {}, + apiEndpointStore: {}, + failoverRunner: {}, + stats: { errors: 0, requests: 0, by_route: {} }, + routingConfig: {}, + }) + const msg = 'Anthropic accounts have reached their daily new session limit; resets at 2026-12-02T00:00:00.000Z' + const failoverResult = { + ok: false, + status: 429, + retryAfterSec: 3600, + via: 'rust-scheduler', + body: { + type: 'error', + error: { + type: 'rate_limit_error', + code: 'daily_session_limit', + message: msg, + }, + }, + } + for (const strictPassthrough of [false, true]) { + const logBag = {} + const mapped = mapProtocolClientError(failoverResult, logBag, 'upstream_error', { strictPassthrough }) + assert.equal(mapped.status, 429) + assert.equal(mapped.retryAfterSec, 3600) + assert.deepEqual(mapped.body, { + type: 'error', + error: { + type: 'rate_limit_error', + code: 'daily_session_limit', + message: msg, + }, + }) + assert.equal(mapped.body.error.details, undefined) + assert.equal(logBag.error_code, 'daily_session_limit') + assert.equal(logBag.error_message, msg) + assert.equal(logBag.error_details, undefined) + } + + const logBagNoRetry = {} + const noRetry = mapProtocolClientError( + { + ok: false, + status: 429, + body: { type: 'error', error: { type: 'rate_limit_error', code: 'daily_session_limit', message: msg } }, + }, + logBagNoRetry, + 'upstream_error', + ) + assert.equal(noRetry.status, 429) + assert.equal(noRetry.retryAfterSec, undefined) + assert.equal(noRetry.body.error.code, 'daily_session_limit') + assert.equal(noRetry.body.error.details, undefined) +}) + test('resolveMutedErrorClasses defaults to auth and accepts an empty list', () => { assert.deepEqual(resolveMutedErrorClasses(null), ['auth']) assert.deepEqual(resolveMutedErrorClasses(undefined), ['auth']) diff --git a/test/unit/errors-map.test.mjs b/test/unit/errors-map.test.mjs index 87e43aa067..3429cc02c2 100644 --- a/test/unit/errors-map.test.mjs +++ b/test/unit/errors-map.test.mjs @@ -102,6 +102,37 @@ test('fable_requires_max remains a dedicated HTTP 429', () => { assert.equal(rewritten.body.error.message, 'Fable requires an available Max account') }) +test('daily_session_limit remains a dedicated HTTP 429 without upstream_* details', () => { + const rawBody = { + type: 'error', + error: { + type: 'rate_limit_error', + code: 'daily_session_limit', + message: 'Anthropic accounts have reached their daily new session limit; resets at 2026-12-02T00:00:00.000Z', + }, + } + const mapped = mapUpstreamError(429, rawBody, { 'retry-after': '120' }) + const rewritten = rewritePoolErrorForClient(mapped, rawBody) + assert.equal(rewritten.status, 429) + assert.equal(rewritten.retryAfterSec, 120) + assert.equal(rewritten.body.error.type, 'rate_limit_error') + assert.equal(rewritten.body.error.code, 'daily_session_limit') + assert.equal(rewritten.body.error.message, rawBody.error.message) + assert.equal(rewritten.body.error.details, undefined) + + const withoutRetryAfter = mapUpstreamError(429, rawBody) + assert.equal(withoutRetryAfter.status, 429) + assert.equal(withoutRetryAfter.retryAfterSec, undefined) + assert.equal(withoutRetryAfter.body.error.code, 'daily_session_limit') + assert.equal(withoutRetryAfter.body.error.details, undefined) + + const strict = passthroughUpstreamError(429, rawBody, { 'retry-after': '90' }) + assert.equal(strict.status, 429) + assert.equal(strict.retryAfterSec, 90) + assert.equal(strict.body.error.code, 'daily_session_limit') + assert.equal(strict.body.error.details, undefined) +}) + test('incomplete upstream stream maps to 502, not api_error 500', () => { const mapped = mapUpstreamError(200, { type: 'error', diff --git a/test/unit/pool-scheduler.test.mjs b/test/unit/pool-scheduler.test.mjs index 06ba391d07..2a5002f735 100644 --- a/test/unit/pool-scheduler.test.mjs +++ b/test/unit/pool-scheduler.test.mjs @@ -32,6 +32,7 @@ import { formatNodeKey, } from '../../src/lib/scheduler/scheduler-runtime.mjs' import { listVms } from '../../src/lib/vm/vm-registry.mjs' +import { shouldGateSchedulerLease } from '../../src/lib/pool/daily-session-gate.mjs' import { atomicWriteJson, setVmWriteHook } from '../../src/lib/vm/vm-file.mjs' import { flushVmDbSyncAsync, @@ -677,3 +678,71 @@ test('vm-db-sync PG mode offloads single-VM writes to async pgPool UNNEST and av assert.equal(watchUpserts.length, 1, 'external edit should trigger a single async PG upsert') assert.deepEqual(watchUpserts[0].params[0], ['vm-02'], 'fs.watch must sync ONLY changed vm-02, not vm-01 or vm-03') }) + +test('validateQuotaRoutingPatch validates quota.daily_session_gate alongside exhaustion guard', () => { + validateQuotaRoutingPatch({ + quota: { + daily_session_gate: { + enabled: true, + reset_timezone: 'Asia/Shanghai', + tier_limits: { default: 10, pro: 20, max_5x: 50, max_20x: 100, team: 80, enterprise: 0 }, + }, + }, + }) + assert.throws( + () => validateQuotaRoutingPatch({ quota: { daily_session_gate: { reset_timezone: 'Bad/Zone' } } }), + (err) => err instanceof TypeError && err.code === 'invalid_quota_config', + ) + assert.throws( + () => validateQuotaRoutingPatch({ quota: { daily_session_gate: { tier_limits: { pro: -1 } } } }), + (err) => err instanceof TypeError && err.code === 'invalid_quota_config', + ) + assert.throws( + () => validateQuotaRoutingPatch({ quota: { daily_session_gate: { unknown: 1 } } }), + (err) => err instanceof TypeError && err.code === 'invalid_quota_config', + ) +}) + +test('shouldGateSchedulerLease gates only new primary Claude leases and skips continuing/subagent/probe/admin-pin/codex', () => { + const baseReq = { session_id: 'sess-new-1' } + const claudeRes = (why) => ({ + selected_node: { node_type: 'claude_vm', node_id: 'vm-01' }, + explain: { affinity: { why } }, + }) + + // New primary Claude session placements (normal, machine home, busy spill) are gated + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('tier_ranked')), true) + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('machine_home_hit')), true) + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('session_spill_busy')), true) + + // Continuing sessions are NOT gated + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('session_hit')), false) + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('session_hit_after_wait')), false) + + // Subagents are NOT gated + assert.equal(shouldGateSchedulerLease({ ...baseReq, parent_session_id: 'parent-1' }, claudeRes('tier_ranked')), false) + assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('subagent_follow_parent')), false) + + // Ephemeral probes & admin diagnostic pins are NOT gated + assert.equal(shouldGateSchedulerLease({ ...baseReq, is_ephemeral_probe: true }, claudeRes('tier_ranked')), false) + assert.equal( + shouldGateSchedulerLease( + { ...baseReq, is_admin_diagnostic: true, pin_node_key: 'claude_vm:vm-01' }, + claudeRes('tier_ranked'), + ), + false, + ) + // Admin diagnostic without pin_node_key still follows normal gating + assert.equal(shouldGateSchedulerLease({ ...baseReq, is_admin_diagnostic: true }, claudeRes('tier_ranked')), true) + + // Missing session_id or non-claude_vm node types (Codex / API endpoint) are NOT gated + assert.equal(shouldGateSchedulerLease({ session_id: '' }, claudeRes('tier_ranked')), false) + assert.equal(shouldGateSchedulerLease({}, claudeRes('tier_ranked')), false) + assert.equal( + shouldGateSchedulerLease(baseReq, { + selected_node: { node_type: 'codex_vm', node_id: 'vm-codex' }, + explain: { affinity: { why: 'tier_ranked' } }, + }), + false, + ) +}) diff --git a/test/unit/routing-runtime-load.test.mjs b/test/unit/routing-runtime-load.test.mjs index abeab5e51e..5c866fb19c 100644 --- a/test/unit/routing-runtime-load.test.mjs +++ b/test/unit/routing-runtime-load.test.mjs @@ -3,11 +3,13 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' +import { buildRouting, buildVmDetail } from '../../src/lib/admin/panel-api.mjs' import { createPanelHandler } from '../../src/lib/admin/panel-routes.mjs' import { createRoutingRuntime } from '../../src/lib/admin/routing-runtime.mjs' -import { buildRouting } from '../../src/lib/admin/panel-api.mjs' -import { DEFAULT_CODEX_ROUTING } from '../../src/lib/protocol/codex-route.mjs' +import { createDatabase } from '../../src/lib/db/database.mjs' import { OFFICIAL_CLI_VERSION } from '../../src/lib/identity/vm-identity.mjs' +import { createDailySessionGate } from '../../src/lib/pool/daily-session-gate.mjs' +import { DEFAULT_CODEX_ROUTING } from '../../src/lib/protocol/codex-route.mjs' function runtimeFor(file) { return createRoutingRuntime({ routingConfigPath: file }) @@ -828,3 +830,301 @@ test('persistRoutingPatch merges and normalizes batch_group and loadRoutingConfi fs.rmSync(root, { recursive: true, force: true }) } }) + +test('daily_session_gate: loadRoutingConfig normalizes, persistRoutingPatch deep-merges & reloads, PUT /api/panel/routing nudges telemetry & rolls back on error', async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-routing-dsg-')) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + const routingFile = path.join(root, 'routing.json') + fs.writeFileSync( + routingFile, + JSON.stringify({ concurrency: {}, tiers: {}, codex: { quota: { max_concurrency: 2 } } }), + ) + + // 1. loadRoutingConfig & buildRouting always expose normalized quota.daily_session_gate + const loaded = runtimeFor(routingFile).loadRoutingConfig() + assert.deepEqual(loaded.quota.daily_session_gate, { + enabled: false, + reset_timezone: 'UTC', + tier_limits: { default: 0, pro: 0, max_5x: 0, max_20x: 0, team: 0, enterprise: 0 }, + }) + const built = buildRouting({ routingConfig: {}, stickyRouter: { stats: () => ({}) } }) + assert.deepEqual(built.data.quota.daily_session_gate, loaded.quota.daily_session_gate) + + // 2. persistRoutingPatch deep-merges partial daily_session_gate patches and reloads dailySessionGate + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + let routingConfig = loaded + const dailySessionGate = createDailySessionGate({ getRoutingConfig: () => routingConfig, db }) + const runtime = createRoutingRuntime({ + cfg: { paths: { project: root } }, + routingConfigPath: routingFile, + routingConfig, + dailySessionGate, + stickyRouter: { reloadConfig() {} }, + accountQuota: { + reloadConfig() {}, + applyTierConcurrency() {}, + applyTierRpm() {}, + repo: { get: () => null }, + }, + requestLog: { setConfig() {} }, + }) + + await runtime.persistRoutingPatch({ + quota: { daily_session_gate: { enabled: true, tier_limits: { pro: 20 } } }, + }) + await runtime.persistRoutingPatch({ + quota: { daily_session_gate: { reset_timezone: 'Asia/Shanghai', tier_limits: { max_5x: 50 } } }, + }) + const saved = JSON.parse(fs.readFileSync(routingFile, 'utf8')) + assert.deepEqual(saved.quota.daily_session_gate, { + enabled: true, + reset_timezone: 'Asia/Shanghai', + tier_limits: { default: 0, pro: 20, max_5x: 50, max_20x: 0, team: 0, enterprise: 0 }, + }) + assert.deepEqual(dailySessionGate.getConfig(), saved.quota.daily_session_gate) + + // 3. PUT /api/panel/routing nudges pushTelemetryNow on success, and restores dailySessionGate on persist error + let telemetryPushes = 0 + let shouldFail = false + const reloadSnapshots = [] + const trackedGate = { + reloadConfig(cfg) { + reloadSnapshots.push(structuredClone(cfg?.quota?.daily_session_gate)) + dailySessionGate.reloadConfig(cfg) + }, + } + const panelCtx = { + cfg: { paths: { project: root }, limits: { max_body_bytes: 8192 } }, + stickyRouter: { stats: () => ({}), reloadConfig() {} }, + accountQuota: { reloadConfig() {}, applyTierConcurrency() {}, applyTierRpm() {} }, + requestLog: { setConfig() {} }, + dailySessionGate: trackedGate, + schedulerRuntime: { + async pushTelemetryNow() { + telemetryPushes += 1 + return { ok: true } + }, + }, + async persistRoutingPatch(body) { + if (shouldFail) { + routingConfig.quota.daily_session_gate.enabled = false + trackedGate.reloadConfig(routingConfig) + throw new Error('disk_full') + } + return runtime.persistRoutingPatch(body) + }, + requireAuth(req) { + req.apiKeyKind = 'master' + req.panelRole = 'admin' + return true + }, + } + + const callPut = async (body) => { + const out = {} + const handler = createPanelHandler({ + ...panelCtx, + get routingConfig() { + return routingConfig + }, + set routingConfig(v) { + routingConfig = v + }, + readBody: async () => body, + json(_res, status, payload) { + out.status = status + out.body = payload + return true + }, + }) + await handler({ method: 'PUT' }, {}, new URL('http://localhost/api/panel/routing')) + return out + } + + const okPut = await callPut({ quota: { daily_session_gate: { tier_limits: { team: 80 } } } }) + assert.equal(okPut.status, 200) + assert.equal(telemetryPushes, 1) + assert.equal(routingConfig.quota.daily_session_gate.tier_limits.team, 80) + + shouldFail = true + const failPut = await callPut({ quota: { daily_session_gate: { enabled: false } } }) + assert.equal(failPut.status, 503) + assert.equal(telemetryPushes, 2, 'rollback should also nudge scheduler telemetry') + assert.equal( + routingConfig.quota.daily_session_gate.enabled, + true, + 'restoreRoutingRuntime must roll back routingConfig', + ) + assert.equal(dailySessionGate.getConfig().enabled, true, 'restoreRoutingRuntime must roll back dailySessionGate') + assert.equal(reloadSnapshots.at(-1)?.enabled, true) +}) + +test('PATCH /api/panel/vms/:id daily_session_limit override (null/0/N, Codex forbidden) and buildVmDetail daily_sessions & restriction_reason', async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-panel-vm-dsg-')) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + fs.mkdirSync(path.join(root, 'vms'), { recursive: true }) + + const claudeVm = { + id: 'vm-claude-1', + name: 'Claude Pro', + status: 'running', + schedulable: true, + claude: { + account_uuid: 'acc-pro-1', + subscription_type: 'pro', + has_access: true, + has_refresh: true, + }, + policy: { maxConcurrency: 2 }, + } + const codexVm = { + id: 'vm-codex-1', + name: 'Codex Slot', + platform: 'openai', + family: 'codex', + status: 'running', + schedulable: true, + codex: { has_token: true }, + policy: { maxConcurrency: 2 }, + } + fs.writeFileSync(path.join(root, 'vms', 'vm-claude-1.json'), JSON.stringify(claudeVm)) + fs.writeFileSync(path.join(root, 'vms', 'vm-codex-1.json'), JSON.stringify(codexVm)) + + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + + const routingConfig = { + quota: { + daily_session_gate: { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 0, pro: 1, max_5x: 5, max_20x: 10, team: 0, enterprise: 0 }, + }, + }, + tiers: {}, + concurrency: {}, + } + const dailySessionGate = createDailySessionGate({ getRoutingConfig: () => routingConfig, db }) + dailySessionGate.hydrate() + + dailySessionGate.tryReserveNewSession({ vm: claudeVm, sessionId: 'sess-used-1', leaseToken: 'lt-used-1' }) + dailySessionGate.commitReservation('lt-used-1') + + const fakeAccountQuota = { + config: routingConfig.quota, + snapshot: () => ({ accounts: [], safety_ratio: 0.85, tiers: {} }), + snapshotAsync: async () => ({ accounts: [], safety_ratio: 0.85, tiers: {} }), + setVmQuotaOverride() {}, + repo: { get: () => null }, + } + const routingRt = createRoutingRuntime({ + cfg: { paths: { project: root } }, + routingConfig, + accountQuota: fakeAccountQuota, + dailySessionGate, + }) + + // 1. Initial detail: capped at 1/1 -> restricted with daily_session_limit + reset_at_ms + const initialDetail = await buildVmDetail({ + cfg: { paths: { project: root } }, + accountQuota: fakeAccountQuota, + id: 'vm-claude-1', + routingConfig, + dailySessionGate, + slotProcessStatus: () => ({ running: true }), + }) + assert.equal(initialDetail.ok, true) + const d0 = initialDetail.data.vm + assert.equal(d0.quota_inherited.daily_session_limit, 1) + assert.equal(d0.quota_policy.daily_session_limit, 1) + assert.equal(d0.daily_sessions.used, 1) + assert.equal(d0.daily_sessions.limit, 1) + assert.equal(d0.daily_sessions.remaining, 0) + assert.equal(d0.daily_sessions.blocked, true) + assert.equal(d0.daily_sessions.tier_key, 'pro') + assert.equal(d0.daily_sessions.source, 'tier') + assert.equal(d0.schedule_state, 'restricted') + assert.equal(d0.restriction_scope, 'new_session') + assert.equal(d0.restriction_reason, 'daily_session_limit') + assert.equal(d0.restriction_text, '今日新会话上限') + assert.equal(d0.restriction_until, d0.daily_sessions.reset_at_ms) + + // Codex VM detail has daily_sessions === null + const codexDetail = await buildVmDetail({ + cfg: { paths: { project: root } }, + accountQuota: fakeAccountQuota, + id: 'vm-codex-1', + routingConfig, + dailySessionGate, + slotProcessStatus: () => ({ running: true }), + }) + assert.equal(codexDetail.data.vm.daily_sessions, null) + + // 2. PATCH /api/panel/vms/:id override 0 -> unlimited & unblocked, nudges telemetry + let telemetryPushes = 0 + const callPatch = async (vmId, body) => { + const out = {} + const handler = createPanelHandler({ + cfg: { paths: { project: root }, limits: { max_body_bytes: 8192 } }, + routingConfig, + accountQuota: fakeAccountQuota, + stickyRouter: { stats: () => ({}) }, + dailySessionGate, + schedulerRuntime: { + async pushTelemetryNow() { + telemetryPushes += 1 + return { ok: true } + }, + }, + applyVmQuotaOverride: routingRt.applyVmQuotaOverride, + readBody: async () => body, + requireAuth(req) { + req.apiKeyKind = 'master' + req.panelRole = 'admin' + return true + }, + json(_res, status, payload) { + out.status = status + out.body = payload + return true + }, + }) + await handler({ method: 'PATCH' }, {}, new URL(`http://localhost/api/panel/vms/${vmId}`)) + return out + } + + const patchZero = await callPatch('vm-claude-1', { quota_override: { daily_session_limit: 0 } }) + assert.equal(patchZero.status, 200) + assert.equal(telemetryPushes, 1) + assert.equal(patchZero.body.data.vm.quota_override.daily_session_limit, 0) + assert.equal(patchZero.body.data.vm.quota_policy.daily_session_limit, 0) + assert.equal(patchZero.body.data.vm.quota_inherited.daily_session_limit, 1) + assert.equal(patchZero.body.data.vm.daily_sessions.active, false) + assert.equal(patchZero.body.data.vm.daily_sessions.blocked, false) + assert.equal(patchZero.body.data.vm.daily_sessions.source, 'override') + assert.equal(patchZero.body.data.vm.schedule_state, 'on') + + // 3. PATCH override N=5 -> active cap 5, remaining 4, unblocked + const patchFive = await callPatch('vm-claude-1', { quota_override: { daily_session_limit: 5 } }) + assert.equal(patchFive.status, 200) + assert.equal(telemetryPushes, 2) + assert.equal(patchFive.body.data.vm.quota_policy.daily_session_limit, 5) + assert.equal(patchFive.body.data.vm.daily_sessions.limit, 5) + assert.equal(patchFive.body.data.vm.daily_sessions.remaining, 4) + assert.equal(patchFive.body.data.vm.daily_sessions.blocked, false) + + // 4. PATCH override null -> restores inherited Pro tier cap 1 -> restricted again + const patchNull = await callPatch('vm-claude-1', { quota_override: { daily_session_limit: null } }) + assert.equal(patchNull.status, 200) + assert.equal(telemetryPushes, 3) + assert.equal(patchNull.body.data.vm.quota_override, null) + assert.equal(patchNull.body.data.vm.quota_policy.daily_session_limit, 1) + assert.equal(patchNull.body.data.vm.daily_sessions.blocked, true) + assert.equal(patchNull.body.data.vm.restriction_reason, 'daily_session_limit') + + // 5. Codex VM rejects quota_override.daily_session_limit with 400 gpt_quota_override_forbidden + const patchCodex = await callPatch('vm-codex-1', { quota_override: { daily_session_limit: 5 } }) + assert.equal(patchCodex.status, 400) + assert.equal(patchCodex.body.error.code, 'gpt_quota_override_forbidden') +}) diff --git a/test/unit/rust-kernel-health.test.mjs b/test/unit/rust-kernel-health.test.mjs index 0bf3dea3b3..54ed1e3168 100644 --- a/test/unit/rust-kernel-health.test.mjs +++ b/test/unit/rust-kernel-health.test.mjs @@ -14,6 +14,8 @@ import { rustKernelNeedsRestart, } from '../../src/lib/transport/rust-kernel-client.mjs' import { createHandleAgentSessions } from '../../src/lib/protocol/handle-agent-sessions.mjs' +import { createDailySessionGate } from '../../src/lib/pool/daily-session-gate.mjs' +import { createDatabase } from '../../src/lib/db/database.mjs' test('toPublicKernelHealth keeps wrap cli-hop slot fields', () => { const out = toPublicKernelHealth( @@ -629,11 +631,17 @@ function makeHarness(root, slot, timeoutMs = 1000, extraDeps = {}) { return { logs, billing, - async request(body, signal = null, configureResponse = null) { + bindings, + async request( + body, + signal = null, + configureResponse = null, + apiKeyRecord = { id: 'key-allowed', group_type: 'all' }, + ) { nextBody = body const res = makeAgentRes() configureResponse?.(res) - await handleAgentSessions(makeAgentReq({ apiKeyRecord: { id: 'key-allowed', group_type: 'all' }, signal }), res) + await handleAgentSessions(makeAgentReq({ apiKeyRecord, signal }), res) return res }, } @@ -1033,3 +1041,208 @@ test('agent sessions resync and retry once on CRAG license_invalid, and mask per assert.equal(hFail.logs[0].error_code, 'license_invalid') assert.match(hFail.logs[0].error_message, /The license or encrypted package is invalid/) }) + +test('handleAgentSessions enforces dailySessionGate: pre-header release, first-header commit, continuing bypass, and 429 when capped', async (t) => { + const root = temp(t) + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + + const dailySessionGate = createDailySessionGate({ + config: { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 1, pro: 1, max_5x: 1, max_20x: 1, team: 1, enterprise: 1 }, + }, + db, + }) + dailySessionGate.hydrate() + + let mode = 'fail' + const slot = await startMockCragSlot(t, root, 'vm-a', { + handler(_req, res, body) { + if (mode === 'fail') { + res.writeHead(500, { 'content-type': 'application/json' }) + return res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: 'boom before stream' } })) + } + res.writeHead(200, { 'content-type': 'application/x-ndjson', 'x-claude-code-session-id': body.session_id }) + res.end( + JSON.stringify({ + type: 'result', + subtype: 'success', + session_id: body.session_id, + usage: { input_tokens: 2, output_tokens: 1 }, + total_cost_usd: 0.001, + }) + '\n', + ) + }, + }) + + const changeEvents = [] + const h = makeHarness(root, slot, 1000, { + dailySessionGate, + onDailySessionGateChange: (vm, info) => changeEvents.push({ vmId: vm?.id, event: info?.event }), + }) + + // 1. Pre-header upstream error releases reservation without counting + const rFail = await h.request({ session_id: 'agent-fail-1', prompt: 'hello', stream: false }) + assert.equal(rFail.statusCode, 500) + const vmObj = { id: 'vm-a', platform: 'anthropic' } + assert.equal(dailySessionGate.statusForVm(vmObj).used, 0) + assert.equal(dailySessionGate.statusForVm(vmObj).pending, 0) + + // 2. First-header streaming success commits once and caps slot (1/1) + mode = 'ok' + const rOk = await h.request({ session_id: 'agent-sess-1', prompt: 'hello' }) + assert.equal(rOk.statusCode, 200) + assert.equal(dailySessionGate.statusForVm(vmObj).used, 1) + assert.equal(dailySessionGate.statusForVm(vmObj).blocked, true) + assert.ok(changeEvents.some((e) => e.vmId === 'vm-a' && e.event === 'newly_capped')) + + // 3. Continuing sticky session bypasses dailySessionGate even when capped + const rCont = await h.request({ session_id: 'agent-sess-1', prompt: 'follow-up' }) + assert.equal(rCont.statusCode, 200) + assert.equal(dailySessionGate.statusForVm(vmObj).used, 1) + + // 4. Brand-new session while all slots capped returns HTTP 429 daily_session_limit with Retry-After + reset_at + const rCapped = await h.request({ session_id: 'agent-sess-2', prompt: 'new session' }) + assert.equal(rCapped.statusCode, 429) + const cappedBody = JSON.parse(Buffer.concat(rCapped.chunks).toString('utf8')) + assert.equal(cappedBody.error?.type, 'rate_limit_error') + assert.equal(cappedBody.error?.code, 'daily_session_limit') + assert.match(cappedBody.error?.message || '', /resets at/i) + assert.ok(Number(rCapped.headers['retry-after']) >= 1) + assert.equal(h.logs.at(-1)?.error_code, 'daily_session_limit') +}) + +test('handleAgentSessions dailySessionGate: pre-commit failure does not sticky-bypass cap or drop counting, and isolates tenants sharing session_id', async (t) => { + // Scenario A: pre-commit failure on attempt 1 must NOT leave a sticky bypass; + // retry when capped is rejected with 429, and retry when uncapped counts used=1 on 200 OK. + { + const root = temp(t) + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + const gate = createDailySessionGate({ + config: { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 1, pro: 1, max_5x: 1, max_20x: 1, team: 1, enterprise: 1 }, + }, + db, + }) + gate.hydrate() + + let mode = 'fail' + const slot = await startMockCragSlot(t, root, 'vm-a', { + handler(_req, res, body) { + if (mode === 'fail') { + res.writeHead(500, { 'content-type': 'application/json' }) + return res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: 'pre-commit fail' } })) + } + res.writeHead(200, { 'content-type': 'application/x-ndjson', 'x-claude-code-session-id': body.session_id }) + res.end( + JSON.stringify({ + type: 'result', + subtype: 'success', + session_id: body.session_id, + usage: { input_tokens: 2, output_tokens: 1 }, + total_cost_usd: 0.001, + }) + '\n', + ) + }, + }) + const h = makeHarness(root, slot, 1000, { dailySessionGate: gate }) + const vmObj = { id: 'vm-a', platform: 'anthropic' } + + // Attempt 1 fails pre-commit: reservation released and sticky binding NOT persisted + const fail1 = await h.request({ session_id: 'retry-sess', prompt: 'try 1', stream: false }) + assert.equal(fail1.statusCode, 500) + assert.equal(gate.statusForVm(vmObj).used, 0) + assert.equal(gate.statusForVm(vmObj).pending, 0) + assert.equal(h.bindings.size, 0, 'pre-commit failure must not bind stickyRouter') + + // Even if a stale uncommitted sticky binding exists, retry must still reserve & count used=1 on success + h.bindings.set('agent_sess:key-allowed:retry-sess', { accountId: 'vm-a', vmId: 'vm-a', sessionId: 'retry-sess' }) + mode = 'ok' + const retryOk = await h.request({ session_id: 'retry-sess', prompt: 'try 2' }) + assert.equal(retryOk.statusCode, 200) + assert.equal(gate.statusForVm(vmObj).used, 1, 'retry after pre-commit failure must count used=1') + assert.equal(gate.statusForVm(vmObj).blocked, true) + + // Another uncommitted session that even has a stale sticky binding MUST NOT bypass the 1/1 cap + h.bindings.set('agent_sess:key-allowed:stale-uncommitted', { + accountId: 'vm-a', + vmId: 'vm-a', + sessionId: 'stale-uncommitted', + }) + const hitsBefore = slot.requests.length + const blockedRetry = await h.request({ session_id: 'stale-uncommitted', prompt: 'should block' }) + assert.equal(blockedRetry.statusCode, 429) + assert.equal(JSON.parse(Buffer.concat(blockedRetry.chunks).toString('utf8')).error?.code, 'daily_session_limit') + assert.equal(slot.requests.length, hitsBefore, 'capped uncommitted sticky session must not reach upstream') + } + + // Scenario B: cross-tenant isolation when Tenant A and Tenant B submit the exact same caller session_id ("default") + { + const root = temp(t) + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + const gate = createDailySessionGate({ + config: { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 1, pro: 1, max_5x: 1, max_20x: 1, team: 1, enterprise: 1 }, + }, + db, + }) + gate.hydrate() + + const slot = await startMockCragSlot(t, root, 'vm-a', { + handler(_req, res, body) { + res.writeHead(200, { 'content-type': 'application/x-ndjson', 'x-claude-code-session-id': body.session_id }) + res.end( + JSON.stringify({ + type: 'result', + subtype: 'success', + session_id: body.session_id, + usage: { input_tokens: 2, output_tokens: 1 }, + total_cost_usd: 0.001, + }) + '\n', + ) + }, + }) + const h = makeHarness(root, slot, 1000, { + dailySessionGate: gate, + getRoutingConfig: () => ({ + inference: { engine: 'rust', dataplane: 'crag', crag_kernel_version: 'v2' }, + agent_sessions: { allowed_key_ids: ['key-tenant-a', 'key-tenant-b'] }, + }), + }) + const vmObj = { id: 'vm-a', platform: 'anthropic' } + const tenantA = { id: 'key-tenant-a', group_type: 'all' } + const tenantB = { id: 'key-tenant-b', group_type: 'all' } + + // Tenant A commits session_id "default" -> fills cap 1/1 + const resA = await h.request({ session_id: 'default', prompt: 'hello from A' }, null, null, tenantA) + assert.equal(resA.statusCode, 200) + assert.equal(gate.statusForVm(vmObj).used, 1) + assert.equal(gate.statusForVm(vmObj).blocked, true) + + // Tenant B sending the same raw session_id "default" MUST NOT bypass the gate + const hitsBeforeB = slot.requests.length + const resBBlocked = await h.request({ session_id: 'default', prompt: 'hello from B' }, null, null, tenantB) + assert.equal(resBBlocked.statusCode, 429) + assert.equal(JSON.parse(Buffer.concat(resBBlocked.chunks).toString('utf8')).error?.code, 'daily_session_limit') + assert.equal(slot.requests.length, hitsBeforeB, 'Tenant B must not bypass cap via Tenant A session_id') + + // Raising limit to 2 allows Tenant B and counts it separately as used=2 + gate.reloadConfig({ + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 2, pro: 2, max_5x: 2, max_20x: 2, team: 2, enterprise: 2 }, + }) + const resBOk = await h.request({ session_id: 'default', prompt: 'hello from B retry' }, null, null, tenantB) + assert.equal(resBOk.statusCode, 200) + assert.equal(gate.statusForVm(vmObj).used, 2) + assert.equal(gate.statusForVm(vmObj).blocked, true) + } +}) diff --git a/test/unit/schedule-state.test.mjs b/test/unit/schedule-state.test.mjs index 5d2b15d41f..8057eab9ac 100644 --- a/test/unit/schedule-state.test.mjs +++ b/test/unit/schedule-state.test.mjs @@ -112,6 +112,12 @@ test('deterministic failures are 不可调度, self-healing ones are 受限', () ) assert.equal(stateOfReason('seats_full').soft, false) assert.equal(stateOfReason('sessions_full').scope, 'new_session') + assert.deepEqual(stateOfReason('daily_session_limit'), { + state: 'restricted', + scope: 'new_session', + soft: false, + text: '今日新会话上限', + }) }) test('mutators keep the legacy trio in step', () => { @@ -268,6 +274,47 @@ test('resolveSlotState: unschedulable > off > restricted > on', () => { assert.equal(sessions.restriction_reason, 'sessions_full') assert.equal(resolveSlotState({ vm: { schedulable: true }, sessions: { active: 3, max: 0 } }).schedule_state, 'on') + const resetMs = now + 12 * 3600_000 + const daily = resolveSlotState({ + vm: { schedulable: true }, + dailySessions: { blocked: true, used: 20, limit: 20, reset_at_ms: resetMs }, + now, + }) + assert.equal(daily.schedule_state, 'restricted') + assert.equal(daily.restriction_reason, 'daily_session_limit') + assert.equal(daily.restriction_text, '今日新会话上限') + assert.equal(daily.restriction_scope, 'new_session') + assert.equal(daily.restriction_soft, false) + assert.equal(daily.restriction_until, resetMs) + + // Higher-precedence states outrank dailySessions; unlimited/unblocked stays on + assert.equal( + resolveSlotState({ + vm: { schedulable: true }, + dailySessions: { blocked: false, used: 5, limit: 0, reset_at_ms: resetMs }, + now, + }).schedule_state, + 'on', + ) + assert.equal( + resolveSlotState({ + vm: { schedulable: true }, + availability: { key: 'quota', reason: 'quota_5h_header', until: now + 60_000 }, + dailySessions: { blocked: true, used: 20, limit: 20, reset_at_ms: resetMs }, + now, + }).restriction_reason, + 'quota_5h_header', + ) + assert.equal( + resolveSlotState({ + vm: { schedulable: true }, + sessions: { active: 3, max: 3 }, + dailySessions: { blocked: true, used: 20, limit: 20, reset_at_ms: resetMs }, + now, + }).restriction_reason, + 'sessions_full', + ) + const held = { schedulable: true } applyHold(held, 'maintenance', { tag: 'kernel_update' }) assert.equal(resolveSlotState({ vm: held, availability: { key: 'off' } }).restriction_text, '维护中') diff --git a/test/unit/scheduler-m0-migrations.test.mjs b/test/unit/scheduler-m0-migrations.test.mjs index f5806b14d6..73e167fe5b 100644 --- a/test/unit/scheduler-m0-migrations.test.mjs +++ b/test/unit/scheduler-m0-migrations.test.mjs @@ -79,6 +79,8 @@ test('SQLite 071 upgrades pre-071 DB cleanly, preserves existing api_keys, and e '071_scheduler_center.sql', '072_scheduler_pool_prompt_default.sql', '073_api_endpoint_body_policy_default.sql', + '074_codex_slot_runtime.sql', + '075_vm_daily_session_creations.sql', ]) // Re-applying is idempotent @@ -736,7 +738,12 @@ test('072 SQLite / 009 PG migrations safely repair untouched legacy vm_pools bac ).run('pool_openai_pt', 'openai-pt', 'OpenAI Pool', now, now) const applied = applyMigrations(db) - assert.deepEqual(applied, ['072_scheduler_pool_prompt_default.sql', '073_api_endpoint_body_policy_default.sql']) + assert.deepEqual(applied, [ + '072_scheduler_pool_prompt_default.sql', + '073_api_endpoint_body_policy_default.sql', + '074_codex_slot_runtime.sql', + '075_vm_daily_session_creations.sql', + ]) const modeOf = (id) => db.prepare('SELECT system_prompt_mode FROM scheduler_pools WHERE id = ?').get(id).system_prompt_mode diff --git a/test/unit/scheduler-m3-runtime.test.mjs b/test/unit/scheduler-m3-runtime.test.mjs index fc8b2fa05d..e0e8bebe18 100644 --- a/test/unit/scheduler-m3-runtime.test.mjs +++ b/test/unit/scheduler-m3-runtime.test.mjs @@ -23,6 +23,7 @@ import { AccountsRepo } from '../../src/lib/db/repos/accounts-repo.mjs' import { GroupsRepo } from '../../src/lib/db/repos/groups-repo.mjs' import { SchedulerPoolsRepo } from '../../src/lib/db/repos/scheduler-pools-repo.mjs' import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' +import { createDailySessionGate } from '../../src/lib/pool/daily-session-gate.mjs' import { FailoverRunner } from '../../src/lib/pool/failover-runner.mjs' import { PLATFORM_OWNER_SENTINEL, @@ -1555,3 +1556,295 @@ test('M3 runtime: default Anthropic pool inherits global official policy and sna assert.equal(acq.prompt_policy.source, 'global') await runtime.releaseLease(acq.lease_id, 'ok') }) + +test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry to 2nd VM, commit vs release, bypasses, and 429 FailoverRunner mapping', async (t) => { + const tmp = makeTempDir('vm2api-m3-dsg-') + const fx = makeFixtureState(tmp) + const gateConfig = { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 1, pro: 1, max_5x: 1, max_20x: 1, team: 1, enterprise: 1 }, + } + const dailySessionGate = createDailySessionGate({ config: gateConfig, db: fx.db }) + dailySessionGate.hydrate() + + const runtime = createSchedulerRuntime({ + getDb: () => fx.db, + getVms: () => fx.vms, + getRoutingConfig: () => ({ quota: { daily_session_gate: gateConfig } }), + apiKeyStore: makeApiKeyStore(fx.db), + apiEndpointStore: { listRaw: () => fx.endpoints }, + geminiScheduler: { listEnvironments: () => fx.geminiEnvs }, + dailySessionGate, + telemetryIntervalMs: 0, + clientOptions: { + binPath: BIN_PATH, + dataDir: tmp, + socketPath: path.join(tmp, 'dsg.sock'), + tokenPath: path.join(tmp, 'dsg.token'), + capFile: path.join(tmp, 'dsg.cap.json'), + }, + }) + t.after(async () => { + await runtime.shutdown({ drain: false, stopProcess: true }) + fx.db.close() + fs.rmSync(tmp, { recursive: true, force: true }) + }) + + await runtime.start({ waitMs: 5_000, startLoops: true }) + const baseReq = { + originPoolId: fx.poolAnth.id, + apiKeyRecord: { ...fx.strictKey, allowed_pool_ids: [fx.poolAnth.id] }, + apiKeyKind: 'managed', + model: 'claude-sonnet-4-6', + protocol: 'anthropic', + } + + // 1. Pre-commit release frees reservation without counting and unblocks telemetry + const sess1 = '550e8400-e29b-41d4-a716-446655440101' + const preFail = await runtime.acquireNode({ ...baseReq, sessionId: sess1 }) + assert.equal(preFail.selected_node.node_key, 'claude_vm:vm-c1') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 1) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).blocked, true) + await runtime.releaseLease(preFail.lease_id, 'aborted') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 0) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 0) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).blocked, false) + + // 2. Commit records once and marks vm-c1 new_sessions_blocked=true (Codex stays false) + const acq1 = await runtime.acquireNode({ ...baseReq, sessionId: sess1 }) + assert.equal(acq1.selected_node.node_key, 'claude_vm:vm-c1') + await runtime.commitLease(acq1.lease_id) + await runtime.releaseLease(acq1.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).blocked, true) + + const telemetry = runtime.buildTelemetryBatch() + const c1Tel = telemetry.find((u) => u.node_key === 'claude_vm:vm-c1') + const c2Tel = telemetry.find((u) => u.node_key === 'claude_vm:vm-c2') + const x1Tel = telemetry.find((u) => u.node_key === 'codex_vm:vm-x1') + assert.equal(c1Tel.new_sessions_blocked, true) + assert.equal(c2Tel.new_sessions_blocked, false) + assert.equal(x1Tel.new_sessions_blocked, false) + await runtime.pushTelemetryNow(telemetry) + + // 3. Continuing session (session_hit), subagent, and ephemeral probe all bypass the gate on capped vm-c1 + const cont = await runtime.acquireNode({ ...baseReq, sessionId: sess1 }) + assert.equal(cont.selected_node.node_key, 'claude_vm:vm-c1') + assert.equal(cont.explain?.affinity?.why, 'session_hit') + await runtime.commitLease(cont.lease_id) + await runtime.releaseLease(cont.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'continuing session must not increment daily count') + + const sub = await runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440102', + parentSessionId: sess1, + }) + assert.equal(sub.selected_node.node_key, 'claude_vm:vm-c1') + await runtime.commitLease(sub.lease_id) + await runtime.releaseLease(sub.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'subagent must not increment daily count') + + const probe = await runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440103', + isEphemeralProbe: true, + pinNodeKey: 'claude_vm:vm-c1', + isAdminDiagnostic: true, + }) + assert.equal(probe.selected_node.node_key, 'claude_vm:vm-c1') + await runtime.releaseLease(probe.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'probe/admin-pin must not increment daily count') + + // 4. Race-guard: even if Rust telemetry is briefly stale (new_sessions_blocked=false on vm-c1), + // acquireNode aborts the capped vm-c1 lease and retries cleanly onto vm-c2! + await runtime.pushTelemetryNow([{ node_key: 'claude_vm:vm-c1', new_sessions_blocked: false }]) + const sess2 = '550e8400-e29b-41d4-a716-446655440104' + const acq2 = await runtime.acquireNode({ ...baseReq, sessionId: sess2 }) + assert.equal(acq2.selected_node.node_key, 'claude_vm:vm-c2') + await runtime.commitLease(acq2.lease_id) + await runtime.releaseLease(acq2.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[1]).used, 1) + assert.equal(dailySessionGate.statusForVm(fx.vms[1]).blocked, true) + + // 5. All Claude VMs capped -> acquireNode throws 429 daily_session_limit, explainDispatch reports daily_session_limit, and FailoverRunner maps cleanly to 429 + await runtime.pushTelemetryNow() + const sess3 = '550e8400-e29b-41d4-a716-446655440105' + const expCapped = await runtime.explainDispatch({ ...baseReq, sessionId: sess3 }) + assert.equal(expCapped.ok, false) + assert.equal(expCapped.error_code, 'daily_session_limit') + assert.ok(Number(expCapped.retry_after_sec) >= 1) + + await assert.rejects( + () => runtime.acquireNode({ ...baseReq, sessionId: sess3 }), + (err) => + err instanceof SchedulerApiError && + err.status === 429 && + err.code === 'daily_session_limit' && + Number(err.retryAfterSec) >= 1, + ) + + const runner = new FailoverRunner({ + scheduler: { markCooldown() {}, markSuccess() {}, setSchedulerRuntime() {} }, + schedulerRuntime: runtime, + }) + const cappedRes = await runner.run({ + requestId: 'req-dsg-capped', + canonicalBody: { model: 'claude-sonnet-4-6' }, + model: 'claude-sonnet-4-6', + stickyKey: '550e8400-e29b-41d4-a716-446655440106', + apiKeyRecord: { ...fx.strictKey, allowed_pool_ids: [fx.poolAnth.id] }, + apiKeyKind: 'managed', + originPoolId: fx.poolAnth.id, + callAttempt: async () => { + throw new Error('upstream must not be called when daily session gate blocks all VMs') + }, + }) + assert.equal(cappedRes.ok, false) + assert.equal(cappedRes.status, 429) + assert.equal(cappedRes.body?.error?.type, 'rate_limit_error') + assert.equal(cappedRes.body?.error?.code, 'daily_session_limit') + assert.ok(Number(cappedRes.retryAfterSec) >= 1) + assert.equal(JSON.stringify(cappedRes.body).includes('explain'), false) +}) + +test('M3 runtime + DailySessionGate: concurrent duplicate-session pre-commit release has zero leak & shared-account sibling telemetry pushes together', async (t) => { + const tmp = makeTempDir('vm2api-m3-dsg-sib-') + const fx = makeFixtureState(tmp) + // Share account_uuid between vm-c1 and vm-c2 to verify sibling telemetry push + fx.vms[0].claude = { ...(fx.vms[0].claude || {}), account_uuid: 'acc-shared-sib', subscription_type: 'pro' } + fx.vms[1].claude = { ...(fx.vms[1].claude || {}), account_uuid: 'acc-shared-sib', subscription_type: 'pro' } + + const gateConfig = { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 1, pro: 1, max_5x: 1, max_20x: 1, team: 1, enterprise: 1 }, + } + const dailySessionGate = createDailySessionGate({ config: gateConfig, db: fx.db }) + dailySessionGate.hydrate() + + const enqueuedTelemetry = [] + let leaseSeq = 0 + const fakeClient = { + stopped: false, + async acquire(req) { + leaseSeq += 1 + return { + lease_id: `lease-dup-${leaseSeq}`, + selected_node: { node_type: 'claude_vm', node_id: 'vm-c1', node_key: 'claude_vm:vm-c1' }, + resolved_pool_id: fx.poolAnth.id, + explain: { affinity: { why: 'load_balanced' } }, + } + }, + async release() { + return { ok: true, released: true } + }, + enqueueTelemetry(batch) { + enqueuedTelemetry.push(batch) + }, + } + + const runtime = createSchedulerRuntime({ + getDb: () => fx.db, + getVms: () => fx.vms, + getRoutingConfig: () => ({ quota: { daily_session_gate: gateConfig } }), + apiKeyStore: makeApiKeyStore(fx.db), + apiEndpointStore: { listRaw: () => fx.endpoints }, + geminiScheduler: { listEnvironments: () => fx.geminiEnvs }, + dailySessionGate, + telemetryIntervalMs: 0, + client: fakeClient, + }) + t.after(() => { + fx.db.close() + fs.rmSync(tmp, { recursive: true, force: true }) + }) + + const baseReq = { + originPoolId: fx.poolAnth.id, + apiKeyRecord: { ...fx.strictKey, allowed_pool_ids: [fx.poolAnth.id] }, + apiKeyKind: 'managed', + model: 'claude-sonnet-4-6', + protocol: 'anthropic', + sessionId: '550e8400-e29b-41d4-a716-446655440201', + } + + // 1. First acquire reserves slot -> newlyCapped pushes telemetry for BOTH vm-c1 and shared-account sibling vm-c2 + const acq1 = await runtime.acquireNode(baseReq) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 1) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).blocked, true) + const capBatch = enqueuedTelemetry.at(-1) || [] + assert.deepEqual( + capBatch.map((u) => [u.node_key, u.new_sessions_blocked]).sort(), + [ + ['claude_vm:vm-c1', true], + ['claude_vm:vm-c2', true], + ], + 'shared-account sibling VM must immediately receive new_sessions_blocked=true', + ) + + // 2. Concurrent duplicate-session acquire registers lease-dup-2 (duplicate: true, tracked: true) + const acq2 = await runtime.acquireNode(baseReq) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 1) + + // 3. Releasing BOTH pre-commit leases must NOT leak lease-dup-2; pending returns to 0 and unblocks both siblings + await runtime.releaseLease(acq1.lease_id, 'aborted') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 1) + await runtime.releaseLease(acq2.lease_id, 'aborted') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).pending, 0) + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).blocked, false) + const uncapBatch = enqueuedTelemetry.at(-1) || [] + assert.deepEqual( + uncapBatch.map((u) => [u.node_key, u.new_sessions_blocked]).sort(), + [ + ['claude_vm:vm-c1', false], + ['claude_vm:vm-c2', false], + ], + 'unblocking must push new_sessions_blocked=false to shared-account sibling VM too', + ) +}) + +test('server.mjs production wiring instantiates, hydrates, and injects dailySessionGate into all consumers', () => { + const serverSrc = fs.readFileSync(path.resolve(process.cwd(), 'src/server.mjs'), 'utf8') + assert.match(serverSrc, /import\s*\{\s*createDailySessionGate\s*\}\s*from\s*'\.\/lib\/pool\/daily-session-gate\.mjs'/) + assert.match(serverSrc, /dailySessionGate\s*=\s*createDailySessionGate\(\{/) + assert.match(serverSrc, /await\s+dailySessionGate\.hydrateAsync\(\)/) + assert.match(serverSrc, /dailySessionGate\.hydrate\(\)/) + + const routingRtBlock = serverSrc.slice( + serverSrc.indexOf('const routingRt = createRoutingRuntime('), + serverSrc.indexOf('const routingRt = createRoutingRuntime(') + 1200, + ) + assert.match(routingRtBlock, /dailySessionGate/) + + const agentBlock = serverSrc.slice( + serverSrc.indexOf('createHandleAgentSessions('), + serverSrc.indexOf('createHandleAgentSessions(') + 900, + ) + assert.match(agentBlock, /dailySessionGate/) + assert.match(agentBlock, /onDailySessionGateChange/) + + const schedBlock = serverSrc.slice( + serverSrc.indexOf('schedulerRuntime = createSchedulerRuntime('), + serverSrc.indexOf('schedulerRuntime = createSchedulerRuntime(') + 900, + ) + assert.match(schedBlock, /dailySessionGate/) + + const panelBlock = serverSrc.slice( + serverSrc.indexOf('const handlePanel = createPanelHandler('), + serverSrc.indexOf('const handlePanel = createPanelHandler(') + 1600, + ) + assert.match(panelBlock, /dailySessionGate/) + + const standbyBlock = serverSrc.slice( + serverSrc.indexOf('async function activateStandby('), + serverSrc.indexOf('async function activateStandby(') + 2500, + ) + assert.match(standbyBlock, /dailySessionGate\.hydrateAsync\(\)/) + assert.match(standbyBlock, /dailySessionGate\.hydrate\(\)/) + assert.ok( + standbyBlock.indexOf('dailySessionGate.hydrate') < standbyBlock.indexOf('schedulerRuntime.promoteToLeader'), + 'standby handover must re-hydrate dailySessionGate before promoting schedulerRuntime', + ) +}) diff --git a/test/unit/sqlite-to-pg-migration.test.mjs b/test/unit/sqlite-to-pg-migration.test.mjs index c88f24d176..6a6e6672e7 100644 --- a/test/unit/sqlite-to-pg-migration.test.mjs +++ b/test/unit/sqlite-to-pg-migration.test.mjs @@ -27,6 +27,7 @@ const PG_URL = process.env.VM2API_TEST_PG_URL || '' test('MIGRATION_TABLES and seedMockSqlite cover every active SQLite table including gemini_environment_owners', () => { assert.ok(MIGRATION_TABLES.includes('gemini_environment_owners')) assert.ok(MIGRATION_TABLES.includes('codex_slot_runtime')) + assert.ok(MIGRATION_TABLES.includes('vm_daily_session_creations')) const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-seed-check-')) try { const outPath = path.join(tmpDir, 'mock.db') @@ -37,6 +38,7 @@ test('MIGRATION_TABLES and seedMockSqlite cover every active SQLite table includ assert.deepEqual(empty, []) assert.ok(seeded.tableCounts.gemini_environment_owners >= 1) assert.ok(seeded.tableCounts.codex_slot_runtime >= 2) + assert.ok(seeded.tableCounts.vm_daily_session_creations >= 2) for (const table of Object.keys(seeded.tableCounts)) { if (table === 'schema_migrations') continue assert.ok(MIGRATION_TABLES.includes(table), `MIGRATION_TABLES missing active table: ${table}`) @@ -143,6 +145,7 @@ test('#1845: SQLite 069 and PostgreSQL 006 migrations add identical usage_logs a ) const usageCols = cols('usage_logs') const attemptCols = cols('request_attempts') + const dailyCols = cols('vm_daily_session_creations') db.close() const expectedUsage = ['upstream_type', 'error_details'] @@ -173,6 +176,17 @@ test('#1845: SQLite 069 and PostgreSQL 006 migrations add identical usage_logs a assert.ok(usageCols.has(col), `SQLite usage_logs missing ${col}`) assert.match(pgAdvisorSql, new RegExp(`ALTER TABLE usage_logs ADD COLUMN IF NOT EXISTS ${col}\\b`)) } + + const pgDailySql = fs.readFileSync( + path.join(root, 'src/lib/db/pg/pg-migrations/014_vm_daily_session_creations.sql'), + 'utf8', + ) + for (const col of ['platform', 'account_key', 'day_key', 'session_id', 'vm_id', 'created_at']) { + assert.ok(dailyCols.has(col), `SQLite vm_daily_session_creations missing ${col}`) + assert.match(pgDailySql, new RegExp(`\\b${col}\\b`)) + } + assert.match(pgDailySql, /created_at\s+BIGINT\s+NOT\s+NULL/i) + assert.match(pgDailySql, /idx_vm_daily_session_creations_created/i) } finally { fs.rmSync(tmpDir, { recursive: true, force: true }) } diff --git a/test/unit/vm-quota-override.test.mjs b/test/unit/vm-quota-override.test.mjs index 781f6bd339..91b03c2bd3 100644 --- a/test/unit/vm-quota-override.test.mjs +++ b/test/unit/vm-quota-override.test.mjs @@ -4,7 +4,31 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { AccountQuota } from '../../src/lib/pool/account-quota.mjs' -import { parseVmQuotaOverride, vmQuotaOverrideOf } from '../../src/lib/pool/vm-quota-override.mjs' +import { createDatabase } from '../../src/lib/db/database.mjs' +import { DailySessionGateRepo } from '../../src/lib/db/repos/daily-session-gate-repo.mjs' +import { + DAILY_SESSION_LIMIT_MAX, + DAILY_SESSION_PLATFORM_ANTHROPIC, + DAILY_SESSION_TIERS, + DailySessionGate, + createDailySessionGate, + isAnthropicSessionVm, + mergeDailySessionGate, + normalizeDailySessionGate, + resolveAccountSessionKey, + resolveAnthropicSessionTier, + resolveDayWindow, + resolveEffectiveDailySessionPolicy, + resolveInheritedDailySessionLimit, + validateDailySessionGatePatch, +} from '../../src/lib/pool/daily-session-gate.mjs' +import { + applyVmQuotaConfig, + applyVmQuotaPolicy, + parseVmQuotaOverride, + vmQuotaOverrideOf, + vmQuotaView, +} from '../../src/lib/pool/vm-quota-override.mjs' function quota() { return new AccountQuota({ @@ -68,3 +92,481 @@ test('stored session window fields are ignored on read', () => { }) assert.equal(parseVmQuotaOverride({ max_sessions: 1 }).ok, false) }) + +test('per-VM daily_session_limit override parses, applies, and renders vmQuotaView cleanly', () => { + assert.deepEqual(parseVmQuotaOverride({ daily_session_limit: null }), { ok: true, value: null }) + assert.deepEqual(parseVmQuotaOverride({ daily_session_limit: 0 }), { ok: true, value: { daily_session_limit: 0 } }) + assert.deepEqual(parseVmQuotaOverride({ daily_session_limit: 1 }), { ok: true, value: { daily_session_limit: 1 } }) + assert.deepEqual(parseVmQuotaOverride({ daily_session_limit: DAILY_SESSION_LIMIT_MAX }), { + ok: true, + value: { daily_session_limit: DAILY_SESSION_LIMIT_MAX }, + }) + for (const bad of [-1, DAILY_SESSION_LIMIT_MAX + 1, 1.5, '10', true, Number.NaN, Number.POSITIVE_INFINITY]) { + assert.equal(parseVmQuotaOverride({ daily_session_limit: bad }).ok, false, `should reject ${String(bad)}`) + } + + assert.deepEqual(vmQuotaOverrideOf({ policy: { quota: { daily_session_limit: 0 } } }), { daily_session_limit: 0 }) + assert.deepEqual(vmQuotaOverrideOf({ policy: { quota: { daily_session_limit: -5, limit_5h: 0.9 } } }), { + limit_5h: 0.9, + }) + + const basePolicy = { limit_5h: 0.85, limit_7d: 0.8 } + const baseQuota = { block_on_5h: true, block_on_7d: true } + + // Inherited view uses extra inherited limit; override 0 explicitly beats inherited 20 + assert.equal(vmQuotaView(basePolicy, baseQuota, { daily_session_limit: 20 }).daily_session_limit, 20) + const zeroOverride = { daily_session_limit: 0 } + assert.equal( + vmQuotaView(applyVmQuotaPolicy(basePolicy, zeroOverride), applyVmQuotaConfig(baseQuota, zeroOverride), { + daily_session_limit: 20, + }).daily_session_limit, + 0, + ) + const capOverride = { daily_session_limit: 35 } + assert.equal( + vmQuotaView(applyVmQuotaPolicy(basePolicy, capOverride), applyVmQuotaConfig(baseQuota, capOverride), { + daily_session_limit: 0, + }).daily_session_limit, + 35, + ) + // Legacy 2-arg call remains backward-compatible + assert.equal(vmQuotaView(basePolicy, baseQuota).daily_session_limit, 0) +}) + +test('resolveAnthropicSessionTier covers all 6 tiers, default_claude_ai veto, free/unknown, and Codex bypass', () => { + assert.deepEqual(DAILY_SESSION_TIERS, ['default', 'pro', 'max_5x', 'max_20x', 'team', 'enterprise']) + + // rate_limit_tier precedence + assert.equal( + resolveAnthropicSessionTier({ claude: { rate_limit_tier: 'default_claude_max_20x', subscription_type: 'max' } }), + 'max_20x', + ) + assert.equal(resolveAnthropicSessionTier({ rate_limit_tier: 'max_20x' }), 'max_20x') + assert.equal(resolveAnthropicSessionTier({ rate_limit_tier: '20x' }), 'max_20x') + assert.equal( + resolveAnthropicSessionTier({ claude: { rate_limit_tier: 'default_claude_max_5x', subscription_type: 'max' } }), + 'max_5x', + ) + assert.equal(resolveAnthropicSessionTier({ rate_limit_tier: '5x' }), 'max_5x') + assert.equal(resolveAnthropicSessionTier({ rate_limit_tier: 'default_claude_enterprise' }), 'enterprise') + assert.equal(resolveAnthropicSessionTier({ rate_limit_tier: 'default_claude_team' }), 'team') + + // subscription_type precedence + assert.equal(resolveAnthropicSessionTier({ claude: { subscription_type: 'Enterprise' } }), 'enterprise') + assert.equal(resolveAnthropicSessionTier({ subscription_type: 'team' }), 'team') + assert.equal(resolveAnthropicSessionTier({ subscription_type: 'pro' }), 'pro') + assert.equal(resolveAnthropicSessionTier({ subscription_type: 'max' }), 'max_5x') + assert.equal( + resolveAnthropicSessionTier({ subscription_type: 'free', rate_limit_tier: 'default_claude_ai' }), + 'default', + ) + + // default_claude_ai vetoes usage-derived account_tier=max + assert.equal( + resolveAnthropicSessionTier({ claude: { rate_limit_tier: 'default_claude_ai', account_tier: 'max' } }), + 'pro', + ) + assert.equal(resolveAnthropicSessionTier({ claude: { account_tier: 'max' } }), 'max_5x') + assert.equal(resolveAnthropicSessionTier({ claude: { account_tier: 'pro' } }), 'pro') + assert.equal(resolveAnthropicSessionTier({ id: 'vm-unknown' }), 'default') + + // Account key SSOT + assert.equal(resolveAccountSessionKey({ id: 'vm-1', claude: { account_uuid: 'acc-uuid-1' } }), 'acc-uuid-1') + assert.equal(resolveAccountSessionKey({ id: 'vm-1', account_uuid: 'acc-uuid-2' }), 'acc-uuid-2') + assert.equal(resolveAccountSessionKey({ id: 'vm-fallback' }), 'vm-fallback') + + // Anthropic-only check + assert.equal(isAnthropicSessionVm({ id: 'vm-claude' }), true) + assert.equal(isAnthropicSessionVm({ id: 'vm-codex', kind: 'codex' }), false) + assert.equal(isAnthropicSessionVm({ id: 'vm-openai', provider: 'openai' }), false) + assert.equal(isAnthropicSessionVm({ id: 'vm-gemini', platform: 'gemini' }), false) +}) + +test('resolveEffectiveDailySessionPolicy enforces override precedence and never falls back to default when tier=0', () => { + const gateOn = { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 10, pro: 0, max_5x: 50, max_20x: 100, team: 80, enterprise: 200 }, + } + const gateOff = { ...gateOn, enabled: false } + + const proVm = { id: 'vm-pro', claude: { subscription_type: 'pro' } } + const max5Vm = { id: 'vm-m5', claude: { rate_limit_tier: 'default_claude_max_5x' } } + const codexVm = { id: 'vm-codex', kind: 'codex' } + + // Tier=0 means unlimited, never silently falls back to default=10 + assert.deepEqual(resolveEffectiveDailySessionPolicy(proVm, gateOn), { + enabled: true, + active: false, + limit: 0, + tier_key: 'pro', + source: 'tier', + }) + assert.equal(resolveInheritedDailySessionLimit(proVm, gateOn), 0) + assert.equal(resolveInheritedDailySessionLimit(max5Vm, gateOn), 50) + + // Global disabled -> disabled unless per-VM positive override + assert.deepEqual(resolveEffectiveDailySessionPolicy(max5Vm, gateOff), { + enabled: false, + active: false, + limit: 0, + tier_key: 'max_5x', + source: 'disabled', + }) + const cappedWhileOff = { ...max5Vm, policy: { quota: { daily_session_limit: 12 } } } + assert.deepEqual(resolveEffectiveDailySessionPolicy(cappedWhileOff, gateOff), { + enabled: false, + active: true, + limit: 12, + tier_key: 'max_5x', + source: 'override', + }) + + // Per-VM override=0 exempts VM even when global gate enabled + const exemptedWhileOn = { ...max5Vm, policy: { quota: { daily_session_limit: 0 } } } + assert.deepEqual(resolveEffectiveDailySessionPolicy(exemptedWhileOn, gateOn), { + enabled: true, + active: false, + limit: 0, + tier_key: 'max_5x', + source: 'override', + }) + + // Codex VM is unsupported + assert.deepEqual(resolveEffectiveDailySessionPolicy(codexVm, gateOn), { + enabled: true, + active: false, + limit: 0, + tier_key: 'default', + source: 'unsupported', + }) +}) + +test('validateDailySessionGatePatch rejects every single invalid rule with code=invalid_quota_config', () => { + const assertInvalid = (patch, label) => { + assert.throws( + () => validateDailySessionGatePatch(patch), + (err) => err instanceof TypeError && err.code === 'invalid_quota_config', + `expected invalid_quota_config for ${label}`, + ) + } + + assertInvalid(null, 'null') + assertInvalid([], 'array') + assertInvalid('on', 'string') + assertInvalid({ extra_key: true }, 'unknown top-level key') + assertInvalid({ enabled: 'true' }, 'non-boolean enabled') + assertInvalid({ enabled: 1 }, 'numeric enabled') + assertInvalid({ reset_timezone: '' }, 'empty timezone') + assertInvalid({ reset_timezone: 123 }, 'numeric timezone') + assertInvalid({ reset_timezone: 'Mars/Olympus' }, 'invalid IANA timezone') + assertInvalid({ reset_timezone: '+08:00' }, 'numeric offset timezone') + assertInvalid({ tier_limits: null }, 'null tier_limits') + assertInvalid({ tier_limits: [] }, 'array tier_limits') + assertInvalid({ tier_limits: { ultra: 10 } }, 'unknown tier key') + assertInvalid({ tier_limits: { pro: -1 } }, 'negative tier limit') + assertInvalid({ tier_limits: { pro: 1.5 } }, 'float tier limit') + assertInvalid({ tier_limits: { pro: '10' } }, 'string tier limit') + assertInvalid({ tier_limits: { pro: true } }, 'boolean tier limit') + assertInvalid({ tier_limits: { pro: DAILY_SESSION_LIMIT_MAX + 1 } }, 'over-max tier limit') + + // Valid patches pass + validateDailySessionGatePatch({}) + validateDailySessionGatePatch({ + enabled: true, + reset_timezone: 'asia/shanghai', + tier_limits: { default: 0, pro: 20, max_5x: 50, max_20x: 100, team: 80, enterprise: DAILY_SESSION_LIMIT_MAX }, + }) + + const normalized = normalizeDailySessionGate({ + enabled: true, + reset_timezone: 'asia/shanghai', + tier_limits: { pro: 25, max_5x: true, team: -3 }, + }) + assert.deepEqual(normalized, { + enabled: true, + reset_timezone: 'Asia/Shanghai', + tier_limits: { default: 0, pro: 25, max_5x: 0, max_20x: 0, team: 0, enterprise: 0 }, + }) + const merged = mergeDailySessionGate(normalized, { tier_limits: { max_5x: 60 } }) + assert.equal(merged.tier_limits.pro, 25) + assert.equal(merged.tier_limits.max_5x, 60) + assert.equal(merged.reset_timezone, 'Asia/Shanghai') +}) + +test('DailySessionGate enforces concurrency reservations, pre-commit release, idempotent commit, shared account_uuid, and SQLite restart hydration', (t) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-dsg-')) + t.after(() => fs.rmSync(tmpDir, { recursive: true, force: true })) + const db = createDatabase({ dbPath: path.join(tmpDir, 'kin.db') }) + t.after(() => db.close()) + + const t0 = Date.parse('2026-12-01T10:00:00.000Z') + const vmA = { id: 'vm-a', claude: { account_uuid: 'acc-shared', subscription_type: 'pro' } } + const vmB = { id: 'vm-b', claude: { account_uuid: 'acc-shared', subscription_type: 'pro' } } + const codexVm = { id: 'vm-codex', kind: 'codex' } + + const config = { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 0, pro: 2, max_5x: 0, max_20x: 0, team: 0, enterprise: 0 }, + } + const gate = createDailySessionGate({ config, db }) + gate.hydrate(t0) + + // Reserve 2 concurrent sessions across two VMs sharing the same account_uuid + const r1 = gate.tryReserveNewSession({ vm: vmA, sessionId: 'sess-1', leaseToken: 'tok-1', now: t0 }) + assert.equal(r1.ok, true) + assert.equal(r1.reserved, true) + assert.equal(r1.newlyCapped, false) + assert.equal(r1.status.pending, 1) + assert.equal(r1.status.remaining, 1) + + // Duplicate sessionId on another token must not consume a second slot + const r1Dup = gate.tryReserveNewSession({ vm: vmB, sessionId: 'sess-1', leaseToken: 'tok-1b', now: t0 + 10 }) + assert.equal(r1Dup.ok, true) + assert.equal(r1Dup.duplicate, true) + assert.equal(r1Dup.status.pending, 1) + + const r2 = gate.tryReserveNewSession({ vm: vmB, sessionId: 'sess-2', leaseToken: 'tok-2', now: t0 + 20 }) + assert.equal(r2.ok, true) + assert.equal(r2.newlyCapped, true) + assert.equal(r2.status.pending, 2) + assert.equal(r2.status.remaining, 0) + assert.equal(r2.status.blocked, true) + assert.equal(gate.isVmNewSessionsBlocked(vmA, t0 + 25), true) + + // 3rd concurrent new session is rejected while 2 are pending + const r3Blocked = gate.tryReserveNewSession({ vm: vmA, sessionId: 'sess-3', leaseToken: 'tok-3', now: t0 + 30 }) + assert.equal(r3Blocked.ok, false) + assert.equal(r3Blocked.reason, 'daily_session_limit') + + // Codex VM is never blocked or counted + assert.equal( + gate.tryReserveNewSession({ vm: codexVm, sessionId: 'sess-c', leaseToken: 'tok-c', now: t0 + 35 }).ok, + true, + ) + assert.equal(gate.statusForVm(codexVm, t0 + 35).source, 'unsupported') + + // Pre-commit failure releases reservation without counting and unblocks + const rel = gate.releaseReservation('tok-2', t0 + 40) + assert.equal(rel.released, true) + assert.equal(rel.uncapped, true) + assert.equal(gate.statusForVm(vmA, t0 + 45).pending, 1) + assert.equal(gate.statusForVm(vmA, t0 + 45).blocked, false) + + // Commit sess-1 (idempotent: second commit is a no-op) + const c1 = gate.commitReservation('tok-1', { now: t0 + 50 }) + assert.equal(c1.recorded, true) + assert.equal(c1.duplicate, false) + assert.equal(gate.hasCommittedSession(vmA, 'sess-1', t0 + 55), true) + const c1Again = gate.commitReservation('tok-1', { vm: vmA, sessionId: 'sess-1', now: t0 + 60 }) + assert.equal(c1Again.recorded, false) + assert.equal(c1Again.duplicate, true) + + // Reserve and commit sess-3 -> hits cap 2/2 + const r3 = gate.tryReserveNewSession({ vm: vmA, sessionId: 'sess-3', leaseToken: 'tok-3', now: t0 + 70 }) + assert.equal(r3.ok, true) + const c3 = gate.commitReservation('tok-3', { now: t0 + 80 }) + assert.equal(c3.recorded, true) + assert.equal(c3.status.used, 2) + assert.equal(c3.status.pending, 0) + assert.equal(c3.status.blocked, true) + + // Already-committed session stays accepted even when capped + assert.equal(gate.canAcceptNewSession(vmA, 'sess-1', t0 + 90).ok, true) + assert.equal(gate.canAcceptNewSession(vmA, 'sess-4', t0 + 90).ok, false) + + // Simulate process restart: new gate hydrates persisted count from SQLite + const restarted = createDailySessionGate({ config, db }) + const hydrated = restarted.hydrate(t0 + 100) + assert.equal(hydrated.loaded, 2) + const statusAfterRestart = restarted.statusForVm(vmB, t0 + 100) + assert.equal(statusAfterRestart.used, 2) + assert.equal(statusAfterRestart.blocked, true) + assert.equal(statusAfterRestart.day_key, '2026-12-01') + assert.equal(statusAfterRestart.timezone, 'UTC') +}) + +test('DailySessionGate handles calendar-day rollover, DST transitions, mid-day timezone switch, and mid-day enable', (t) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-dsg-tz-')) + t.after(() => fs.rmSync(tmpDir, { recursive: true, force: true })) + const db = createDatabase({ dbPath: path.join(tmpDir, 'kin.db') }) + t.after(() => db.close()) + + // DST spring-forward in America/New_York: 2026-03-08 is a 23-hour day (05:00Z -> next day 04:00Z) + const dstWin = resolveDayWindow(Date.parse('2026-03-08T12:00:00.000Z'), 'America/New_York') + assert.equal(dstWin.dayKey, '2026-03-08') + assert.equal(dstWin.resetAtMs - dstWin.dayStartMs, 23 * 3600_000) + + const vm = { id: 'vm-tz', claude: { account_uuid: 'acc-tz', subscription_type: 'pro' } } + // Start with gate disabled -> commits must still be tracked for observability & mid-day enable + const gate = new DailySessionGate({ + config: { enabled: false, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, + db, + }) + const tEarlyUtc = Date.parse('2026-12-01T10:00:00.000Z') // before 16:00Z (Shanghai midnight) + const tLateUtc = Date.parse('2026-12-01T18:00:00.000Z') // after 16:00Z (Shanghai 2026-12-02 02:00) + + gate.tryReserveNewSession({ vm, sessionId: 's-early', leaseToken: 'lt-1', now: tEarlyUtc }) + gate.commitReservation('lt-1', { now: tEarlyUtc }) + gate.tryReserveNewSession({ vm, sessionId: 's-late', leaseToken: 'lt-2', now: tLateUtc }) + gate.commitReservation('lt-2', { now: tLateUtc }) + + // Still disabled -> used=2, blocked=false + const offStatus = gate.statusForVm(vm, tLateUtc + 1000) + assert.equal(offStatus.used, 2) + assert.equal(offStatus.active, false) + assert.equal(offStatus.blocked, false) + + // Enable mid-day -> immediately blocked because 2 sessions were already created today in UTC + gate.reloadConfig({ enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, tLateUtc + 2000) + assert.equal(gate.statusForVm(vm, tLateUtc + 2000).blocked, true) + + // Switch timezone mid-day to Asia/Shanghai at 18:00Z (= 2026-12-02 02:00+08:00, dayStart = 16:00Z) + // Only s-late (18:00Z) falls inside Shanghai's 2026-12-02 window; s-early (10:00Z) drops out! + const reloaded = gate.reloadConfig( + { enabled: true, reset_timezone: 'Asia/Shanghai', tier_limits: { pro: 2 } }, + tLateUtc + 3000, + ) + assert.equal(reloaded.timezoneChanged, true) + const shStatus = gate.statusForVm(vm, tLateUtc + 3000) + assert.equal(shStatus.day_key, '2026-12-02') + assert.equal(shStatus.timezone, 'Asia/Shanghai') + assert.equal(shStatus.used, 1) + assert.equal(shStatus.remaining, 1) + assert.equal(shStatus.blocked, false) + + // Switch back to UTC -> re-hydrates s-early from SQLite DB so used becomes 2 again! + gate.reloadConfig({ enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, tLateUtc + 4000) + assert.equal(gate.statusForVm(vm, tLateUtc + 4000).used, 2) + assert.equal(gate.statusForVm(vm, tLateUtc + 4000).blocked, true) + + // Rollover into next UTC day clears in-memory count and opportunistically prunes >7d rows + const oldRowMs = tEarlyUtc - 10 * 86_400_000 + db.prepare( + 'INSERT INTO vm_daily_session_creations (platform, account_key, day_key, session_id, vm_id, created_at) VALUES (?, ?, ?, ?, ?, ?)', + ).run(DAILY_SESSION_PLATFORM_ANTHROPIC, 'acc-tz', '2026-11-21', 's-old', 'vm-tz', oldRowMs) + + const nextDayMs = Date.parse('2026-12-02T00:00:05.000Z') + const nextStatus = gate.statusForVm(vm, nextDayMs) + assert.equal(nextStatus.day_key, '2026-12-02') + assert.equal(nextStatus.used, 0) + assert.equal(nextStatus.blocked, false) + const oldRowCount = db + .prepare("SELECT COUNT(*) AS c FROM vm_daily_session_creations WHERE session_id = 's-old'") + .get().c + assert.equal(oldRowCount, 0, 'rollover should opportunistically prune rows older than retention window') +}) + +test('DailySessionGateRepo PG async mode executes non-blocking pgPool queries with zero sync db.prepare calls', async () => { + const queries = [] + let prepareCalls = 0 + const fakeSyncDb = { + engine: 'postgres', + prepare() { + prepareCalls += 1 + throw new Error('sync db.prepare must never be called in PG async mode') + }, + } + const fakePgPool = { + async query(sql, params) { + queries.push({ sql: String(sql), params }) + if (/^SELECT /i.test(String(sql))) { + return { + rows: [ + { + platform: 'anthropic', + account_key: 'acc-pg', + day_key: '2026-12-01', + session_id: 'pg-s1', + vm_id: 'vm-pg', + created_at: String(Date.parse('2026-12-01T08:00:00.000Z')), + }, + ], + } + } + return { rows: [], rowCount: 1 } + }, + } + + const repo = new DailySessionGateRepo({ db: fakeSyncDb, pgPool: fakePgPool }) + assert.equal(repo.isPgAsyncMode, true) + assert.deepEqual( + repo.listSince('anthropic', 0), + [], + 'sync listSince returns [] in PG mode without touching sync bridge', + ) + + const gate = new DailySessionGate({ + config: { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, + repo, + }) + const tNow = Date.parse('2026-12-01T12:00:00.000Z') + const hydrated = await gate.hydrateAsync(tNow) + assert.equal(hydrated.loaded, 1) + + const vm = { id: 'vm-pg', claude: { account_uuid: 'acc-pg', subscription_type: 'pro' } } + assert.equal(gate.statusForVm(vm, tNow).used, 1) + + gate.tryReserveNewSession({ vm, sessionId: 'pg-s2', leaseToken: 'pg-tok-2', now: tNow }) + gate.commitReservation('pg-tok-2', { now: tNow }) + await new Promise((resolve) => setImmediate(resolve)) + + assert.equal(prepareCalls, 0, 'PG hot path must have zero sync db.prepare / Atomics.wait calls') + assert.ok(queries.some((q) => /ON CONFLICT \(platform, account_key, day_key, session_id\) DO NOTHING/i.test(q.sql))) + assert.equal(gate.statusForVm(vm, tNow).blocked, true) +}) + +test('DailySessionGate releases concurrent duplicate-session pending reservations without leaking blocked state', () => { + const t0 = Date.parse('2026-12-01T10:00:00.000Z') + const vm = { id: 'vm-dup', claude: { account_uuid: 'acc-dup', subscription_type: 'pro' } } + const gate = createDailySessionGate({ + config: { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 0, pro: 1, max_5x: 0, max_20x: 0, team: 0, enterprise: 0 }, + }, + }) + + // Two concurrent requests reserve the same uncommitted sessionId + const r1 = gate.tryReserveNewSession({ vm, sessionId: 'sess-dup', leaseToken: 'tok-dup-1', now: t0 }) + assert.equal(r1.ok, true) + assert.equal(r1.reserved, true) + assert.equal(r1.duplicate, false) + assert.equal(r1.tracked, true) + assert.equal(r1.status.pending, 1) + assert.equal(r1.status.blocked, true) + + const r2 = gate.tryReserveNewSession({ vm, sessionId: 'sess-dup', leaseToken: 'tok-dup-2', now: t0 + 10 }) + assert.equal(r2.ok, true) + assert.equal(r2.reserved, false) + assert.equal(r2.duplicate, true) + assert.equal(r2.tracked, true) + assert.equal(r2.status.pending, 1) + assert.equal(r2.status.blocked, true) + + // First fails pre-commit: second is still pending, so pending stays 1 + const rel1 = gate.releaseReservation('tok-dup-1', t0 + 20) + assert.equal(rel1.released, true) + assert.equal(rel1.uncapped, false) + assert.equal(gate.statusForVm(vm, t0 + 25).pending, 1) + assert.equal(gate.statusForVm(vm, t0 + 25).blocked, true) + + // Second ALSO fails pre-commit: releasing tok-dup-2 frees the slot completely + const rel2 = gate.releaseReservation('tok-dup-2', t0 + 30) + assert.equal(rel2.released, true) + assert.equal(rel2.uncapped, true) + const finalStatus = gate.statusForVm(vm, t0 + 35) + assert.equal(finalStatus.pending, 0) + assert.equal(finalStatus.used, 0) + assert.equal(finalStatus.blocked, false) + + // Committing one concurrent duplicate token cleans up sibling pending tokens + gate.tryReserveNewSession({ vm, sessionId: 'sess-dup-commit', leaseToken: 'tok-c1', now: t0 + 40 }) + gate.tryReserveNewSession({ vm, sessionId: 'sess-dup-commit', leaseToken: 'tok-c2', now: t0 + 45 }) + const committed = gate.commitReservation('tok-c1', { now: t0 + 50 }) + assert.equal(committed.recorded, true) + assert.equal(gate.releaseReservation('tok-c2', t0 + 55).released, false) + assert.equal(gate.statusForVm(vm, t0 + 60).pending, 0) + assert.equal(gate.statusForVm(vm, t0 + 60).used, 1) +}) diff --git a/web/src/features/pools/pool-rules.ts b/web/src/features/pools/pool-rules.ts index 6286f95eb8..7bcaab5023 100644 --- a/web/src/features/pools/pool-rules.ts +++ b/web/src/features/pools/pool-rules.ts @@ -788,6 +788,9 @@ const EXCLUDED_REASON_LABELS: Record = { tenant_mismatch: '租户隔离不匹配', member_disabled: '池成员已停用', capacity_full: '并发/席位已满', + new_session_blocked: '暂停接新会话(每日上限 / 保护区)', + new_sessions_blocked: '暂停接新会话(每日上限 / 保护区)', + daily_session_limit: '今日新会话上限', } export function formatAffinityWhy(why: string | null | undefined): { diff --git a/web/src/features/pools/pools.test.ts b/web/src/features/pools/pools.test.ts index 0534945c1f..5622aacea5 100644 --- a/web/src/features/pools/pools.test.ts +++ b/web/src/features/pools/pools.test.ts @@ -13,6 +13,7 @@ import { buildPoolPayload, createDefaultPoolDraft, defaultSystemPromptModeForProvider, + formatExcludedReason, formatExplainSummary, formatTtlLabel, isPromptLockedProvider, @@ -472,6 +473,13 @@ describe('Explain result formatting', () => { expect(summary.excludedCount).toBe(2) expect(summary.excludedItems[0].reasonLabel).toBe('冷却中') expect(summary.excludedItems[1].reasonLabel).toContain('95%') + expect(formatExcludedReason('new_session_blocked')).toContain( + '暂停接新会话' + ) + expect(formatExcludedReason('new_sessions_blocked')).toContain( + '暂停接新会话' + ) + expect(formatExcludedReason('daily_session_limit')).toBe('今日新会话上限') }) }) diff --git a/web/src/features/settings/index.tsx b/web/src/features/settings/index.tsx index e6b45c84a6..f37fb36f56 100644 --- a/web/src/features/settings/index.tsx +++ b/web/src/features/settings/index.tsx @@ -189,7 +189,7 @@ export function SettingsPage() { title={VIEW_TITLES.settings} description={ tab === 'quota' - ? 'Claude 配额闸线、并发、RPM,以及请求体上限。GPT 配额在 OpenAI 页。个人自用引导会把闸关掉并拉到上限;这里仍可再改。' + ? 'Claude 配额闸线、执行并发、RPM、每日新会话闸门,以及请求体上限。GPT 配额在 OpenAI 页。个人自用引导会把闸关掉并拉到上限;这里仍可再改。' : tab === 'openai' ? 'GPT 传输、准入、配额与客户端画像。全局 WebSocket 只作用于推理,不影响终端或集群。' : tab === 'gemini-config' @@ -307,6 +307,27 @@ export function SettingsPage() { const currentWeekly = (currentQuota.weekly_split as Record | undefined) || {} + const currentDaily = + (currentQuota.daily_session_gate as + Record | undefined) || {} + const patchDaily = + patch.daily_session_gate && + typeof patch.daily_session_gate === 'object' && + !Array.isArray(patch.daily_session_gate) + ? (patch.daily_session_gate as Record< + string, + unknown + >) + : null + const currentDailyLimits = + (currentDaily.tier_limits as + Record | undefined) || {} + const patchDailyLimits = + patchDaily?.tier_limits && + typeof patchDaily.tier_limits === 'object' && + !Array.isArray(patchDaily.tier_limits) + ? (patchDaily.tier_limits as Record) + : null return { ...current, quota: { @@ -323,6 +344,22 @@ export function SettingsPage() { }, } : {}), + ...(patchDaily + ? { + daily_session_gate: { + ...currentDaily, + ...patchDaily, + ...(patchDailyLimits + ? { + tier_limits: { + ...currentDailyLimits, + ...patchDailyLimits, + }, + } + : {}), + }, + } + : {}), }, } }) diff --git a/web/src/features/settings/quota-controls.tsx b/web/src/features/settings/quota-controls.tsx index 1e76707ce7..5b8d808573 100644 --- a/web/src/features/settings/quota-controls.tsx +++ b/web/src/features/settings/quota-controls.tsx @@ -142,11 +142,17 @@ export function PlatformAccountList({ {items.map((vm) => { const hasSource = platform === 'claude' - ? Object.keys(recordOf(vm.quota_override)).length > 0 + ? Object.values(recordOf(vm.quota_override)).some((v) => v != null) : vm.concurrency_override === true || vm.rpm_override === true || vm.max_sessions_override === true const status = vm.availability?.text || vm.status || '状态未知' + const daily = + platform === 'claude' && + vm.daily_sessions && + vm.daily_sessions.source !== 'unsupported' + ? vm.daily_sessions + : null return (
来源:{hasSource ? '本槽覆盖' : '跟随全局'} 状态:{status} + {daily ? ( + + 今日新会话:{daily.used}/ + {daily.limit > 0 ? daily.limit : '不限'} + + ) : null}
} +function cloneQuotaDraft(source: Obj): Obj { + const rawGate = recordOf(source.daily_session_gate) + const normalized = normalizeDailySessionGate(rawGate) + return { + ...source, + ...(source.weekly_split && typeof source.weekly_split === 'object' + ? { weekly_split: { ...recordOf(source.weekly_split) } } + : {}), + daily_session_gate: { + enabled: normalized.enabled, + reset_timezone: + typeof rawGate.reset_timezone === 'string' + ? rawGate.reset_timezone + : normalized.reset_timezone, + tier_limits: { ...normalized.tier_limits }, + }, + } +} + function ratioValue( policy: QuotaTierPolicy, key: 'limit_5h' | 'limit_7d', @@ -448,6 +480,133 @@ function ClaudeRpm({ ) } +function ClaudeDailySessionGate({ + quota, + onGateChange, +}: { + quota: Obj + onGateChange: (next: Obj) => void +}) { + const rawGate = recordOf(quota.daily_session_gate) + const normalized = normalizeDailySessionGate(rawGate) + const enabled = rawGate.enabled === true + const tzValue = + typeof rawGate.reset_timezone === 'string' + ? rawGate.reset_timezone + : normalized.reset_timezone + const tzValid = Boolean(validTimezone(tzValue)) + const tzNow = tzValid ? zoneNowLabel(tzValue) : '' + const gateError = dailySessionGateError(quota) + + const patchGate = (patch: Obj) => + onGateChange({ + enabled, + reset_timezone: tzValue, + tier_limits: { ...normalized.tier_limits }, + ...patch, + }) + + const setTierLimit = (key: DailySessionTierKey, next: number) => + patchGate({ + tier_limits: { + ...normalized.tier_limits, + [key]: Math.min(DAILY_SESSION_LIMIT_MAX, Math.max(0, Math.round(next))), + }, + }) + + return ( +
+
+
+ +

+ 按自然日限制单个 Anthropic / Claude 账号新建主会话的总数。达到上限后 + 仅拦截新主会话落入该账号,既有对话与子代理继续放行,跨日自动恢复。 +

+
+ patchGate({ enabled: next })} + /> +
+ +
+
+
+ +

+ 每日 00:00 按此时区重置计数;默认 UTC,可改为 Asia/Shanghai 或任意 + IANA 时区。 +

+
+ {tzNow ? ( + + 当前 {tzNow} + + ) : null} +
+ patchGate({ reset_timezone })} + /> + {!tzValid ? ( +

+ 重置时区无效,请填写合法的 IANA 时区名称(例如 UTC、Asia/Shanghai) +

+ ) : null} +
+ +
+
+
按账号等级配置每日上限
+

+ 0 表示该等级不限(不会回落到「默认」);单槽可在 VM + 调度弹窗单独覆盖。 + {!enabled ? ' 当前总开关未启用,可先预设各等级上限再开启。' : ''} +

+
+
+ {DAILY_SESSION_TIER_META.map((item) => { + const value = normalized.tier_limits[item.key] + return ( +
+ setTierLimit(item.key, next)} + /> + setTierLimit(item.key, next)} + /> +
+ ) + })} +
+
+ + {gateError && tzValid ? ( +

+ {gateError} +

+ ) : null} +
+ ) +} + export function QuotaTierPane({ tiers, quota, @@ -468,7 +627,9 @@ export function QuotaTierPane({ onFailoverChange: (patch: Obj) => void saving?: boolean pending?: boolean - pendingCards?: Partial> + pendingCards?: Partial< + Record<'gates' | 'concurrency' | 'rpm' | 'dailySessions', boolean> + > maxBodyMib?: number }) { const list = useQuery(vmsListQueryOptions(5000)) @@ -477,7 +638,9 @@ export function QuotaTierPane({ const [draftTiers, setDraftTiers] = useState< Record >(cloneTiers(tiers)) - const [draftQuota, setDraftQuota] = useState({ ...quota }) + const [draftQuota, setDraftQuota] = useState(() => + cloneQuotaDraft(quota) + ) const [weeklyExpanded, setWeeklyExpanded] = useState(false) const triggerRefs = useRef< Partial> @@ -494,7 +657,7 @@ export function QuotaTierPane({ const openDialog = (kind: DialogKind) => { if (saving) return setDraftTiers(cloneTiers(tiers)) - setDraftQuota({ ...quota }) + setDraftQuota(cloneQuotaDraft(quota)) setTier('default') setWeeklyExpanded(false) setDialog(kind) @@ -503,6 +666,7 @@ export function QuotaTierPane({ if (!saving) setDialog(null) } const gatesOrderError = exhaustionGuardOrderError(draftQuota) + const dailySessionError = dailySessionGateError(draftQuota) const apply = () => { if (!dialog || saving) return if (dialog === 'details') { @@ -570,6 +734,13 @@ export function QuotaTierPane({ max_rpm: numberOf(policy.max_rpm, TIER_DEFAULTS[key].max_rpm), }) }) + } else if (dialog === 'daily_sessions') { + if (dailySessionError) return + onQuotaChange({ + daily_session_gate: normalizeDailySessionGate( + draftQuota.daily_session_gate + ), + }) } setDialog(null) } @@ -602,7 +773,9 @@ export function QuotaTierPane({ ? '执行并发' : dialog === 'rpm' ? '请求速率' - : '生效账号与本槽覆盖' + : dialog === 'daily_sessions' + ? '每日新会话闸门' + : '生效账号与本槽覆盖' return (
@@ -611,7 +784,7 @@ export function QuotaTierPane({ title='Claude 配额' desc={`${claudeItems.length} 个账号。GPT 配额在 OpenAI 页。`} > -
+
openDialog('rpm')} /> + { + triggerRefs.current.daily_sessions = node + }} + disabled={saving} + onClick={() => openDialog('daily_sessions')} + />
{isCodexVm(vm) ? null : ( <> + {vm.daily_sessions && + vm.daily_sessions.source !== 'unsupported' ? ( + +
+
+ {vm.daily_sessions.used} /{' '} + {vm.daily_sessions.limit > 0 + ? vm.daily_sessions.limit + : '不限'} + {vm.daily_sessions.pending > 0 + ? `(在途 ${vm.daily_sessions.pending})` + : ''} +
+
+ {vm.daily_sessions.timezone} + {vm.daily_sessions.active || + vm.daily_sessions.blocked ? ( + <> + {' · '} + + {' 重置'} + + ) : !vm.daily_sessions.enabled ? ( + ' · 已关闭' + ) : null} +
+
+
+ ) : null} diff --git a/web/src/features/vm/proxy-timezone-copy.test.tsx b/web/src/features/vm/proxy-timezone-copy.test.tsx index 5fa5c8fec9..84c539b5c7 100644 --- a/web/src/features/vm/proxy-timezone-copy.test.tsx +++ b/web/src/features/vm/proxy-timezone-copy.test.tsx @@ -1,6 +1,115 @@ +import { type ReactNode } from 'react' import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + VM_TIMEZONE_CUSTOM, + resolveTimezonePickerState, +} from './create-options' import { VmEnvironmentCard } from './environment-card' +import { TimezonePicker } from './timezone-picker' + +type SelectCapture = { + value?: string + onValueChange?: (next: string) => void +} +type InputCapture = { + value?: string + onChange?: (event: { target: { value: string } }) => void +} + +const captured: { + select: SelectCapture | null + input: InputCapture | null +} = { select: null, input: null } + +const stateHarness: { + active: boolean + slots: unknown[] + cursor: number +} = { active: false, slots: [], cursor: 0 } + +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useState: (initial: T | (() => T)) => { + if (!stateHarness.active) return actual.useState(initial) + const idx = stateHarness.cursor++ + if (!(idx in stateHarness.slots)) { + stateHarness.slots[idx] = + typeof initial === 'function' ? (initial as () => T)() : initial + } + const setState = (next: T | ((prev: T) => T)) => { + stateHarness.slots[idx] = + typeof next === 'function' + ? (next as (prev: T) => T)(stateHarness.slots[idx] as T) + : next + } + return [stateHarness.slots[idx] as T, setState] as const + }, + } +}) + +vi.mock('@/components/ui/select', () => ({ + Select: ({ + value, + onValueChange, + children, + }: { + value?: string + onValueChange?: (next: string) => void + children?: ReactNode + }) => { + captured.select = { value, onValueChange } + return
{children}
+ }, + SelectTrigger: ({ children }: { children?: ReactNode }) => ( +
{children}
+ ), + SelectValue: ({ placeholder }: { placeholder?: string }) => ( + {placeholder} + ), + SelectContent: ({ children }: { children?: ReactNode }) => ( +
{children}
+ ), + SelectItem: ({ + value, + children, + }: { + value: string + children?: ReactNode + }) => , +})) + +vi.mock('@/components/ui/input', () => ({ + Input: (props: Record) => { + if (props['aria-label'] === '自定义时区') { + captured.input = { + value: typeof props.value === 'string' ? props.value : undefined, + onChange: props.onChange as InputCapture['onChange'], + } + } + return ( + + ) + }, +})) + +afterEach(() => { + stateHarness.active = false + stateHarness.slots = [] + stateHarness.cursor = 0 + captured.select = null + captured.input = null +}) function render(proxy: unknown) { return renderToStaticMarkup( @@ -14,6 +123,20 @@ function render(proxy: unknown) { ) } +function renderPicker(value: string, onChange: (next: string) => void) { + stateHarness.active = true + stateHarness.cursor = 0 + captured.select = null + captured.input = null + try { + return renderToStaticMarkup( + + ) + } finally { + stateHarness.active = false + } +} + describe('proxy timezone wording', () => { it('keeps missing proxy data distinct from geo data without a valid timezone', () => { expect(render(undefined)).toContain('暂无代理出口信息') @@ -25,3 +148,85 @@ describe('proxy timezone wording', () => { expect(invalid).toContain('title="代理出口时区不可用"') }) }) + +describe('TimezonePicker custom mode transitions', () => { + it('reveals custom input from preset UTC and hides it cleanly when switching back to a preset', () => { + expect(resolveTimezonePickerState('UTC', false)).toEqual({ + selectValue: 'UTC', + showCustom: false, + }) + expect(resolveTimezonePickerState('UTC', true)).toEqual({ + selectValue: VM_TIMEZONE_CUSTOM, + showCustom: true, + }) + expect(resolveTimezonePickerState('Pacific/Auckland', false)).toEqual({ + selectValue: VM_TIMEZONE_CUSTOM, + showCustom: true, + }) + + let value = 'UTC' + const onChange = vi.fn((next: string) => { + value = next + }) + + // 1. Preset UTC starts collapsed with select showing UTC + let html = renderPicker(value, onChange) + expect(captured.select?.value).toBe('UTC') + expect(captured.input).toBeNull() + expect(html).not.toContain('aria-label="自定义时区"') + + // 2. Selecting 自定义… from preset UTC reveals the custom input immediately + captured.select?.onValueChange?.(VM_TIMEZONE_CUSTOM) + expect(onChange).not.toHaveBeenCalled() + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe(VM_TIMEZONE_CUSTOM) + expect(captured.input?.value).toBe('UTC') + expect(html).toContain('aria-label="自定义时区"') + + // 3. Typing a custom IANA zone keeps custom mode open with valid live clock + captured.input?.onChange?.({ target: { value: 'Pacific/Auckland' } }) + expect(value).toBe('Pacific/Auckland') + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe(VM_TIMEZONE_CUSTOM) + expect(captured.input?.value).toBe('Pacific/Auckland') + expect(html).toContain('aria-label="自定义时区"') + expect(html).not.toContain('无效时区') + + // 4. Clearing the custom input stays in custom mode and surfaces 无效时区 + captured.input?.onChange?.({ target: { value: '' } }) + expect(value).toBe('') + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe(VM_TIMEZONE_CUSTOM) + expect(html).toContain('aria-label="自定义时区"') + expect(html).toContain('无效时区') + + // 5. Switching back to a preset clears custom mode and hides the input + captured.select?.onValueChange?.('Asia/Shanghai') + expect(value).toBe('Asia/Shanghai') + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe('Asia/Shanghai') + expect(captured.input).toBeNull() + expect(html).not.toContain('aria-label="自定义时区"') + + // 6. Entering custom mode from Asia/Shanghai and returning to the same preset hides it again + captured.select?.onValueChange?.(VM_TIMEZONE_CUSTOM) + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe(VM_TIMEZONE_CUSTOM) + expect(html).toContain('aria-label="自定义时区"') + captured.select?.onValueChange?.('Asia/Shanghai') + html = renderPicker(value, onChange) + expect(captured.select?.value).toBe('Asia/Shanghai') + expect(html).not.toContain('aria-label="自定义时区"') + }) + + it('auto-opens for initial non-preset values and collapses if parent externally resets to a preset', () => { + const onChange = vi.fn() + let html = renderPicker('Pacific/Auckland', onChange) + expect(captured.select?.value).toBe(VM_TIMEZONE_CUSTOM) + expect(html).toContain('aria-label="自定义时区"') + + html = renderPicker('UTC', onChange) + expect(captured.select?.value).toBe('UTC') + expect(html).not.toContain('aria-label="自定义时区"') + }) +}) diff --git a/web/src/features/vm/status-today.test.tsx b/web/src/features/vm/status-today.test.tsx index 5de2975bfd..6cc76a3791 100644 --- a/web/src/features/vm/status-today.test.tsx +++ b/web/src/features/vm/status-today.test.tsx @@ -45,4 +45,56 @@ describe('status board today cost wording', () => { expect(html).not.toContain('Go telemetry') expect(html).not.toContain('cc-node') }) + + it('renders daily new-session usage, timezone, and reset hint on Claude slots', () => { + const html = renderToStaticMarkup( + + + + ) + + expect(html).toContain('今日新会话') + expect(html).toContain('50 / 50') + expect(html).toContain('在途 1') + expect(html).toContain('Asia/Shanghai') + expect(html).toContain('重置') + }) }) diff --git a/web/src/features/vm/timezone-picker.tsx b/web/src/features/vm/timezone-picker.tsx index ffdacd6abf..b7bb9286cf 100644 --- a/web/src/features/vm/timezone-picker.tsx +++ b/web/src/features/vm/timezone-picker.tsx @@ -11,7 +11,7 @@ import { import { VM_TIMEZONE_CUSTOM, VM_TIMEZONES, - isPresetTimezone, + resolveTimezonePickerState, } from '@/features/vm/create-options' type TimezonePickerProps = { @@ -34,10 +34,8 @@ export function TimezonePicker({ disabled, className, }: TimezonePickerProps) { - const preset = isPresetTimezone(value) - const [custom, setCustom] = useState(!preset && !!value) - const selectValue = preset ? value : custom ? VM_TIMEZONE_CUSTOM : '' - const showCustom = custom && !preset + const [custom, setCustom] = useState(false) + const { selectValue, showCustom } = resolveTimezonePickerState(value, custom) const now = showCustom ? zoneNowLabel(value) : '' return ( @@ -75,7 +73,10 @@ export function TimezonePicker({ aria-label='自定义时区' disabled={disabled} value={value} - onChange={(e) => onChange(e.target.value)} + onChange={(e) => { + if (!custom) setCustom(true) + onChange(e.target.value) + }} /> {now || (validTimezone(value) ? '' : '无效时区')} diff --git a/web/src/features/vm/vm-list-table.test.tsx b/web/src/features/vm/vm-list-table.test.tsx index 5724298c7a..44620a7270 100644 --- a/web/src/features/vm/vm-list-table.test.tsx +++ b/web/src/features/vm/vm-list-table.test.tsx @@ -35,6 +35,7 @@ import { VmRack } from './vm-rack' import { bladeState, vmWindows, zoneCounts } from './vm-rack-model' import { VmRowDetail } from './vm-row-detail' import { VmSchedulingBlock, VmSchedulingEditor } from './vm-scheduling' +import { draftOf, fmtQuota, patchOf } from './vm-scheduling-model' import { filterVms, sortVms } from './vm-table' vi.mock('./vm-actions-context', () => ({ useVmActions: () => ({}) })) @@ -57,7 +58,7 @@ function render(over: Partial = {}) { describe('VM scheduling priority', () => { it('groups the three Claude seat PATCH fields under one VM type check', () => { const source = readFileSync( - new URL('./vm-scheduling.tsx', import.meta.url), + new URL('./vm-scheduling-model.ts', import.meta.url), 'utf8' ) const guards = [...source.matchAll(/if \(!isCodexVm\(vm\)\) \{([^}]+)\}/g)] @@ -1334,6 +1335,166 @@ describe('VM table first-column resize and Gemini presentation', () => { expect(legacyHtml).toContain('跟随全局') expect(legacyHtml).not.toContain('遥测关') }) + + it('handles 3-way daily_session_limit override (inherit null vs 0 unlimited vs positive cap)', () => { + expect(fmtQuota('daily_session_limit', 0)).toBe('不限') + expect(fmtQuota('daily_session_limit', undefined)).toBe('不限') + expect(fmtQuota('daily_session_limit', 50)).toBe('50 个/天') + + const baseVm: Vm = { + id: 'vm-01', + platform: 'anthropic', + quota_inherited: { + limit_5h: 0.85, + limit_7d: 0.8, + block_on_5h: true, + block_on_7d: true, + weekly_split: false, + daily_session_limit: 50, + }, + quota_policy: { + limit_5h: 0.85, + limit_7d: 0.8, + block_on_5h: true, + block_on_7d: true, + weekly_split: false, + daily_session_limit: 50, + }, + daily_sessions: { + enabled: true, + active: true, + used: 12, + pending: 0, + limit: 50, + remaining: 38, + blocked: false, + day_key: '2026-12-01', + timezone: 'Asia/Shanghai', + reset_at: '2026-12-01T16:00:00.000Z', + reset_at_ms: Date.parse('2026-12-01T16:00:00.000Z'), + tier_key: 'max_5x', + source: 'tier', + }, + } + + // Inherit (absent override) + const inheritedDraft = draftOf(baseVm) + expect(inheritedDraft.quota.daily_session_limit).toEqual({ + own: false, + value: 50, + }) + expect(patchOf(baseVm, inheritedDraft)).toEqual({}) + + // Set explicit 0 (unlimited override) + const zeroOverrideDraft = { + ...inheritedDraft, + quota: { + ...inheritedDraft.quota, + daily_session_limit: { own: true, value: 0 }, + }, + } + expect(patchOf(baseVm, zeroOverrideDraft)).toEqual({ + quota_override: { daily_session_limit: 0 }, + }) + + // Set explicit positive integer override + const positiveOverrideDraft = { + ...inheritedDraft, + quota: { + ...inheritedDraft.quota, + daily_session_limit: { own: true, value: 120 }, + }, + } + expect(patchOf(baseVm, positiveOverrideDraft)).toEqual({ + quota_override: { daily_session_limit: 120 }, + }) + + // VM already has explicit 0 override: unchanged -> no patch; clear -> quota_override: null + const zeroVm: Vm = { + ...baseVm, + quota_override: { daily_session_limit: 0 }, + quota_policy: { ...baseVm.quota_policy!, daily_session_limit: 0 }, + } + const zeroVmDraft = draftOf(zeroVm) + expect(zeroVmDraft.quota.daily_session_limit).toEqual({ + own: true, + value: 0, + }) + expect(patchOf(zeroVm, zeroVmDraft)).toEqual({}) + expect( + patchOf(zeroVm, { + ...zeroVmDraft, + quota: { + ...zeroVmDraft.quota, + daily_session_limit: { own: false, value: 0 }, + }, + }) + ).toEqual({ quota_override: null }) + + // Block & editor SSR rendering + const blockHtml = renderToStaticMarkup( + + + + ) + expect(blockHtml).toContain('每日新会话上限') + expect(blockHtml).toContain('>12/50') + + // Per-VM override stays active even when global daily_session_gate.enabled is false + const perVmActiveWhileGlobalOff: Vm = { + ...baseVm, + quota_override: { daily_session_limit: 20 }, + quota_inherited: { ...baseVm.quota_inherited!, daily_session_limit: 0 }, + quota_policy: { ...baseVm.quota_policy!, daily_session_limit: 20 }, + daily_sessions: { + ...baseVm.daily_sessions!, + enabled: false, + active: true, + used: 5, + limit: 20, + remaining: 15, + source: 'override', + }, + } + const perVmActiveHtml = renderToStaticMarkup( + + + + ) + expect(perVmActiveHtml).toContain('>5/20') + expect(perVmActiveHtml).toContain('Asia/Shanghai') + expect(perVmActiveHtml).not.toContain('全局闸门未启用') + + // Fully disabled (enabled: false, active: false) shows static policy + 全局闸门未启用 tooltip + const disabledGateVm: Vm = { + ...baseVm, + quota_inherited: { ...baseVm.quota_inherited!, daily_session_limit: 0 }, + quota_policy: { ...baseVm.quota_policy!, daily_session_limit: 0 }, + daily_sessions: { + ...baseVm.daily_sessions!, + enabled: false, + active: false, + used: 0, + limit: 0, + remaining: null, + source: 'disabled', + }, + } + const disabledGateHtml = renderToStaticMarkup( + + + + ) + expect(disabledGateHtml).toContain('全局闸门未启用') + + const editorHtml = renderToStaticMarkup( + + + + ) + expect(editorHtml).toContain('每日新会话上限') + expect(editorHtml).toContain('跟随 · 50 个/天') + }) }) describe('VM table tail data-column resize', () => { @@ -1395,9 +1556,7 @@ describe('VM table tail data-column resize', () => { `34px minmax(240px,max-content) minmax(250px,1.3fr) minmax(190px,0.95fr) repeat(3,minmax(104px,0.55fr)) 96px 120px 40px 40px 80px 60px 62px 64px 56px` ) // 勾选形态头部多一根 34px,数据列键位不受影响(对齐契约)。 - expect( - buildVmTableGridTemplate(true, 360, { today: 96 }) - ).toBe( + expect(buildVmTableGridTemplate(true, 360, { today: 96 })).toBe( `34px 34px 360px minmax(250px,1.3fr) minmax(190px,0.95fr) repeat(3,minmax(104px,0.55fr)) 96px 80px 40px 40px 80px 60px 62px 64px 56px` ) // 最小宽度随覆盖同步增长。 @@ -1426,13 +1585,16 @@ describe('VM table tail data-column resize', () => { ) // 八个数据列各有一个把手(不含操作列与首列的 first 把手)。 - const grips = - html.match(/data-col-resizer="(?!first")[^"]+"/g) ?? [] + const grips = html.match(/data-col-resizer="(?!first")[^"]+"/g) ?? [] expect(grips).toHaveLength(8) expect(html).toContain('data-col-resizer="today"') - expect(html).toContain('aria-label="拖拽调整该列宽度,双击或按 Home 键恢复默认"') + expect(html).toContain( + 'aria-label="拖拽调整该列宽度,双击或按 Home 键恢复默认"' + ) // 持久化宽度渲染为固定轨道。 - expect(html).toContain('grid-template-columns:34px minmax(240px,max-content)') + expect(html).toContain( + 'grid-template-columns:34px minmax(240px,max-content)' + ) expect(html).toMatch(/96px 80px 40px/) // 键盘步进与 Home 重置。 expect(nextDataColWidthForKey('ArrowRight', 96, 76)).toEqual({ diff --git a/web/src/features/vm/vm-scheduling-model.ts b/web/src/features/vm/vm-scheduling-model.ts new file mode 100644 index 0000000000..c7607d3709 --- /dev/null +++ b/web/src/features/vm/vm-scheduling-model.ts @@ -0,0 +1,280 @@ +import type { Vm, VmQuotaOverride, VmQuotaView } from '@/types/panel-vm' +import type { VmPatch } from '@/lib/api' +import { isCodexVm } from '@/lib/vm-kind' +import { SEAT_CAP_MAX } from '@/components/scheduler-viz' +import { DAILY_SESSION_LIMIT_MAX } from '@/features/settings/quota-values' + +export type Knob = { own: boolean; value: T } +export type QuotaKey = keyof VmQuotaView +export type QuotaFieldKind = 'ratio' | 'bool' | 'int' +export type DayPreset = 'all' | 'weekday' | 'weekend' | 'custom' + +export type Draft = { + seats: Knob + primary: Knob + subagents: Knob + conc: Knob + rpm: Knob + sessions: Knob + /** 'auto' = 按 7D 重置倒计时自动算;数字 = 手动 1–10。 */ + level: 'auto' | number + quota: Record> + /** 工作时段;own=false = 跟随全局(24h 接单)。timezone 是已钉住的值,面板不改但要原样带回。 */ + hours: { + own: boolean + start: string + end: string + days: number[] + timezone?: string + } +} + +export const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6] +export const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/ +export const DAY_LABELS = ['日', '一', '二', '三', '四', '五', '六'] + +export const QUOTA_FIELDS: { + key: QuotaKey + kind: QuotaFieldKind + label: string + desc: string +}[] = [ + { + key: 'limit_5h', + kind: 'ratio', + label: '5h 闸线', + desc: '5h 用量到这里写成受限并切号', + }, + { + key: 'limit_7d', + kind: 'ratio', + label: '7d 闸线', + desc: '7d 用量到这里写成受限并切号', + }, + { + key: 'block_on_5h', + kind: 'bool', + label: '5h 闸生效', + desc: '关掉后不按 5h 拦截', + }, + { + key: 'block_on_7d', + kind: 'bool', + label: '7d 闸生效', + desc: '关掉后不按 7d 拦截', + }, + { + key: 'weekly_split', + kind: 'bool', + label: '周仓拆分', + desc: '7d 一半留给 Fable(实验)', + }, + { + key: 'daily_session_limit', + kind: 'int', + label: '每日新会话上限', + desc: '单槽每日允许新建的主会话数;0 = 本槽不限(覆盖全局分档)。', + }, +] + +const QUOTA_FIELD_KIND: Record = Object.fromEntries( + QUOTA_FIELDS.map(({ key, kind }) => [key, kind]) +) as Record + +export const LEVELS = Array.from({ length: 10 }, (_, i) => i + 1) + +export const DAY_PRESET_DAYS: Record, number[]> = { + all: ALL_DAYS, + weekday: [1, 2, 3, 4, 5], + weekend: [0, 6], +} + +export function fmtQuota(key: QuotaKey, value: unknown): string { + const kind = QUOTA_FIELD_KIND[key] + if (kind === 'ratio') return `${Math.round(Number(value) * 100)}%` + if (kind === 'int') { + const n = Math.max(0, Math.round(Number(value) || 0)) + return n > 0 ? `${n} 个/天` : '不限' + } + return value ? '开' : '关' +} + +export function draftOf(vm: Vm): Draft { + const inherited = vm.scheduling_inherited + const override = vm.quota_override || {} + const quotaBase = vm.quota_inherited + const quota = Object.fromEntries( + QUOTA_FIELDS.map(({ key, kind }) => { + const own = override[key] != null + const raw = own ? override[key] : quotaBase?.[key] + const value = + kind === 'ratio' + ? Math.round(Number(raw ?? 0.85) * 100) + : kind === 'int' + ? Math.min( + DAILY_SESSION_LIMIT_MAX, + Math.max(0, Math.round(Number(raw ?? 0) || 0)) + ) + : Boolean(raw) + return [key, { own, value }] + }) + ) as Draft['quota'] + return { + seats: { + own: vm.session_slots_override === true, + value: Number( + vm.session_slots ?? inherited?.session_slots ?? SEAT_CAP_MAX + ), + }, + primary: { + own: vm.max_primary_sessions_override === true, + value: Number( + vm.max_primary_sessions ?? + inherited?.max_primary_sessions ?? + vm.session_slots ?? + SEAT_CAP_MAX + ), + }, + subagents: { + own: vm.max_subagents_per_session_override === true, + value: Number( + vm.max_subagents_per_session ?? + inherited?.max_subagents_per_session ?? + 0 + ), + }, + conc: { + own: vm.concurrency_override === true, + value: Number(vm.max_concurrency ?? inherited?.max_concurrency ?? 2), + }, + rpm: { + own: vm.rpm_override === true, + value: Number(vm.max_rpm ?? inherited?.max_rpm ?? 0), + }, + sessions: { + own: vm.max_sessions_override === true, + value: Number(vm.max_sessions ?? inherited?.max_sessions ?? 0), + }, + level: + vm.schedule_level_mode === 'manual' && Number(vm.schedule_level) >= 1 + ? Number(vm.schedule_level) + : 'auto', + quota, + hours: { + own: !!vm.active_hours, + start: vm.active_hours?.start || '08:00', + end: vm.active_hours?.end || '22:00', + days: vm.active_hours?.days?.length + ? [...vm.active_hours.days] + : ALL_DAYS, + timezone: vm.active_hours?.timezone, + }, + } +} + +export function sortedDays(days: number[]): number[] { + return [...days].sort((a, b) => a - b) +} + +function sameDays(a: number[], b: number[]): boolean { + const x = sortedDays(a) + const y = sortedDays(b) + return x.length === y.length && x.every((v, i) => v === y[i]) +} + +function sameHours(a: Draft['hours'], b: Draft['hours']): boolean { + if (a.own !== b.own) return false + if (!a.own) return true + return a.start === b.start && a.end === b.end && sameDays(a.days, b.days) +} + +export function dayPreset(days: number[]): DayPreset { + if (sameDays(days, ALL_DAYS)) return 'all' + if (sameDays(days, [1, 2, 3, 4, 5])) return 'weekday' + if (sameDays(days, [0, 6])) return 'weekend' + return 'custom' +} + +/** 只发生变化的字段;null = 去掉本槽覆盖。 */ +export function patchOf(vm: Vm, draft: Draft): VmPatch { + const body: VmPatch = {} + const before = draftOf(vm) + const knob = ( + key: + | 'session_slots' + | 'max_primary_sessions' + | 'max_subagents_per_session' + | 'max_concurrency' + | 'max_rpm' + | 'max_sessions', + next: Knob, + prev: Knob + ) => { + if (next.own && (!prev.own || next.value !== prev.value)) { + body[key] = next.value + } else if (!next.own && prev.own) { + body[key] = null + } + } + if (!isCodexVm(vm)) { + knob('session_slots', draft.seats, before.seats) + knob('max_primary_sessions', draft.primary, before.primary) + knob('max_subagents_per_session', draft.subagents, before.subagents) + } + knob('max_concurrency', draft.conc, before.conc) + knob('max_rpm', draft.rpm, before.rpm) + if (isCodexVm(vm)) knob('max_sessions', draft.sessions, before.sessions) + if (draft.level !== before.level) { + body.schedule_level = draft.level === 'auto' ? null : draft.level + } + if (!sameHours(draft.hours, before.hours)) { + body.active_hours = draft.hours.own + ? { + start: draft.hours.start, + end: draft.hours.end, + ...(draft.hours.timezone ? { timezone: draft.hours.timezone } : {}), + ...(sameDays(draft.hours.days, ALL_DAYS) + ? {} + : { days: sortedDays(draft.hours.days) }), + } + : null + } + if (!isCodexVm(vm)) { + const next: VmQuotaOverride = {} + for (const { key, kind } of QUOTA_FIELDS) { + const k = draft.quota[key] + if (!k.own) continue + ;(next as Record)[key] = + kind === 'ratio' + ? Number(k.value) / 100 + : kind === 'int' + ? Math.min( + DAILY_SESSION_LIMIT_MAX, + Math.max(0, Math.round(Number(k.value) || 0)) + ) + : Boolean(k.value) + } + const prev = vm.quota_override || {} + const same = QUOTA_FIELDS.every( + ({ key }) => (prev[key] ?? null) === (next[key] ?? null) + ) + if (!same) body.quota_override = Object.keys(next).length ? next : null + } + return body +} + +export function overrideCount(vm: Vm): number { + const quota = Object.values(vm.quota_override || {}).filter( + (v) => v != null + ).length + return ( + quota + + Number(vm.session_slots_override === true) + + Number(vm.max_primary_sessions_override === true) + + Number(vm.max_subagents_per_session_override === true) + + Number(vm.concurrency_override === true) + + Number(vm.rpm_override === true) + + Number(vm.max_sessions_override === true) + + Number(!!vm.active_hours) + ) +} diff --git a/web/src/features/vm/vm-scheduling.tsx b/web/src/features/vm/vm-scheduling.tsx index 0d5ad2efe8..13dcf72d15 100644 --- a/web/src/features/vm/vm-scheduling.tsx +++ b/web/src/features/vm/vm-scheduling.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import { useMutation, useQueryClient } from '@tanstack/react-query' -import type { Vm, VmQuotaOverride, VmQuotaView } from '@/types/panel-vm' +import type { Vm } from '@/types/panel-vm' import { SlidersHorizontal } from 'lucide-react' import { toast } from 'sonner' import { @@ -23,13 +23,18 @@ import { } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' -import { SEAT_CAP_MAX, SeatCells } from '@/components/scheduler-viz' +import { SeatCells } from '@/components/scheduler-viz' import { dashboardQueryOptions } from '@/features/overview/queries' import { NodePoolBadges } from '@/features/pools/node-pool-badges' import { WeightTierBadge } from '@/features/pools/pool-badges' +import { + DAILY_SESSION_LIMIT_MAX, + DAILY_SESSION_STEPS, +} from '@/features/settings/quota-values' import { ChipGroup, FamilyLimitSelect, + StepperSetting, } from '@/features/settings/scheduler-controls' import { vmQueryOptions, vmsListQueryOptions } from '@/features/vm/queries' import { @@ -40,6 +45,22 @@ import { withCurrent, } from '@/features/vm/scheduling-steps' import { useVmPerms } from '@/features/vm/vm-perms' +import { + DAY_LABELS, + DAY_PRESET_DAYS, + HHMM, + LEVELS, + QUOTA_FIELDS, + dayPreset, + draftOf, + fmtQuota, + overrideCount, + patchOf, + sortedDays, + type Draft, + type Knob, + type QuotaKey, +} from './vm-scheduling-model' function shortSession(id: string) { if (id.length <= 18) return id @@ -78,231 +99,6 @@ function SeatSessionList({ sessions }: { sessions: Vm['seat_sessions'] }) { ) } -type Knob = { own: boolean; value: T } -type QuotaKey = keyof VmQuotaView -type Draft = { - seats: Knob - primary: Knob - subagents: Knob - conc: Knob - rpm: Knob - sessions: Knob - /** 'auto' = 按 7D 重置倒计时自动算;数字 = 手动 1–10。 */ - level: 'auto' | number - quota: Record> - /** 工作时段;own=false = 跟随全局(24h 接单)。timezone 是已钉住的值,面板不改但要原样带回。 */ - hours: { - own: boolean - start: string - end: string - days: number[] - timezone?: string - } -} - -const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6] -const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/ -const DAY_LABELS = ['日', '一', '二', '三', '四', '五', '六'] - -const QUOTA_FIELDS: { key: QuotaKey; label: string; desc: string }[] = [ - { key: 'limit_5h', label: '5h 闸线', desc: '5h 用量到这里写成受限并切号' }, - { key: 'limit_7d', label: '7d 闸线', desc: '7d 用量到这里写成受限并切号' }, - { key: 'block_on_5h', label: '5h 闸生效', desc: '关掉后不按 5h 拦截' }, - { key: 'block_on_7d', label: '7d 闸生效', desc: '关掉后不按 7d 拦截' }, - { - key: 'weekly_split', - label: '周仓拆分', - desc: '7d 一半留给 Fable(实验)', - }, -] - -const LEVELS = Array.from({ length: 10 }, (_, i) => i + 1) - -function isRatio(key: QuotaKey) { - return key === 'limit_5h' || key === 'limit_7d' -} - -function fmtQuota(key: QuotaKey, value: unknown): string { - if (isRatio(key)) return `${Math.round(Number(value) * 100)}%` - return value ? '开' : '关' -} - -function draftOf(vm: Vm): Draft { - const inherited = vm.scheduling_inherited - const override = vm.quota_override || {} - const quotaBase = vm.quota_inherited - const quota = Object.fromEntries( - QUOTA_FIELDS.map(({ key }) => { - const own = override[key] != null - const raw = own ? override[key] : quotaBase?.[key] - const value = isRatio(key) - ? Math.round(Number(raw ?? 0.85) * 100) - : Boolean(raw) - return [key, { own, value }] - }) - ) as Draft['quota'] - return { - seats: { - own: vm.session_slots_override === true, - value: Number( - vm.session_slots ?? inherited?.session_slots ?? SEAT_CAP_MAX - ), - }, - primary: { - own: vm.max_primary_sessions_override === true, - value: Number( - vm.max_primary_sessions ?? - inherited?.max_primary_sessions ?? - vm.session_slots ?? - SEAT_CAP_MAX - ), - }, - subagents: { - own: vm.max_subagents_per_session_override === true, - value: Number( - vm.max_subagents_per_session ?? - inherited?.max_subagents_per_session ?? - 0 - ), - }, - conc: { - own: vm.concurrency_override === true, - value: Number(vm.max_concurrency ?? inherited?.max_concurrency ?? 2), - }, - rpm: { - own: vm.rpm_override === true, - value: Number(vm.max_rpm ?? inherited?.max_rpm ?? 0), - }, - sessions: { - own: vm.max_sessions_override === true, - value: Number(vm.max_sessions ?? inherited?.max_sessions ?? 0), - }, - level: - vm.schedule_level_mode === 'manual' && Number(vm.schedule_level) >= 1 - ? Number(vm.schedule_level) - : 'auto', - quota, - hours: { - own: !!vm.active_hours, - start: vm.active_hours?.start || '08:00', - end: vm.active_hours?.end || '22:00', - days: vm.active_hours?.days?.length - ? [...vm.active_hours.days] - : ALL_DAYS, - timezone: vm.active_hours?.timezone, - }, - } -} - -function sortedDays(days: number[]): number[] { - return [...days].sort((a, b) => a - b) -} - -function sameDays(a: number[], b: number[]): boolean { - const x = sortedDays(a) - const y = sortedDays(b) - return x.length === y.length && x.every((v, i) => v === y[i]) -} - -function sameHours(a: Draft['hours'], b: Draft['hours']): boolean { - if (a.own !== b.own) return false - if (!a.own) return true - return a.start === b.start && a.end === b.end && sameDays(a.days, b.days) -} - -type DayPreset = 'all' | 'weekday' | 'weekend' | 'custom' - -function dayPreset(days: number[]): DayPreset { - if (sameDays(days, ALL_DAYS)) return 'all' - if (sameDays(days, [1, 2, 3, 4, 5])) return 'weekday' - if (sameDays(days, [0, 6])) return 'weekend' - return 'custom' -} - -const DAY_PRESET_DAYS: Record, number[]> = { - all: ALL_DAYS, - weekday: [1, 2, 3, 4, 5], - weekend: [0, 6], -} - -/** 只发生变化的字段;null = 去掉本槽覆盖。 */ -function patchOf(vm: Vm, draft: Draft): VmPatch { - const body: VmPatch = {} - const before = draftOf(vm) - const knob = ( - key: - | 'session_slots' - | 'max_primary_sessions' - | 'max_subagents_per_session' - | 'max_concurrency' - | 'max_rpm' - | 'max_sessions', - next: Knob, - prev: Knob - ) => { - if (next.own && (!prev.own || next.value !== prev.value)) { - body[key] = next.value - } else if (!next.own && prev.own) { - body[key] = null - } - } - if (!isCodexVm(vm)) { - knob('session_slots', draft.seats, before.seats) - knob('max_primary_sessions', draft.primary, before.primary) - knob('max_subagents_per_session', draft.subagents, before.subagents) - } - knob('max_concurrency', draft.conc, before.conc) - knob('max_rpm', draft.rpm, before.rpm) - if (isCodexVm(vm)) knob('max_sessions', draft.sessions, before.sessions) - if (draft.level !== before.level) { - body.schedule_level = draft.level === 'auto' ? null : draft.level - } - if (!sameHours(draft.hours, before.hours)) { - body.active_hours = draft.hours.own - ? { - start: draft.hours.start, - end: draft.hours.end, - ...(draft.hours.timezone ? { timezone: draft.hours.timezone } : {}), - ...(sameDays(draft.hours.days, ALL_DAYS) - ? {} - : { days: sortedDays(draft.hours.days) }), - } - : null - } - if (!isCodexVm(vm)) { - const next: VmQuotaOverride = {} - for (const { key } of QUOTA_FIELDS) { - const k = draft.quota[key] - if (!k.own) continue - ;(next as Record)[key] = isRatio(key) - ? Number(k.value) / 100 - : k.value - } - const prev = vm.quota_override || {} - const same = QUOTA_FIELDS.every( - ({ key }) => (prev[key] ?? null) === (next[key] ?? null) - ) - if (!same) body.quota_override = Object.keys(next).length ? next : null - } - return body -} - -function overrideCount(vm: Vm): number { - const quota = Object.values(vm.quota_override || {}).filter( - (v) => v != null - ).length - return ( - quota + - Number(vm.session_slots_override === true) + - Number(vm.max_primary_sessions_override === true) + - Number(vm.max_subagents_per_session_override === true) + - Number(vm.concurrency_override === true) + - Number(vm.rpm_override === true) + - Number(vm.max_sessions_override === true) + - Number(!!vm.active_hours) - ) -} - function Tile({ label, value, @@ -572,19 +368,39 @@ export function VmSchedulingBlock({ /> {codex || !policy ? null - : QUOTA_FIELDS.map(({ key, label }) => ( - - ))} + : QUOTA_FIELDS.map(({ key, label }) => { + const dailyInfo = + key === 'daily_session_limit' && + vm.daily_sessions && + vm.daily_sessions.source !== 'unsupported' + ? vm.daily_sessions + : null + const daily = + dailyInfo && (dailyInfo.enabled || dailyInfo.active) + ? dailyInfo + : null + const tileValue = daily + ? `${daily.used}/${daily.limit > 0 ? daily.limit : '不限'}` + : fmtQuota(key, policy[key]) + const tzHint = daily + ? ` · ${daily.timezone}` + : dailyInfo + ? ' · 全局闸门未启用' + : '' + return ( + + ) + })}
{Number.isInteger(level) && level >= 1 && level <= 10 ? (
@@ -1070,9 +886,9 @@ export function VmSchedulingEditor({ vm }: { vm: Vm }) { 配额闸
- {QUOTA_FIELDS.map(({ key, label, desc }) => { + {QUOTA_FIELDS.map(({ key, kind, label, desc }) => { const k = draft.quota[key] - return ( + const row = ( setQuota(key, { own })} disabled={pending} > - {isRatio(key) ? ( + {kind === 'ratio' ? ( setQuota(key, { value })} disabled={pending} /> + ) : kind === 'int' ? ( +
+ setQuota(key, { value })} + /> + setQuota(key, { value })} + disabled={pending} + /> +
) : ( ) + return kind === 'int' ? ( +
+ {row} +
+ ) : ( + row + ) })}
diff --git a/web/src/lib/vm-status.test.ts b/web/src/lib/vm-status.test.ts index fa61e8c5af..53cc4650c2 100644 --- a/web/src/lib/vm-status.test.ts +++ b/web/src/lib/vm-status.test.ts @@ -957,6 +957,42 @@ describe('custom quota window restriction labels (#1744)', () => { } as Vm expect(restrictionCopy(slot)).toContain('24h 限制') }) + + it('maps daily_session_limit new_session restriction to caution daily_session tone', () => { + const resetAt = Date.parse('2026-12-02T00:00:00.000Z') + const capped = liveVm({ + schedule_state: 'restricted', + restriction_scope: 'new_session', + restriction_reason: 'daily_session_limit', + restriction_text: '今日新会话上限', + restriction_until: resetAt, + }) + expect(poolStatus(capped)).toMatchObject({ + key: 'daily_session', + text: '今日新会话上限', + cls: 'caution', + }) + expect(accountStatus(capped)).toMatchObject({ + key: 'daily_session', + text: '今日新会话上限', + cls: 'caution', + }) + expect(restrictionCopy(capped)).toBe('今日新会话上限') + expect(scheduleStateLabel(capped)).toBe('受限') + expect(fleetGroup(capped)).toBe('restricted') + + const fallbackText = liveVm({ + schedule_state: 'restricted', + restriction_scope: 'new_session', + restriction_reason: 'daily_session_limit', + availability: undefined, + }) + expect(poolStatus(fallbackText)).toMatchObject({ + key: 'daily_session', + text: '今日新会话上限', + cls: 'caution', + }) + }) }) describe('vmRunning', () => { diff --git a/web/src/lib/vm-status.ts b/web/src/lib/vm-status.ts index 65ed181f92..1cc1e5445e 100644 --- a/web/src/lib/vm-status.ts +++ b/web/src/lib/vm-status.ts @@ -551,8 +551,15 @@ function restrictionTone(vm: Vm | undefined): StatusTone | null { const reason = String( vm.restriction_reason || vm.availability?.reason || '' ) - // 只拦新会话(席位满 / 对话窗口满 / 临近闸线):已入座会话照常在跑。 + // 只拦新会话(每日新会话上限 / 席位满 / 对话窗口满 / 临近闸线):已入座会话照常在跑。 if (vm.restriction_scope === 'new_session') { + if (/daily_session/.test(reason)) { + return { + key: 'daily_session', + text: restrictionLabel(vm, '今日新会话上限'), + cls: 'caution', + } + } return { key: /draining/.test(reason) ? 'drain' : 'seats', text: restrictionLabel(vm, '席位满'), diff --git a/web/src/types/panel-vm.ts b/web/src/types/panel-vm.ts index 4eee7f2b05..1510ff404e 100644 --- a/web/src/types/panel-vm.ts +++ b/web/src/types/panel-vm.ts @@ -536,6 +536,8 @@ export type Vm = { quota_policy?: VmQuotaView | null /** 不含覆盖、按全局分档算出的配额,供「跟随全局」展示。 */ quota_inherited?: VmQuotaView | null + /** 单账号每日新建主会话闸门实时状态(仅 Claude 槽;Codex 为 null)。 */ + daily_sessions?: VmDailySessionsView | null /** OpenAI 的生效额度与限制原因;不包含 Claude 分档/weekly split。 */ openai_quota_policy?: | (OpenAIQuotaPolicy & { @@ -906,15 +908,48 @@ export type OfficialCcStatus = { [key: string]: unknown } +export type DailySessionTierKey = + 'default' | 'pro' | 'max_5x' | 'max_20x' | 'team' | 'enterprise' + +export type DailySessionGateConfig = { + enabled: boolean + reset_timezone: string + tier_limits: Record +} + +export type VmDailySessionsView = { + enabled: boolean + active: boolean + used: number + pending: number + limit: number + remaining: number | null + blocked: boolean + day_key: string + timezone: string + reset_at: string + reset_at_ms: number + tier_key: DailySessionTierKey + source: 'override' | 'tier' | 'disabled' | 'unsupported' +} + export type VmQuotaView = { limit_5h: number limit_7d: number block_on_5h: boolean block_on_7d: boolean weekly_split: boolean + /** 每日新建主会话上限;0 = 不限。 */ + daily_session_limit?: number } -export type VmQuotaOverride = Partial +export type VmQuotaOverride = Omit< + Partial, + 'daily_session_limit' +> & { + /** null / 缺省 = 跟随全局分档;0 = 本槽覆盖不限;正整数 = 本槽每日上限。 */ + daily_session_limit?: number | null +} /** 单槽工作时段(`vm.policy.active_hours`)。start 晚于 end = 跨夜班次。 */ export type VmActiveHours = { From 571fb9c02d28ec2f87483af89523f85cbd574e5f Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 03:45:07 +0800 Subject: [PATCH 2/3] fix(quota): close parent-session and short-probe daily gate bypasses and add 503 hydration recovery --- .../crates/scheduler-core/src/admission.rs | 2 +- .../tests/admission_affinity_tests.rs | 66 ++++++ src/lib/pool/daily-session-gate.mjs | 171 +++++++++++++-- src/lib/pool/failover-runner.mjs | 2 + src/lib/protocol/handle-protocol.mjs | 20 ++ src/lib/scheduler/scheduler-runtime.mjs | 59 ++++- test/unit/pool-scheduler.test.mjs | 28 ++- test/unit/scheduler-m3-runtime.test.mjs | 206 ++++++++++++++++-- test/unit/vm-quota-override.test.mjs | 86 +++++++- 9 files changed, 574 insertions(+), 66 deletions(-) diff --git a/scheduler/crates/scheduler-core/src/admission.rs b/scheduler/crates/scheduler-core/src/admission.rs index cfa7aa7f4d..085357fa77 100644 --- a/scheduler/crates/scheduler-core/src/admission.rs +++ b/scheduler/crates/scheduler-core/src/admission.rs @@ -264,7 +264,7 @@ pub fn filter_members_for<'a>( }); continue; } - if st.new_sessions_blocked && !continuing_known_session && !req.is_ephemeral_probe { + if st.new_sessions_blocked && !continuing_known_session { excluded.push(ExcludedEntry { pool_id: pool.id.clone(), node: node.node_key.clone(), diff --git a/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs b/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs index 6afe248961..724ff7bdc3 100644 --- a/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs +++ b/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs @@ -2971,6 +2971,72 @@ async fn quota_guard_band_keeps_pinned_conversations_and_refuses_new_ones() { .await; } +#[tokio::test] +async fn new_sessions_blocked_excludes_ephemeral_probe_and_honors_continuing_node_keys() { + let eng = two_node_engine(); + eng.update_telemetry(TelemetryBatchRequest { + nodes: vec![ + NodeTelemetryUpdate { + node_key: CompactString::const_new("claude_vm:vm1"), + new_sessions_blocked: Some(true), + ..Default::default() + }, + NodeTelemetryUpdate { + node_key: CompactString::const_new("claude_vm:vm2"), + new_sessions_blocked: Some(true), + ..Default::default() + }, + ], + }); + + // Ephemeral probes without a pinned or continuing session MUST still be excluded + // by `new_sessions_blocked` (zero behavior change when daily_session_gate is off). + let mut probe = base_req( + "r_probe_blocked", + "pool_1", + "claude-opus-4-6", + ModelFamily::Claude, + "s_probe_new", + None, + ); + probe.is_ephemeral_probe = true; + let err = eng.acquire(probe).await.unwrap_err(); + assert_eq!(err.code(), ErrorCode::PoolExhausted); + match err { + ScheduleError::PoolExhausted { explain } => { + assert!( + explain + .excluded + .iter() + .any(|e| e.node == "claude_vm:vm1" + && e.reason == ExcludeReason::NewSessionBlocked) + ); + assert!( + explain + .excluded + .iter() + .any(|e| e.node == "claude_vm:vm2" + && e.reason == ExcludeReason::NewSessionBlocked) + ); + } + other => panic!("unexpected error: {other:?}"), + } + + // Verified cross-day committed session passed via `continuing_node_keys` is admitted. + let mut resume = base_req( + "r_resume_xday", + "pool_1", + "claude-opus-4-6", + ModelFamily::Claude, + "s_old_committed", + None, + ); + resume.continuing_node_keys = vec![CompactString::const_new("claude_vm:vm2")]; + let ok = eng.acquire(resume).await.unwrap(); + assert_eq!(ok.selected_node.node_key, "claude_vm:vm2"); + release_ok(&eng, &ok.lease_id); +} + #[tokio::test] async fn host_memory_pressure_keeps_pinned_conversations_and_refuses_new_ones() { continuing_only_case( diff --git a/src/lib/pool/daily-session-gate.mjs b/src/lib/pool/daily-session-gate.mjs index 9d138b3a24..7955d57f84 100644 --- a/src/lib/pool/daily-session-gate.mjs +++ b/src/lib/pool/daily-session-gate.mjs @@ -46,6 +46,7 @@ const DEFAULT_RETENTION_DAYS = 7 // Cross-process DB lease TTL for crash-orphan recovery; live local handles renew this automatically. const DEFAULT_DB_RESERVATION_TTL_MS = 900_000 const PRUNE_MIN_INTERVAL_MS = 3_600_000 +const DEFAULT_HYDRATE_RETRY_BACKOFF_MS = Object.freeze([5_000, 15_000, 30_000, 60_000]) function quotaValidationError(message) { const error = new TypeError(message) @@ -288,19 +289,24 @@ export function resolveDayWindow(now = Date.now(), resetTimezone = 'UTC') { * Determine whether a scheduler lease represents a new primary Anthropic session * that should be governed by the daily session creation gate. * - * Security: do NOT exempt merely because caller supplied `parent_session_id`. - * Only exempt verified subagent placements (`affinity.why === 'subagent_follow_parent'`) - * or verified continuing/ephemeral/admin-diagnostic leases. + * Security: + * - Do NOT exempt `subagent_follow_parent`: caller-supplied `x-kin-parent-session` + * with a brand-new `session_id` must still be governed by the daily session gate. + * - Do NOT exempt arbitrary `is_ephemeral_probe` requests (short prompts like + * "Explain TCP" must not bypass daily limits). Only genuine `is_admin_diagnostic` + * probes or verified same-session continuations (`session_hit`, `session_hit_after_wait`, + * or `ephemeral_follow_session` without a caller-supplied `parent_session_id`) + * are exempted. */ export function shouldGateSchedulerLease(req, res) { if (res?.selected_node?.node_type !== 'claude_vm') return false - if (req?.is_ephemeral_probe) return false + if (req?.is_admin_diagnostic) return false const why = res?.explain?.affinity?.why - if (why === 'subagent_follow_parent') return false if (why === 'session_hit') return false if (why === 'session_hit_after_wait') return false - if (why === 'ephemeral_follow_session') return false - if (req?.is_admin_diagnostic && req?.pin_node_key) return false + const parentSessionId = + typeof req?.parent_session_id === 'string' ? req.parent_session_id.trim() : req?.parent_session_id + if (why === 'ephemeral_follow_session' && !parentSessionId) return false const sessionId = typeof req?.session_id === 'string' ? req.session_id.trim() : req?.session_id return Boolean(sessionId) } @@ -347,6 +353,82 @@ export class DailySessionGate { this._hydrationError = null this._lastWriteError = null this._pendingWrites = new Set() + const rawBackoff = Array.isArray(options.hydrateRetryBackoffMs) + ? options.hydrateRetryBackoffMs.map((n) => Math.max(10, Math.floor(Number(n)))).filter(Number.isFinite) + : [] + this._hydrateRetryBackoffMs = rawBackoff.length ? rawBackoff : DEFAULT_HYDRATE_RETRY_BACKOFF_MS + this._hydrateRetryTimer = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._closed = false + } + + close() { + this._closed = true + this._clearHydrateRetryTimer() + } + + stop() { + this.close() + } + + _clearHydrateRetryTimer() { + if (this._hydrateRetryTimer) { + clearTimeout(this._hydrateRetryTimer) + this._hydrateRetryTimer = null + } + } + + _notifyHydrated(res) { + try { + this._onHydrated?.(res) + } catch {} + } + + _scheduleHydrateRecovery(now = Date.now()) { + if (this._closed || !this._config.enabled || !this._hydrationError) return + if (this._hydrateRetryTimer || this._hydrating) return + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + this._lastHydrateRetryAt = ts + const idx = Math.min(this._hydrateRetryAttempt, this._hydrateRetryBackoffMs.length - 1) + const delayMs = this._hydrateRetryBackoffMs[idx] + this._hydrateRetryAttempt += 1 + this._hydrateRetryTimer = setTimeout(() => { + this._hydrateRetryTimer = null + if (this._closed || !this._config.enabled || !this._hydrationError) return + this._attemptHydrateRecovery(Date.now()) + }, delayMs) + this._hydrateRetryTimer.unref?.() + } + + _attemptHydrateRecovery(now = Date.now()) { + if (this._closed || !this._config.enabled || !this._hydrationError || this._hydrating) return false + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + this._lastHydrateRetryAt = ts + if (this._repo?.isPgAsyncMode) { + this._startAsyncHydration(ts) + return true + } + try { + this.hydrate(ts) + } catch { + // hydrate() already recorded _hydrationError and scheduled the next backoff retry. + } + return true + } + + /** + * Throttled recovery trigger safe to call from telemetry / status refresh loops + * when hydration previously failed (`hydrationError != null`). + */ + maybeRetryHydration(now = Date.now()) { + if (this._closed || !this._config.enabled || !this._hydrationError || this._hydrating) return false + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const idx = Math.min(Math.max(0, this._hydrateRetryAttempt - 1), this._hydrateRetryBackoffMs.length - 1) + const minIntervalMs = this._hydrateRetryBackoffMs[idx] + if (this._lastHydrateRetryAt && ts - this._lastHydrateRetryAt < minIntervalMs) return false + this._clearHydrateRetryTimer() + return this._attemptHydrateRecovery(ts) } _reportError(op, err) { @@ -402,6 +484,9 @@ export class DailySessionGate { this._hydrationError = null this._hydrating = false this._hydrationPromise = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() } _syncConfig(now) { @@ -424,6 +509,9 @@ export class DailySessionGate { } else if (!nextConfig.enabled && prev.enabled) { this._hydrating = false this._hydrationError = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() } return { changed, timezoneChanged, newlyEnabled } } @@ -451,6 +539,7 @@ export class DailySessionGate { } _startAsyncHydration(ts) { + this._clearHydrateRetryTimer() const gen = ++this._hydrationGen this._hydrating = true const p = this.hydrateAsync(ts) @@ -458,9 +547,7 @@ export class DailySessionGate { if (this._hydrationGen === gen) { this._hydrating = false this._hydrationPromise = null - try { - this._onHydrated?.(res) - } catch {} + this._notifyHydrated(res) } return res }) @@ -469,6 +556,7 @@ export class DailySessionGate { this._hydrating = false this._hydrationPromise = null this._hydrationError = err + this._scheduleHydrateRecovery(Date.now()) } throw err }) @@ -489,15 +577,23 @@ export class DailySessionGate { if (this._repo?.isPgAsyncMode) { this._startAsyncHydration(ts) } else if (typeof this._repo?.listSince === 'function') { + const wasDegraded = this._hydrationError != null try { const sinceMs = Math.min(nextWindow.dayStartMs, ts - this._retentionMs) const rows = this._repo.listSince(this._platform, sinceMs) - this._mergeRows(rows, nextWindow.dayStartMs) + const loaded = this._mergeRows(rows, nextWindow.dayStartMs) this._hydrated = true this._hydrationError = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + if (wasDegraded) { + this._notifyHydrated({ loaded, window: nextWindow }) + } } catch (err) { this._hydrationError = err this._reportError('hydrate', err) + this._scheduleHydrateRecovery(ts) } } } @@ -720,10 +816,16 @@ export class DailySessionGate { return { loaded: 0, skipped: true, window } } this._pruneInMemoryCommitted(window.dayStartMs) + const wasDegraded = this._hydrationError != null if (!this._repo || typeof this._repo.listSince !== 'function') { this._hydrated = true this._hydrationError = null - return { loaded: 0, window } + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + const res = { loaded: 0, window } + if (wasDegraded) this._notifyHydrated(res) + return res } try { const sinceMs = Math.min(window.dayStartMs, ts - this._retentionMs) @@ -732,11 +834,17 @@ export class DailySessionGate { this._rebuildPendingIndex(window.dayStartMs) this._hydrated = true this._hydrationError = null - return { loaded, window } + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + const res = { loaded, window } + if (wasDegraded) this._notifyHydrated(res) + return res } catch (err) { this._hydrated = false this._hydrationError = err this._reportError('hydrate', err) + this._scheduleHydrateRecovery(ts) throw err } } @@ -749,10 +857,16 @@ export class DailySessionGate { return { loaded: 0, skipped: true, window } } this._pruneInMemoryCommitted(window.dayStartMs) + const wasDegraded = this._hydrationError != null if (!this._repo || typeof this._repo.listSinceAsync !== 'function') { this._hydrated = true this._hydrationError = null - return { loaded: 0, window } + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + const res = { loaded: 0, window } + if (wasDegraded && !this._hydrating) this._notifyHydrated(res) + return res } try { const sinceMs = Math.min(window.dayStartMs, ts - this._retentionMs) @@ -762,11 +876,17 @@ export class DailySessionGate { this._rebuildPendingIndex(activeWindow.dayStartMs) this._hydrated = true this._hydrationError = null - return { loaded, window: activeWindow } + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + const res = { loaded, window: activeWindow } + if (wasDegraded && !this._hydrating) this._notifyHydrated(res) + return res } catch (err) { this._hydrated = false this._hydrationError = err this._reportError('hydrateAsync', err) + this._scheduleHydrateRecovery(ts) throw err } } @@ -1786,16 +1906,17 @@ export class DailySessionGate { } /** Release a pre-commit pending reservation without counting it as a created session. */ - releaseReservation(leaseToken, now = Date.now()) { + _releaseReservationLocal(leaseToken, now = Date.now(), { skipPgFireAndForget = false } = {}) { const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() const window = this._ensureWindow(ts) const token = String(leaseToken || '').trim() if (!token) { return { released: false, uncapped: false, vmId: null, accountKey: null, status: null } } + const shouldSyncRepoRelease = !(skipPgFireAndForget && this._repo?.isPgAsyncMode) const entry = this._pending.get(token) if (!entry) { - if (this._config.enabled) { + if (this._config.enabled && shouldSyncRepoRelease) { try { this._repo?.releaseReservation?.(token) } catch {} @@ -1805,10 +1926,12 @@ export class DailySessionGate { const beforeBlocked = entry.vm ? this._buildStatus(entry.vm, window, { now: ts }).blocked : false this._pending.delete(token) this._unindexPendingEntry(entry) - try { - this._repo?.releaseReservation?.(token) - } catch (err) { - this._reportError('releaseReservation', err) + if (shouldSyncRepoRelease) { + try { + this._repo?.releaseReservation?.(token) + } catch (err) { + this._reportError('releaseReservation', err) + } } const afterStatus = entry.vm ? this._buildStatus(entry.vm, window, { now: ts }) : null return { @@ -1820,8 +1943,12 @@ export class DailySessionGate { } } + releaseReservation(leaseToken, now = Date.now()) { + return this._releaseReservationLocal(leaseToken, now, { skipPgFireAndForget: false }) + } + async releaseReservationAsync(leaseToken, now = Date.now()) { - const res = this.releaseReservation(leaseToken, now) + const res = this._releaseReservationLocal(leaseToken, now, { skipPgFireAndForget: true }) const token = String(leaseToken || '').trim() if (token && this._repo?.isPgAsyncMode && typeof this._repo?.releaseReservationAsync === 'function') { try { diff --git a/src/lib/pool/failover-runner.mjs b/src/lib/pool/failover-runner.mjs index 9d042b39c9..93029906fb 100644 --- a/src/lib/pool/failover-runner.mjs +++ b/src/lib/pool/failover-runner.mjs @@ -299,6 +299,8 @@ const TERMINAL_SWITCH_ERROR_CODES = new Set([ 'session_node_busy', 'fable_requires_max', 'daily_session_limit', + 'daily_session_gate_unavailable', + 'daily_session_gate_hydrating', 'pool_rate_limited', ]) diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 548ae4937e..061949273e 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -741,6 +741,26 @@ export function createHandleProtocol(deps) { }, } } + if (explicitCode === 'daily_session_gate_unavailable' || explicitCode === 'daily_session_gate_hydrating') { + logBag.error_code = explicitCode + logBag.error_message = originalMessage || 'Anthropic daily session gate is temporarily unavailable' + const retryAfter = + Number(result?.retryAfterSec) > 0 + ? Math.max(1, Math.ceil(Number(result.retryAfterSec))) + : retryAfterSeconds(result?.headers?.['retry-after']) || 5 + return { + status: 503, + retryAfterSec: retryAfter, + body: { + type: 'error', + error: { + type: 'api_error', + code: explicitCode, + message: logBag.error_message, + }, + }, + } + } if ( explicitCode === 'session_in_flight' || explicitCode === 'session_queue_full' || diff --git a/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index bb8de1bb15..72ac5ab33d 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -1642,7 +1642,7 @@ export class SchedulerRuntime { } } - #releaseTrackedDailySessionLease(leaseId, now = Date.now()) { + async #releaseTrackedDailySessionLeaseAsync(leaseId, now = Date.now()) { const id = String(leaseId || '').trim() if (!id) return null const entry = this.#dailySessionLeases.get(id) @@ -1651,7 +1651,10 @@ export class SchedulerRuntime { if (this.#dailySessionLeases.size === 0) this.#stopDailySessionHeartbeat() const dailyGate = this.#resolveDailySessionGate() if (dailyGate && (entry.tracked || entry.reserved)) { - const rel = dailyGate.releaseReservation(id, now) + const rel = + typeof dailyGate.releaseReservationAsync === 'function' + ? await dailyGate.releaseReservationAsync(id, now) + : dailyGate.releaseReservation(id, now) if (rel?.uncapped) { this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, false, now) } @@ -2689,6 +2692,9 @@ export class SchedulerRuntime { if (schedulable && !codex) { const dailyGate = this.#resolveDailySessionGate() + if (dailyGate?.hydrationError) { + dailyGate.maybeRetryHydration?.(now) + } if (dailyGate?.isVmNewSessionsBlocked?.(vm, now)) { newSessionsBlocked = true } @@ -3724,10 +3730,35 @@ export class SchedulerRuntime { }) } + #isDailySessionUnavailableOnly(statuses = []) { + if (!Array.isArray(statuses) || statuses.length === 0) return false + return statuses.every((st) => { + if (!st?.degraded && !st?.hydrating) return false + const limit = Number(st?.limit || 0) + const used = Number(st?.used || 0) + const pending = Number(st?.pending || 0) + return !(limit > 0 && used + pending >= limit) + }) + } + + #dailySessionUnavailableError(statuses = [], explain = null) { + const hydratingOnly = statuses.length > 0 && statuses.every((st) => st?.hydrating && !st?.degraded) + const code = hydratingOnly ? 'daily_session_gate_hydrating' : 'daily_session_gate_unavailable' + return new SchedulerApiError({ + status: 503, + code, + message: hydratingOnly + ? 'Anthropic daily session gate is initializing' + : 'Anthropic daily session gate is temporarily unavailable', + retryAfterSec: 5, + ...(explain != null ? { explain } : {}), + }) + } + #dailySessionBlockedStatusesFromExplain(explain, req, extraStatuses = [], now = Date.now()) { const dailyGate = this.#resolveDailySessionGate() if (!dailyGate) return [] - if (req?.is_ephemeral_probe || (req?.is_admin_diagnostic && req?.pin_node_key)) { + if (req?.is_admin_diagnostic) { return [] } const statuses = [...(extraStatuses || [])] @@ -3758,6 +3789,9 @@ export class SchedulerRuntime { if (err.code !== 'pool_exhausted' && err.status !== 503) return null const statuses = this.#dailySessionBlockedStatusesFromExplain(err.explain, req, extraStatuses, now) if (!statuses.length) return null + if (this.#isDailySessionUnavailableOnly(statuses)) { + return this.#dailySessionUnavailableError(statuses, err.explain ?? null) + } return this.#dailySessionLimitError(statuses, err.explain ?? null, now) } @@ -3783,7 +3817,7 @@ export class SchedulerRuntime { if (typeof dailyGate.whenReady === 'function') { await dailyGate.whenReady().catch(() => {}) } - if (req?.is_ephemeral_probe || (req?.is_admin_diagnostic && req?.pin_node_key)) return + if (req?.is_admin_diagnostic) return const sid = String(req?.session_id || '').trim() if (!sid || typeof dailyGate.findCommittedAccountsForSessionAsync !== 'function') return const committedAccounts = await dailyGate.findCommittedAccountsForSessionAsync(sid) @@ -3857,8 +3891,11 @@ export class SchedulerRuntime { throw new SchedulerApiError({ status: 503, code: reserve.reason, - message: 'Anthropic daily session gate is temporarily unavailable', - retryAfterSec: 2, + message: + reserve.reason === 'daily_session_gate_hydrating' + ? 'Anthropic daily session gate is initializing' + : 'Anthropic daily session gate is temporarily unavailable', + retryAfterSec: 5, ...(res?.explain != null ? { explain: res.explain } : {}), }) } @@ -3933,7 +3970,7 @@ export class SchedulerRuntime { async switchNode(params = {}, opts = {}) { const release_lease_id = String(params.releaseLeaseId ?? params.release_lease_id ?? '').trim() - this.#releaseTrackedDailySessionLease(release_lease_id) + await this.#releaseTrackedDailySessionLeaseAsync(release_lease_id) const rawFailure = params.failure || {} const http_status = Number(rawFailure.http_status ?? rawFailure.httpStatus ?? 0) || 0 const error_class = @@ -4078,7 +4115,7 @@ export class SchedulerRuntime { const ttftMs = raw.ttft_ms ?? raw.ttftMs const tokensUsed = raw.tokens_used ?? raw.tokensUsed const leaseIdToRelease = String(raw.lease_id).trim() - this.#releaseTrackedDailySessionLease(leaseIdToRelease) + await this.#releaseTrackedDailySessionLeaseAsync(leaseIdToRelease) const payload = { lease_id: leaseIdToRelease, outcome, @@ -4121,10 +4158,12 @@ export class SchedulerRuntime { } const dailyStatuses = this.#dailySessionBlockedStatusesFromExplain(res.explain, req) if (dailyStatuses.length) { - const dailyErr = this.#dailySessionLimitError(dailyStatuses, res.explain ?? null) + const dailyErr = this.#isDailySessionUnavailableOnly(dailyStatuses) + ? this.#dailySessionUnavailableError(dailyStatuses, res.explain ?? null) + : this.#dailySessionLimitError(dailyStatuses, res.explain ?? null) return { ...res, - error_code: 'daily_session_limit', + error_code: dailyErr.code, retry_after_sec: dailyErr.retryAfterSec, message: dailyErr.message, } diff --git a/test/unit/pool-scheduler.test.mjs b/test/unit/pool-scheduler.test.mjs index 77d00d05df..7e067d1055 100644 --- a/test/unit/pool-scheduler.test.mjs +++ b/test/unit/pool-scheduler.test.mjs @@ -705,7 +705,7 @@ test('validateQuotaRoutingPatch validates quota.daily_session_gate alongside exh ) }) -test('shouldGateSchedulerLease gates only new primary Claude leases and skips continuing/subagent/probe/admin-pin/codex', () => { +test('shouldGateSchedulerLease gates new Claude leases (including subagent_follow_parent & short probes) and skips continuing/admin-diagnostic/codex', () => { const baseReq = { session_id: 'sess-new-1' } const claudeRes = (why) => ({ selected_node: { node_type: 'claude_vm', node_id: 'vm-01' }, @@ -720,13 +720,28 @@ test('shouldGateSchedulerLease gates only new primary Claude leases and skips co // Continuing sessions are NOT gated assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('session_hit')), false) assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('session_hit_after_wait')), false) + assert.equal( + shouldGateSchedulerLease({ ...baseReq, is_ephemeral_probe: true }, claudeRes('ephemeral_follow_session')), + false, + ) - // Verified subagents are NOT gated; client-supplied parent_session_id on a fresh placement IS gated (security) + // M1 security: caller-supplied parent_session_id MUST NOT exempt new session_ids, + // even when Rust returned subagent_follow_parent or ephemeral_follow_session assert.equal(shouldGateSchedulerLease({ ...baseReq, parent_session_id: 'parent-1' }, claudeRes('tier_ranked')), true) - assert.equal(shouldGateSchedulerLease(baseReq, claudeRes('subagent_follow_parent')), false) + assert.equal( + shouldGateSchedulerLease({ ...baseReq, parent_session_id: 'parent-1' }, claudeRes('subagent_follow_parent')), + true, + ) + assert.equal( + shouldGateSchedulerLease( + { ...baseReq, is_ephemeral_probe: true, parent_session_id: 'parent-1' }, + claudeRes('ephemeral_follow_session'), + ), + true, + ) - // Ephemeral probes & admin diagnostic pins are NOT gated - assert.equal(shouldGateSchedulerLease({ ...baseReq, is_ephemeral_probe: true }, claudeRes('tier_ranked')), false) + // M2 security: arbitrary short prompts (`is_ephemeral_probe`) ARE gated; genuine admin diagnostics are NOT gated + assert.equal(shouldGateSchedulerLease({ ...baseReq, is_ephemeral_probe: true }, claudeRes('tier_ranked')), true) assert.equal( shouldGateSchedulerLease( { ...baseReq, is_admin_diagnostic: true, pin_node_key: 'claude_vm:vm-01' }, @@ -734,8 +749,7 @@ test('shouldGateSchedulerLease gates only new primary Claude leases and skips co ), false, ) - // Admin diagnostic without pin_node_key still follows normal gating - assert.equal(shouldGateSchedulerLease({ ...baseReq, is_admin_diagnostic: true }, claudeRes('tier_ranked')), true) + assert.equal(shouldGateSchedulerLease({ ...baseReq, is_admin_diagnostic: true }, claudeRes('tier_ranked')), false) // Missing session_id or non-claude_vm node types (Codex / API endpoint) are NOT gated assert.equal(shouldGateSchedulerLease({ session_id: '' }, claudeRes('tier_ranked')), false) diff --git a/test/unit/scheduler-m3-runtime.test.mjs b/test/unit/scheduler-m3-runtime.test.mjs index 8b31048d41..dd07e24c95 100644 --- a/test/unit/scheduler-m3-runtime.test.mjs +++ b/test/unit/scheduler-m3-runtime.test.mjs @@ -1664,7 +1664,8 @@ test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry assert.equal(x1Tel.new_sessions_blocked, false) await runtime.pushTelemetryNow(telemetry) - // 3. Continuing session (session_hit), subagent, and ephemeral probe all bypass the gate on capped vm-c1 + // 3. Continuing session (session_hit) and genuine admin diagnostic probe bypass the gate on capped vm-c1, + // while a new session_id carrying parentSessionId: sess1 MUST spill off capped vm-c1 (not bypass cap)! const cont = await runtime.acquireNode({ ...baseReq, sessionId: sess1 }) assert.equal(cont.selected_node.node_key, 'claude_vm:vm-c1') assert.equal(cont.explain?.affinity?.why, 'session_hit') @@ -1672,16 +1673,6 @@ test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry await runtime.releaseLease(cont.lease_id, 'ok') assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'continuing session must not increment daily count') - const sub = await runtime.acquireNode({ - ...baseReq, - sessionId: '550e8400-e29b-41d4-a716-446655440102', - parentSessionId: sess1, - }) - assert.equal(sub.selected_node.node_key, 'claude_vm:vm-c1') - await runtime.commitLease(sub.lease_id) - await runtime.releaseLease(sub.lease_id, 'ok') - assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'subagent must not increment daily count') - const probe = await runtime.acquireNode({ ...baseReq, sessionId: '550e8400-e29b-41d4-a716-446655440103', @@ -1691,7 +1682,7 @@ test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry }) assert.equal(probe.selected_node.node_key, 'claude_vm:vm-c1') await runtime.releaseLease(probe.lease_id, 'ok') - assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'probe/admin-pin must not increment daily count') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1, 'admin diagnostic probe must not increment daily count') // 4. Race-guard: even if Rust telemetry is briefly stale (new_sessions_blocked=false on vm-c1), // acquireNode aborts the capped vm-c1 lease and retries cleanly onto vm-c2! @@ -1704,22 +1695,54 @@ test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry assert.equal(dailySessionGate.statusForVm(fx.vms[1]).used, 1) assert.equal(dailySessionGate.statusForVm(fx.vms[1]).blocked, true) - // 5. All Claude VMs capped -> standalone ephemeral probe STILL succeeds without admin pin or parent sticky, - // while forged parentSessionId and brand-new sessions are rejected with 429 daily_session_limit! + // 5. All Claude VMs capped (1/1 each): + // - M1: caller-supplied parentSessionId pointing to LIVE turn-1 session (sess1) + new sessionId -> 429 daily_session_limit! + // - M2: short prompt (`isEphemeralProbe: true`, e.g. "Explain TCP" max_tokens:4096) with or without parentSessionId -> 429 daily_session_limit! + // - Forged parentSessionId and normal new sessions -> 429 daily_session_limit! + // - Genuine admin diagnostic (isAdminDiagnostic: true + pinNodeKey) still works. await runtime.pushTelemetryNow() - // Standalone ephemeral probe (NO pinNodeKey, NO isAdminDiagnostic, NO parentSessionId) - const standaloneProbe = await runtime.acquireNode({ - ...baseReq, - sessionId: '550e8400-e29b-41d4-a716-446655440199', - isEphemeralProbe: true, - }) - assert.ok(standaloneProbe.selected_node?.node_key?.startsWith('claude_vm:')) - await runtime.releaseLease(standaloneProbe.lease_id, 'ok') + // M1 attack: brand-new session_ids with x-kin-parent-session pointing to live sess1 MUST all be rejected 429! + for (let i = 0; i < 3; i += 1) { + await assert.rejects( + () => + runtime.acquireNode({ + ...baseReq, + sessionId: `550e8400-e29b-41d4-a716-44665544018${i}`, + parentSessionId: sess1, + }), + (err) => err instanceof SchedulerApiError && err.status === 429 && err.code === 'daily_session_limit', + 'caller-supplied parentSessionId pointing to live turn-1 session must not bypass daily limit', + ) + } + + // M2 attack: short prompt (`{messages:[{role:'user',content:'Explain TCP'}], max_tokens:4096}` -> isEphemeralProbe: true) + // MUST be rejected with 429 daily_session_limit (both standalone and paired with live parentSessionId)! + await assert.rejects( + () => + runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440199', + isEphemeralProbe: true, + }), + (err) => err instanceof SchedulerApiError && err.status === 429 && err.code === 'daily_session_limit', + 'short prompt (isEphemeralProbe: true) must be rejected with 429 daily_session_limit when all VMs are capped', + ) + await assert.rejects( + () => + runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440197', + isEphemeralProbe: true, + parentSessionId: sess1, + }), + (err) => err instanceof SchedulerApiError && err.status === 429 && err.code === 'daily_session_limit', + 'short prompt with live parentSessionId must also be rejected with 429 daily_session_limit when all VMs are capped', + ) assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1) assert.equal(dailySessionGate.statusForVm(fx.vms[1]).used, 1) - // Forged parentSessionId (no active parent sticky session) MUST NOT bypass daily limit (Cursor HIGH) + // Forged parentSessionId (no active parent sticky session) MUST NOT bypass daily limit await assert.rejects( () => runtime.acquireNode({ @@ -1767,6 +1790,143 @@ test('M3 runtime + DailySessionGate: telemetry new_sessions_blocked, race retry assert.equal(cappedRes.body?.error?.code, 'daily_session_limit') assert.ok(Number(cappedRes.retryAfterSec) >= 1) assert.equal(JSON.stringify(cappedRes.body).includes('explain'), false) + + // 6. When cap has room (raise cap to 2), a new session with parentSessionId: sess1 MUST count against vm-c1's ledger! + dailySessionGate.reloadConfig({ + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 2, pro: 2, max_5x: 2, max_20x: 2, team: 2, enterprise: 2 }, + }) + await runtime.pushTelemetryNow() + const subCounted = await runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440102', + parentSessionId: sess1, + }) + assert.equal(subCounted.selected_node.node_key, 'claude_vm:vm-c1') + await runtime.commitLease(subCounted.lease_id) + await runtime.releaseLease(subCounted.lease_id, 'ok') + assert.equal( + dailySessionGate.statusForVm(fx.vms[0]).used, + 2, + 'new session_id carrying live parentSessionId must count against the daily ledger when cap has room', + ) +}) + +test('M3 runtime + DailySessionGate M4: failed hydration returns 503 daily_session_gate_unavailable and auto-recovers once DB returns', async (t) => { + const tmp = makeTempDir('vm2api-m3-dsg-m4-') + const fx = makeFixtureState(tmp) + let dbDown = true + const committedRows = [] + const fakePgPool = { + async query(sql, params = []) { + const q = String(sql) + if (q.includes('FROM vm_daily_session_creations')) { + if (dbDown) throw new Error('pg_hydrate_conn_refused') + return { rows: committedRows } + } + if (q.includes('INSERT INTO vm_daily_session_creations')) { + committedRows.push({ + platform: params[0], + account_key: params[1], + day_key: params[2], + session_id: params[3], + vm_id: params[4], + created_at: params[5], + }) + return { rowCount: 1, rows: [] } + } + return { rows: [], rowCount: 0 } + }, + } + + let runtime = null + const gateConfig = { + enabled: true, + reset_timezone: 'UTC', + tier_limits: { default: 2, pro: 2, max_5x: 2, max_20x: 2, team: 2, enterprise: 2 }, + } + const dailySessionGate = createDailySessionGate({ + config: gateConfig, + pgPool: fakePgPool, + hydrateRetryBackoffMs: [30, 30, 50], + onError: () => {}, + onHydrated: () => { + void runtime?.pushTelemetryNow?.().catch(() => {}) + }, + }) + runtime = createSchedulerRuntime({ + getDb: () => fx.db, + getVms: () => fx.vms, + getRoutingConfig: () => ({ quota: { daily_session_gate: gateConfig } }), + apiKeyStore: makeApiKeyStore(fx.db), + apiEndpointStore: { listRaw: () => fx.endpoints }, + geminiScheduler: { listEnvironments: () => fx.geminiEnvs }, + dailySessionGate, + telemetryIntervalMs: 0, + clientOptions: { + binPath: BIN_PATH, + dataDir: tmp, + socketPath: path.join(tmp, 'dsg-m4.sock'), + tokenPath: path.join(tmp, 'dsg-m4.token'), + capFile: path.join(tmp, 'dsg-m4.cap.json'), + }, + }) + t.after(async () => { + dailySessionGate.close() + await runtime.shutdown({ drain: false, stopProcess: true }) + fx.db.close() + fs.rmSync(tmp, { recursive: true, force: true }) + }) + + await assert.rejects(() => dailySessionGate.hydrateAsync(), /pg_hydrate_conn_refused/) + await runtime.start({ waitMs: 5_000, startLoops: false }) + await runtime.pushTelemetryNow() + + const baseReq = { + originPoolId: fx.poolAnth.id, + apiKeyRecord: { ...fx.strictKey, allowed_pool_ids: [fx.poolAnth.id] }, + apiKeyKind: 'managed', + model: 'claude-sonnet-4-6', + protocol: 'anthropic', + } + + // While degraded from hydration failure, acquireNode and explainDispatch MUST return 503 daily_session_gate_unavailable + // with short retryAfterSec=5 (NOT 429 daily_session_limit with midnight Retry-After)! + const expDegraded = await runtime.explainDispatch({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440501', + }) + assert.equal(expDegraded.ok, false) + assert.equal(expDegraded.error_code, 'daily_session_gate_unavailable') + assert.equal(expDegraded.retry_after_sec, 5) + + await assert.rejects( + () => runtime.acquireNode({ ...baseReq, sessionId: '550e8400-e29b-41d4-a716-446655440502' }), + (err) => + err instanceof SchedulerApiError && + err.status === 503 && + err.code === 'daily_session_gate_unavailable' && + err.retryAfterSec === 5, + ) + + // DB recovers -> automatic re-hydration clears degraded/blocked & onHydrated pushes telemetry -> new session succeeds! + dbDown = false + const deadline = Date.now() + 3_000 + while (dailySessionGate.hydrationError && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 20)) + } + assert.equal(dailySessionGate.hydrationError, null) + // Give the async onHydrated -> pushTelemetryNow a brief tick to reach Rust + await new Promise((r) => setTimeout(r, 80)) + + const acqRecovered = await runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440503', + }) + assert.ok(acqRecovered.selected_node.node_key.startsWith('claude_vm:')) + await runtime.commitLease(acqRecovered.lease_id) + await runtime.releaseLease(acqRecovered.lease_id, 'ok') }) test('M3 runtime + DailySessionGate: concurrent duplicate-session pre-commit release has zero leak & shared-account sibling telemetry pushes together', async (t) => { diff --git a/test/unit/vm-quota-override.test.mjs b/test/unit/vm-quota-override.test.mjs index 83b2e04795..323e6a6d8f 100644 --- a/test/unit/vm-quota-override.test.mjs +++ b/test/unit/vm-quota-override.test.mjs @@ -848,7 +848,8 @@ test('DailySessionGate cross-day resume & shouldGateSchedulerLease parent_sessio // Brand-new session on Day 2 is still blocked assert.equal(g2.canAcceptNewSession(vm, 'brand-new-day2', day2 + 300).ok, false) - // Security (Cursor HIGH): client-supplied parent_session_id MUST NOT exempt a new primary placement + // Security (M1 & M2): caller-supplied parent_session_id (even with live parent stick) and + // arbitrary short prompts (`is_ephemeral_probe`) MUST still be governed by the daily session gate! assert.equal( shouldGateSchedulerLease( { session_id: 's-forged', parent_session_id: 'fake-parent' }, @@ -859,10 +860,89 @@ test('DailySessionGate cross-day resume & shouldGateSchedulerLease parent_sessio ) assert.equal( shouldGateSchedulerLease( - { session_id: 's-verified-sub', parent_session_id: 'real-parent' }, + { session_id: 's-new-sub', parent_session_id: 'real-parent' }, { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'subagent_follow_parent' } } }, ), + true, + 'caller-supplied parent_session_id with a brand-new session_id must NOT bypass daily session gate', + ) + assert.equal( + shouldGateSchedulerLease( + { session_id: 's-short-prompt', is_ephemeral_probe: true }, + { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'tier_ranked' } } }, + ), + true, + 'arbitrary short prompt (is_ephemeral_probe) must NOT bypass daily session gate', + ) + assert.equal( + shouldGateSchedulerLease( + { session_id: 's-short-parent', is_ephemeral_probe: true, parent_session_id: 'real-parent' }, + { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'ephemeral_follow_session' } } }, + ), + true, + 'ephemeral_follow_session via caller-supplied parent_session_id with a new session_id must still be gated', + ) + assert.equal( + shouldGateSchedulerLease( + { session_id: 's-own-session', is_ephemeral_probe: true }, + { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'ephemeral_follow_session' } } }, + ), + false, + 'seatless probe following its own live session pin (no parent_session_id) remains exempt', + ) + assert.equal( + shouldGateSchedulerLease( + { session_id: 's-admin-diag', is_admin_diagnostic: true }, + { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'tier_ranked' } } }, + ), false, - 'verified subagent_follow_parent placement is exempted', + 'genuine admin diagnostic requests remain exempt', ) }) + +test('DailySessionGate hydration failure auto-recovers with backoff and fires onHydrated once DB recovers', async (t) => { + const vm = { id: 'vm-rec', claude: { account_uuid: 'acc-rec', subscription_type: 'pro' } } + let dbDown = true + let listCalls = 0 + const hydratedEvents = [] + + const fakePgPool = { + async query(sql) { + if (String(sql).includes('FROM vm_daily_session_creations')) { + listCalls += 1 + if (dbDown) throw new Error('pg_temp_outage') + return { rows: [] } + } + return { rows: [], rowCount: 0 } + }, + } + + const gate = new DailySessionGate({ + config: { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 1 } }, + pgPool: fakePgPool, + hydrateRetryBackoffMs: [25, 25, 50], + onError: () => {}, + onHydrated: (res) => hydratedEvents.push(res), + }) + t.after(() => gate.close()) + + await assert.rejects(() => gate.hydrateAsync(), /pg_temp_outage/) + const degradedStatus = gate.statusForVm(vm) + assert.equal(degradedStatus.blocked, true) + assert.equal(degradedStatus.degraded, true) + assert.equal(gate.hydrationError?.message, 'pg_temp_outage') + + // DB recovers; backoff timer automatically re-hydrates, clears degraded/blocked, and invokes onHydrated. + dbDown = false + const deadline = Date.now() + 2_000 + while (gate.hydrationError && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 15)) + } + assert.equal(gate.hydrationError, null, 'hydrationError must clear automatically after DB recovery') + assert.ok(listCalls >= 2, `expected retry hydration call, got ${listCalls}`) + assert.equal(hydratedEvents.length, 1, 'onHydrated must fire once upon recovery') + const recoveredStatus = gate.statusForVm(vm) + assert.equal(recoveredStatus.degraded, undefined) + assert.equal(recoveredStatus.blocked, false) + assert.equal(recoveredStatus.remaining, 1) +}) From 96ffb76ee8d3b9c41ac1cfa868078c576a5c20c9 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 03:51:24 +0800 Subject: [PATCH 3/3] fix(quota): release daily reservation when scheduler commit fails and sync SQL header comments --- .../077_vm_daily_session_creations.sql | 4 +-- .../018_vm_daily_session_creations.sql | 4 +-- src/lib/scheduler/scheduler-runtime.mjs | 30 +++++++++++++++---- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/lib/db/migrations/077_vm_daily_session_creations.sql b/src/lib/db/migrations/077_vm_daily_session_creations.sql index 6a0f751131..84fa05a320 100644 --- a/src/lib/db/migrations/077_vm_daily_session_creations.sql +++ b/src/lib/db/migrations/077_vm_daily_session_creations.sql @@ -1,6 +1,6 @@ --- 076_vm_daily_session_creations — Persistent per-account daily new session creation ledger +-- 077_vm_daily_session_creations — Persistent per-account daily new session creation ledger -- and shared in-flight reservation lease table. --- Mirrors PostgreSQL migration 015_vm_daily_session_creations.sql. +-- Mirrors PostgreSQL migration 018_vm_daily_session_creations.sql. CREATE TABLE IF NOT EXISTS vm_daily_session_creations ( platform TEXT NOT NULL, diff --git a/src/lib/db/pg/pg-migrations/018_vm_daily_session_creations.sql b/src/lib/db/pg/pg-migrations/018_vm_daily_session_creations.sql index 48ed0c1eef..4c7ffc0fc2 100644 --- a/src/lib/db/pg/pg-migrations/018_vm_daily_session_creations.sql +++ b/src/lib/db/pg/pg-migrations/018_vm_daily_session_creations.sql @@ -1,7 +1,7 @@ --- 015_vm_daily_session_creations.sql +-- 018_vm_daily_session_creations.sql -- Persistent per-account daily new session creation ledger and shared in-flight -- reservation lease table for daily session creation gate. --- Mirrors SQLite migration 076_vm_daily_session_creations.sql. +-- Mirrors SQLite migration 077_vm_daily_session_creations.sql. CREATE TABLE IF NOT EXISTS vm_daily_session_creations ( platform TEXT NOT NULL, diff --git a/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index b024c953f9..a542504cae 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -4048,13 +4048,32 @@ export class SchedulerRuntime { this.#dailySessionLeases.delete(id) if (this.#dailySessionLeases.size === 0) this.#stopDailySessionHeartbeat() } + let commitRes try { - return await this.#client.commit(id, opts) - } finally { - if (entry) { + commitRes = await this.#client.commit(id, opts) + } catch (err) { + if (entry && (entry.tracked || entry.reserved)) { const dailyGate = this.#resolveDailySessionGate() - if (dailyGate && entry.shouldTrack) { + if (dailyGate) { const now = Date.now() + try { + const rel = + typeof dailyGate.releaseReservationAsync === 'function' + ? await dailyGate.releaseReservationAsync(id, now) + : dailyGate.releaseReservation(id, now) + if (rel?.uncapped) { + this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, false, now) + } + } catch {} + } + } + throw err + } + if (entry) { + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate && entry.shouldTrack) { + const now = Date.now() + try { const committed = typeof dailyGate.commitReservationAsync === 'function' ? await dailyGate.commitReservationAsync(id, { @@ -4070,9 +4089,10 @@ export class SchedulerRuntime { if (committed?.newlyCapped) { this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, true, now) } - } + } catch {} } } + return commitRes } async releaseLease(leaseIdOrPayload, outcomeOrPayload = {}, maybeOpts = {}) {