diff --git a/docs/PANEL_API.md b/docs/PANEL_API.md index 4007458bf..f2c0f69fd 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 上限 @@ -354,6 +356,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/scheduler/crates/scheduler-core/src/admission.rs b/scheduler/crates/scheduler-core/src/admission.rs index 47ac7061b..085357fa7 100644 --- a/scheduler/crates/scheduler-core/src/admission.rs +++ b/scheduler/crates/scheduler-core/src/admission.rs @@ -253,6 +253,8 @@ pub fn filter_members_for<'a>( continue; } let continuing = continuing_node == Some(&node.node_key); + let continuing_known_session = + continuing || req.continuing_node_keys.contains(&node.node_key); if st.host_memory_pressure && !continuing { excluded.push(ExcludedEntry { pool_id: pool.id.clone(), @@ -262,7 +264,7 @@ pub fn filter_members_for<'a>( }); continue; } - if st.new_sessions_blocked && !continuing { + 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 a009035cc..724ff7bdc 100644 --- a/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs +++ b/scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs @@ -88,6 +88,7 @@ fn base_req( model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], } } @@ -2970,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/scheduler/crates/scheduler-core/tests/admission_codex_quota_tests.rs b/scheduler/crates/scheduler-core/tests/admission_codex_quota_tests.rs index c65673906..d80e774c6 100644 --- a/scheduler/crates/scheduler-core/tests/admission_codex_quota_tests.rs +++ b/scheduler/crates/scheduler-core/tests/admission_codex_quota_tests.rs @@ -97,6 +97,7 @@ fn make_req(model: &str, family: ModelFamily) -> AcquireRequest { model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], } } diff --git a/scheduler/crates/scheduler-core/tests/session_gate_tests.rs b/scheduler/crates/scheduler-core/tests/session_gate_tests.rs index 75be6d789..391c362c9 100644 --- a/scheduler/crates/scheduler-core/tests/session_gate_tests.rs +++ b/scheduler/crates/scheduler-core/tests/session_gate_tests.rs @@ -111,6 +111,7 @@ fn make_req(req_id: &str, pool_id: &str, family: ModelFamily, sid: &str) -> Acqu model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], } } diff --git a/scheduler/crates/scheduler-core/tests/tier_rank_health_tests.rs b/scheduler/crates/scheduler-core/tests/tier_rank_health_tests.rs index e65b932bb..046e59bbc 100644 --- a/scheduler/crates/scheduler-core/tests/tier_rank_health_tests.rs +++ b/scheduler/crates/scheduler-core/tests/tier_rank_health_tests.rs @@ -81,6 +81,7 @@ fn req(req_id: &str, pool_id: &str, model: &str, sid: &str) -> AcquireRequest { model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], } } diff --git a/scheduler/crates/scheduler-daemon/tests/http_uds_integration.rs b/scheduler/crates/scheduler-daemon/tests/http_uds_integration.rs index ef7156644..789b4aecc 100644 --- a/scheduler/crates/scheduler-daemon/tests/http_uds_integration.rs +++ b/scheduler/crates/scheduler-daemon/tests/http_uds_integration.rs @@ -103,6 +103,7 @@ fn make_acquire(req_id: &str, sid: &str, mid: Option<&str>) -> AcquireRequest { model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], } } diff --git a/scheduler/crates/scheduler-proto/src/ipc.rs b/scheduler/crates/scheduler-proto/src/ipc.rs index 8b56e44cb..a7452cb6c 100644 --- a/scheduler/crates/scheduler-proto/src/ipc.rs +++ b/scheduler/crates/scheduler-proto/src/ipc.rs @@ -236,6 +236,10 @@ pub struct AcquireRequest { /// a `stood_in` spill preserves the existing session pin instead of moving it on commit. #[serde(default = "default_true")] pub session_affinity_first: bool, + /// Nodes where `session_id` was already committed on an earlier calendar day + /// (verified from persistent DB), exempting those nodes from `new_sessions_blocked`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub continuing_node_keys: Vec, } #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/scheduler/crates/scheduler-proto/tests/proto_contract.rs b/scheduler/crates/scheduler-proto/tests/proto_contract.rs index f532b03e0..58ac82988 100644 --- a/scheduler/crates/scheduler-proto/tests/proto_contract.rs +++ b/scheduler/crates/scheduler-proto/tests/proto_contract.rs @@ -304,6 +304,7 @@ fn switch_heartbeat_commit_release_roundtrip() { model_gated_node_keys: vec![], skip_session_gate: false, session_affinity_first: true, + continuing_node_keys: vec![], }, }; let encoded = serde_json::to_string(&sw).unwrap(); diff --git a/scripts/migrate-sqlite-to-pg.mjs b/scripts/migrate-sqlite-to-pg.mjs index 3b2bffc4a..6bda3d02f 100755 --- a/scripts/migrate-sqlite-to-pg.mjs +++ b/scripts/migrate-sqlite-to-pg.mjs @@ -65,6 +65,8 @@ export const MIGRATION_TABLES = [ 'scheduler_node_penalties', 'vms', 'codex_slot_runtime', + 'vm_daily_session_creations', + 'vm_daily_session_reservations', 'thinking_signature_owners', 'usage_logs', 'request_log_debug', diff --git a/scripts/seed-mock-sqlite.mjs b/scripts/seed-mock-sqlite.mjs index 7fbce62e1..61538c638 100755 --- a/scripts/seed-mock-sqlite.mjs +++ b/scripts/seed-mock-sqlite.mjs @@ -343,6 +343,19 @@ 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) + db.prepare(` + INSERT INTO vm_daily_session_reservations (lease_token, platform, account_key, session_id, vm_id, reserved_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run('tok-mock-01', 'anthropic', 'acct-mock-01', 'sess-daily-pending', 'vm-01', nowMs, nowMs + 600_000) + // 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 b5b1b6671..0d8a70162 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 36180b540..87e5a667c 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' @@ -897,6 +904,7 @@ export async function buildDashboard({ proxyPool = null, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, bypass = false, }) { // Expired runtime windows are cleared asynchronously by `pool-scheduler.maintain()`; @@ -943,6 +951,7 @@ export async function buildDashboard({ codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, supplierTag: supplierById?.get(v.id) || null, + dailySessionGate, }), ) const accounts = liveAccounts(snap.accounts, listed) @@ -1046,6 +1055,7 @@ export async function buildVmList({ requestLog = null, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, bypass = false, } = {}) { const active = getActiveVmId(cfg.paths.project) @@ -1079,6 +1089,7 @@ export async function buildVmList({ codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, supplierTag: supplierById?.get(v.id) || null, + dailySessionGate, }), ) const accounts = snap?.accounts || [] @@ -1118,6 +1129,7 @@ export async function buildVmDetail({ slotProcessStatus = readSlotProcessStatus, clusterNodes = [], supplierTagStore = null, + dailySessionGate = null, role = 'admin', bypass = false, }) { @@ -1161,6 +1173,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 () => { @@ -1941,7 +1954,10 @@ export async function buildRouting({ }) 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 || {}, @@ -1978,6 +1994,7 @@ export async function snapshotAccountPool({ poolScheduler = null, proxyPool = null, requestLog = null, + dailySessionGate = null, bypass = false, }) { const active = getActiveVmId(cfg.paths.project) @@ -2010,6 +2027,7 @@ export async function snapshotAccountPool({ runtimeById, codexInflightByVmId: codexObs.inflightByVmId, codexRpmByVmId: codexObs.rpmByVmId, + dailySessionGate, }), ) const accounts = snap?.accounts || [] @@ -2473,6 +2491,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, @@ -2482,6 +2533,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, @@ -2564,8 +2617,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 228adff39..ef8080c98 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -966,11 +966,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 || {}, @@ -1900,7 +1909,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 {} @@ -2278,6 +2289,7 @@ export function createPanelHandler(ctx) { }, } } + notifySchedulerTelemetry() return { ok: true, applied, publicEngineRuntime } } @@ -4236,6 +4248,7 @@ export function createPanelHandler(ctx) { proxyPool, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), bypass, }), { freshTtlMs: 5_000, ttlMs: 15_000, bypass }, @@ -4271,6 +4284,7 @@ export function createPanelHandler(ctx) { ownerUserId, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), bypass, }), { freshTtlMs: 5_000, ttlMs: 15_000, bypass }, @@ -5241,6 +5255,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: ident.role, bypass, }) @@ -5279,6 +5294,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: panelIdentity(req).role, }) return json(res, 200, detail) @@ -5564,6 +5580,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 }) @@ -5738,6 +5755,7 @@ export function createPanelHandler(ctx) { kernelHealth: panelKernelHealth, clusterNodes: clusterNodesOf(ctx), supplierTagStore, + dailySessionGate: resolveDailySessionGate(), role: panelIdentity(req).role, }) if (slotPolicyResult && detail?.data) { @@ -9040,6 +9058,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 38f986e91..4e2d2ab61 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 { RateLimitService } from '../pool/rate-limit-service.mjs' @@ -88,6 +89,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 @@ -618,6 +621,7 @@ export function createRoutingRuntime(ctx) { const prevCragZombieGuard = draft.crag_zombie_guard const prevNotify = draft.notify const prevTiers = draft.tiers + const prevDailySessionGate = draft.quota?.daily_session_gate const prevIdleMs = streamIdleTimeoutMs(currentRouting) const prevRequestBytes = maxRequestBytes(currentRouting) const prevUploadInterval = telemetryUploadInterval(currentRouting) @@ -625,7 +629,16 @@ export function createRoutingRuntime(ctx) { const prevDisableNonessential = telemetryDisableNonessentialTraffic(currentRouting) if (body.sticky) draft.sticky = { ...(draft.sticky || {}), ...body.sticky } - if (body.quota) draft.quota = { ...(draft.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) + draft.quota = { + ...(draft.quota || {}), + ...body.quota, + daily_session_gate: nextDailyGate, + } + } if (body.concurrency) draft.concurrency = { ...(draft.concurrency || {}), ...body.concurrency } if (body.pool) { draft.pool = normalizePoolRouting({ ...(draft.pool || {}), ...body.pool }) @@ -761,6 +774,7 @@ export function createRoutingRuntime(ctx) { } ctx.stickyRouter.reloadConfig(routingConfig) ctx.accountQuota.reloadConfig(routingConfig) + getDailySessionGate()?.reloadConfig?.(routingConfig) getPool()?.reloadConfig?.(poolSchedulerConfig()) const sessionSlotsApplied = body.inference && Object.hasOwn(body.inference, 'session_slots') @@ -865,6 +879,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 2d459b840..07dc86842 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', @@ -1360,6 +1361,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, @@ -1703,6 +1716,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/core/timezone.mjs b/src/lib/core/timezone.mjs index 3254b838e..9f1ff2aac 100644 --- a/src/lib/core/timezone.mjs +++ b/src/lib/core/timezone.mjs @@ -51,14 +51,56 @@ export function zonedParts(ms, timeZone) { return out } -/** Epoch ms for a wall-clock time in `timeZone` (DST-safe, two passes). Out-of-range days roll over. */ +function seenWallMs(ms, timeZone) { + const seen = zonedParts(ms, timeZone) + return Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute, seen.second) +} + +/** + * Epoch ms for a wall-clock time in `timeZone` (DST-safe, including skipped-midnight + * spring-forward transitions such as America/Santiago 2026-09-06). Out-of-range days roll over. + */ export function zonedWallToMs({ year, month, day, hour = 0, minute = 0 }, timeZone) { - const wall = Date.UTC(year, month - 1, day, hour, minute) - let ms = wall - for (let i = 0; i < 2; i++) { - const seen = zonedParts(ms, timeZone) - const seenWall = Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute) - ms += wall - seenWall + const target = Date.UTC(year, month - 1, day, hour, minute) + let ms = target + let matched = null + for (let i = 0; i < 3; i++) { + const seen = seenWallMs(ms, timeZone) + if (seen === target) { + matched = ms + break + } + ms += target - seen + } + if (matched !== null) { + let best = matched + // Ambiguous fall-back wall time: return the earliest matching instant. + for (const shift of [3_600_000, 1_800_000, 7_200_000]) { + const earlier = best - shift + if (seenWallMs(earlier, timeZone) === target) { + best = earlier + break + } + } + return best + } + + // Non-existent wall time inside a spring-forward DST gap (e.g. skipped midnight): + // find the exact first valid instant at or after `target`. + let lo = ms + let hi = ms + const stepMs = 3_600_000 + for (let i = 0; i < 6 && seenWallMs(lo, timeZone) >= target; i++) lo -= stepMs + for (let i = 0; i < 6 && seenWallMs(hi, timeZone) < target; i++) hi += stepMs + if (seenWallMs(lo, timeZone) < target && seenWallMs(hi, timeZone) >= target) { + let loSec = Math.floor(lo / 1_000) + let hiSec = Math.ceil(hi / 1_000) + while (loSec + 1 < hiSec) { + const midSec = Math.floor((loSec + hiSec) / 2) + if (seenWallMs(midSec * 1_000, timeZone) >= target) hiSec = midSec + else loSec = midSec + } + return hiSec * 1_000 } return ms } diff --git a/src/lib/db/migrations/077_vm_daily_session_creations.sql b/src/lib/db/migrations/077_vm_daily_session_creations.sql new file mode 100644 index 000000000..84fa05a32 --- /dev/null +++ b/src/lib/db/migrations/077_vm_daily_session_creations.sql @@ -0,0 +1,32 @@ +-- 077_vm_daily_session_creations — Persistent per-account daily new session creation ledger +-- and shared in-flight reservation lease table. +-- Mirrors PostgreSQL migration 018_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); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_creations_session + ON vm_daily_session_creations (platform, account_key, session_id); + +CREATE TABLE IF NOT EXISTS vm_daily_session_reservations ( + lease_token TEXT PRIMARY KEY, + platform TEXT NOT NULL, + account_key TEXT NOT NULL, + session_id TEXT NOT NULL, + vm_id TEXT NOT NULL, + reserved_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_reservations_account + ON vm_daily_session_reservations (platform, account_key, expires_at); 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 new file mode 100644 index 000000000..4c7ffc0fc --- /dev/null +++ b/src/lib/db/pg/pg-migrations/018_vm_daily_session_creations.sql @@ -0,0 +1,33 @@ +-- 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 077_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); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_creations_session + ON vm_daily_session_creations (platform, account_key, session_id); + +CREATE TABLE IF NOT EXISTS vm_daily_session_reservations ( + lease_token TEXT PRIMARY KEY, + platform TEXT NOT NULL, + account_key TEXT NOT NULL, + session_id TEXT NOT NULL, + vm_id TEXT NOT NULL, + reserved_at BIGINT NOT NULL, + expires_at BIGINT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_vm_daily_session_reservations_account + ON vm_daily_session_reservations (platform, account_key, expires_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 000000000..535d5a016 --- /dev/null +++ b/src/lib/db/repos/daily-session-gate-repo.mjs @@ -0,0 +1,846 @@ +/** + * Dual-DB repository for per-account daily new session creation records + * (`vm_daily_session_creations`) and shared cross-process in-flight + * reservations (`vm_daily_session_reservations`). + * + * SQLite uses prepared synchronous statements inside `BEGIN IMMEDIATE` + * transactions so multiple `DailySessionGate` instances / processes sharing a + * SQLite database cannot over-issue past the cap. + * + * PostgreSQL 18 uses non-blocking `pgPool.connect()` / `pgPool.query()` + * (`0 Atomics.wait` on the hot path) with `pg_advisory_xact_lock` per + * `(platform, account_key)` for cross-process atomic reserve & commit. + */ +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' + +const SQLITE_HAS_SESSION_SQL = `SELECT 1 AS ok FROM vm_daily_session_creations +WHERE platform = ? AND account_key = ? AND session_id = ? +LIMIT 1` + +const PG_HAS_SESSION_SQL = `SELECT 1 AS ok FROM vm_daily_session_creations +WHERE platform = $1 AND account_key = $2 AND session_id = $3 +LIMIT 1` + +const SQLITE_FIND_ACCOUNTS_FOR_SESSION_SQL = `SELECT DISTINCT account_key FROM vm_daily_session_creations +WHERE platform = ? AND session_id = ?` + +const PG_FIND_ACCOUNTS_FOR_SESSION_SQL = `SELECT DISTINCT account_key FROM vm_daily_session_creations +WHERE platform = $1 AND session_id = $2` + +const SQLITE_COUNT_USED_SQL = `SELECT COUNT(DISTINCT session_id) AS c FROM vm_daily_session_creations +WHERE platform = ? AND account_key = ? AND created_at >= ?` + +const PG_COUNT_USED_SQL = `SELECT COUNT(DISTINCT session_id)::int AS c FROM vm_daily_session_creations +WHERE platform = $1 AND account_key = $2 AND created_at >= $3` + +const SQLITE_COUNT_PENDING_SQL = `SELECT COUNT(DISTINCT r.session_id) AS c +FROM vm_daily_session_reservations r +WHERE r.platform = ? AND r.account_key = ? AND r.expires_at > ? + AND NOT EXISTS ( + SELECT 1 FROM vm_daily_session_creations c + WHERE c.platform = r.platform AND c.account_key = r.account_key + AND c.session_id = r.session_id AND c.created_at >= ? + )` + +const PG_COUNT_PENDING_SQL = `SELECT COUNT(DISTINCT r.session_id)::int AS c +FROM vm_daily_session_reservations r +WHERE r.platform = $1 AND r.account_key = $2 AND r.expires_at > $3 + AND NOT EXISTS ( + SELECT 1 FROM vm_daily_session_creations c + WHERE c.platform = r.platform AND c.account_key = r.account_key + AND c.session_id = r.session_id AND c.created_at >= $4 + )` + +const SQLITE_COUNT_OTHER_PENDING_SQL = `SELECT COUNT(DISTINCT r.session_id) AS c +FROM vm_daily_session_reservations r +WHERE r.platform = ? AND r.account_key = ? AND r.expires_at > ? AND r.session_id <> ? + AND NOT EXISTS ( + SELECT 1 FROM vm_daily_session_creations c + WHERE c.platform = r.platform AND c.account_key = r.account_key + AND c.session_id = r.session_id AND c.created_at >= ? + )` + +const PG_COUNT_OTHER_PENDING_SQL = `SELECT COUNT(DISTINCT r.session_id)::int AS c +FROM vm_daily_session_reservations r +WHERE r.platform = $1 AND r.account_key = $2 AND r.expires_at > $3 AND r.session_id <> $4 + AND NOT EXISTS ( + SELECT 1 FROM vm_daily_session_creations c + WHERE c.platform = r.platform AND c.account_key = r.account_key + AND c.session_id = r.session_id AND c.created_at >= $5 + )` + +const SQLITE_HAS_PENDING_SESSION_SQL = `SELECT 1 AS ok FROM vm_daily_session_reservations +WHERE platform = ? AND account_key = ? AND session_id = ? AND expires_at > ? +LIMIT 1` + +const PG_HAS_PENDING_SESSION_SQL = `SELECT 1 AS ok FROM vm_daily_session_reservations +WHERE platform = $1 AND account_key = $2 AND session_id = $3 AND expires_at > $4 +LIMIT 1` + +const SQLITE_UPSERT_RESERVATION_SQL = `INSERT INTO vm_daily_session_reservations ( + lease_token, platform, account_key, session_id, vm_id, reserved_at, expires_at +) VALUES (?, ?, ?, ?, ?, ?, ?) +ON CONFLICT (lease_token) DO UPDATE SET + platform = excluded.platform, + account_key = excluded.account_key, + session_id = excluded.session_id, + vm_id = excluded.vm_id, + reserved_at = excluded.reserved_at, + expires_at = excluded.expires_at` + +const PG_UPSERT_RESERVATION_SQL = `INSERT INTO vm_daily_session_reservations ( + lease_token, platform, account_key, session_id, vm_id, reserved_at, expires_at +) VALUES ($1, $2, $3, $4, $5, $6, $7) +ON CONFLICT (lease_token) DO UPDATE SET + platform = EXCLUDED.platform, + account_key = EXCLUDED.account_key, + session_id = EXCLUDED.session_id, + vm_id = EXCLUDED.vm_id, + reserved_at = EXCLUDED.reserved_at, + expires_at = EXCLUDED.expires_at` + +const SQLITE_DELETE_EXPIRED_RES_SQL = `DELETE FROM vm_daily_session_reservations +WHERE platform = ? AND account_key = ? AND expires_at <= ?` + +const PG_DELETE_EXPIRED_RES_SQL = `DELETE FROM vm_daily_session_reservations +WHERE platform = $1 AND account_key = $2 AND expires_at <= $3` + +const SQLITE_DELETE_RES_BY_TOKEN_SQL = 'DELETE FROM vm_daily_session_reservations WHERE lease_token = ?' +const PG_DELETE_RES_BY_TOKEN_SQL = 'DELETE FROM vm_daily_session_reservations WHERE lease_token = $1' + +const SQLITE_DELETE_RES_BY_SESSION_SQL = `DELETE FROM vm_daily_session_reservations +WHERE platform = ? AND account_key = ? AND session_id = ?` + +const PG_DELETE_RES_BY_SESSION_SQL = `DELETE FROM vm_daily_session_reservations +WHERE platform = $1 AND account_key = $2 AND session_id = $3` + +const SQLITE_TOUCH_RES_SQL = 'UPDATE vm_daily_session_reservations SET expires_at = ? WHERE lease_token = ?' +const PG_TOUCH_RES_SQL = 'UPDATE vm_daily_session_reservations SET expires_at = $1 WHERE lease_token = ANY($2::text[])' + +const SQLITE_LIST_ACTIVE_RES_SQL = `SELECT lease_token, platform, account_key, session_id, vm_id, reserved_at, expires_at +FROM vm_daily_session_reservations +WHERE platform = ? AND expires_at > ?` + +const PG_LIST_ACTIVE_RES_SQL = `SELECT lease_token, platform, account_key, session_id, vm_id, reserved_at, expires_at +FROM vm_daily_session_reservations +WHERE platform = $1 AND expires_at > $2` + +const PG_ADVISORY_LOCK_SQL = 'SELECT pg_advisory_xact_lock(hashtext($1), hashtext($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) +} + +function withSqliteImmediateTx(db, fn) { + if (db.isTransaction) { + const sp = 'sp_dsg_atomic' + db.exec(`SAVEPOINT ${sp}`) + try { + const out = fn() + db.exec(`RELEASE SAVEPOINT ${sp}`) + return out + } catch (err) { + try { + db.exec(`ROLLBACK TO SAVEPOINT ${sp}`) + db.exec(`RELEASE SAVEPOINT ${sp}`) + } catch {} + throw err + } + } + db.exec('BEGIN IMMEDIATE') + try { + const out = fn() + db.exec('COMMIT') + return out + } catch (err) { + try { + if (db.isTransaction) db.exec('ROLLBACK') + } catch {} + throw err + } +} + +async function withPgAccountTx(pgPool, platform, accountKey, fn) { + if (typeof pgPool?.connect === 'function') { + const client = await pgPool.connect() + try { + await client.query('BEGIN') + await client.query(PG_ADVISORY_LOCK_SQL, [platform, accountKey]) + const out = await fn(client) + await client.query('COMMIT') + return out + } catch (err) { + try { + await client.query('ROLLBACK') + } catch {} + throw err + } finally { + client.release?.() + } + } + // Fallback for lightweight unit-test mock pools that expose only `.query()`. + return fn(pgPool) +} + +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, + } +} + +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 +} + +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 } +} + +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 async function hasCommittedSessionPgAsync(pgPool, platform, accountKey, sessionId) { + if (!pgPool || typeof pgPool.query !== 'function') return false + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const sid = cleanText(sessionId) + if (!plat || !acc || !sid) return false + const res = await pgPool.query(PG_HAS_SESSION_SQL, [plat, acc, sid]) + return Boolean(res?.rows?.length) +} + +export async function findCommittedAccountsForSessionPgAsync(pgPool, platform, sessionId) { + if (!pgPool || typeof pgPool.query !== 'function') return [] + const plat = cleanText(platform) + const sid = cleanText(sessionId) + if (!plat || !sid) return [] + const res = await pgPool.query(PG_FIND_ACCOUNTS_FOR_SESSION_SQL, [plat, sid]) + return (res?.rows || []).map((r) => cleanText(r?.account_key)).filter(Boolean) +} + +export async function tryReserveDailySessionPgAsync( + pgPool, + { platform, accountKey, sessionId, vmId, leaseToken, dayStartMs, limit, active, now, expiresAt }, +) { + if (!pgPool || typeof pgPool.query !== 'function') return null + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const sid = cleanText(sessionId) + const tok = cleanText(leaseToken) + if (!plat || !acc || !sid || !tok) return null + + return withPgAccountTx(pgPool, plat, acc, async (q) => { + await q.query(PG_DELETE_EXPIRED_RES_SQL, [plat, acc, now]) + + const committedHit = await q.query(PG_HAS_SESSION_SQL, [plat, acc, sid]) + const usedRow = await q.query(PG_COUNT_USED_SQL, [plat, acc, dayStartMs]) + const pendingRow = await q.query(PG_COUNT_PENDING_SQL, [plat, acc, now, dayStartMs]) + const used = Number(usedRow?.rows?.[0]?.c || 0) + const pending = Number(pendingRow?.rows?.[0]?.c || 0) + + if (committedHit?.rows?.length) { + return { ok: true, alreadyCommitted: true, reserved: false, duplicate: true, used, pending } + } + + const pendingHit = await q.query(PG_HAS_PENDING_SESSION_SQL, [plat, acc, sid, now]) + const alreadyPending = Boolean(pendingHit?.rows?.length) + + if (!alreadyPending && active && limit > 0 && used + pending >= limit) { + return { ok: false, alreadyCommitted: false, reserved: false, duplicate: false, used, pending } + } + + await q.query(PG_UPSERT_RESERVATION_SQL, [tok, plat, acc, sid, cleanText(vmId) || acc, now, expiresAt]) + return { + ok: true, + alreadyCommitted: false, + reserved: !alreadyPending, + duplicate: alreadyPending, + used, + pending: alreadyPending ? pending : pending + 1, + } + }) +} + +export async function commitDailySessionPgAsync( + pgPool, + { platform, accountKey, dayKey, sessionId, vmId, leaseToken, dayStartMs, limit, active, now }, +) { + if (!pgPool || typeof pgPool.query !== 'function') return null + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const dKey = cleanText(dayKey) + const sid = cleanText(sessionId) + const vid = cleanText(vmId) || acc + const tok = cleanText(leaseToken) + if (!plat || !acc || !dKey || !sid) return null + + // Simple mock pools (unit tests with only `.query` and no `.connect`) may only mock INSERT/SELECT + // on `vm_daily_session_creations`; handle full atomic transaction when `.connect` is present. + if (typeof pgPool.connect !== 'function') { + const res = await pgPool.query(PG_INSERT_SQL, [plat, acc, dKey, sid, vid, now]) + const inserted = Number(res?.rowCount || 0) > 0 + return { recorded: inserted, duplicate: !inserted, rejected: false, persisted: true, used: null, pending: null } + } + + return withPgAccountTx(pgPool, plat, acc, async (q) => { + await q.query(PG_DELETE_EXPIRED_RES_SQL, [plat, acc, now]) + if (tok) await q.query(PG_DELETE_RES_BY_TOKEN_SQL, [tok]) + + const committedHit = await q.query(PG_HAS_SESSION_SQL, [plat, acc, sid]) + const usedRow = await q.query(PG_COUNT_USED_SQL, [plat, acc, dayStartMs]) + const otherPendingRow = await q.query(PG_COUNT_OTHER_PENDING_SQL, [plat, acc, now, sid, dayStartMs]) + const used = Number(usedRow?.rows?.[0]?.c || 0) + const otherPending = Number(otherPendingRow?.rows?.[0]?.c || 0) + + if (committedHit?.rows?.length) { + await q.query(PG_DELETE_RES_BY_SESSION_SQL, [plat, acc, sid]) + return { recorded: false, duplicate: true, rejected: false, persisted: true, used, pending: otherPending } + } + + if (active && limit > 0 && used + otherPending >= limit) { + return { + recorded: false, + duplicate: false, + rejected: true, + reason: 'daily_session_limit', + persisted: false, + used, + pending: otherPending, + } + } + + const ins = await q.query(PG_INSERT_SQL, [plat, acc, dKey, sid, vid, now]) + const inserted = Number(ins?.rowCount || 0) > 0 + await q.query(PG_DELETE_RES_BY_SESSION_SQL, [plat, acc, sid]) + return { + recorded: inserted, + duplicate: !inserted, + rejected: false, + persisted: true, + used: used + (inserted ? 1 : 0), + pending: otherPending, + } + }) +} + +export async function releaseDailySessionReservationPgAsync(pgPool, leaseToken) { + if (!pgPool || typeof pgPool.query !== 'function') return false + const tok = cleanText(leaseToken) + if (!tok) return false + const res = await pgPool.query(PG_DELETE_RES_BY_TOKEN_SQL, [tok]) + return Number(res?.rowCount || 0) > 0 +} + +export async function touchDailySessionReservationsPgAsync(pgPool, leaseTokens, expiresAt) { + if (!pgPool || typeof pgPool.query !== 'function') return 0 + const tokens = Array.isArray(leaseTokens) ? leaseTokens.map(cleanText).filter(Boolean) : [] + if (!tokens.length) return 0 + const res = await pgPool.query(PG_TOUCH_RES_SQL, [expiresAt, tokens]) + 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._resetSqliteStatements() + } + + _resetSqliteStatements() { + this._stmtDb = null + this._listSinceStmt = null + this._insertStmt = null + this._pruneStmt = null + this._hasSessionStmt = null + this._findAccountsForSessionStmt = null + this._countUsedStmt = null + this._countPendingStmt = null + this._countOtherPendingStmt = null + this._hasPendingSessionStmt = null + this._upsertResStmt = null + this._deleteExpiredResStmt = null + this._deleteResByTokenStmt = null + this._deleteResBySessionStmt = null + this._touchResStmt = null + this._listActiveResStmt = null + } + + rebind(db, { pgPool } = {}) { + this._explicitDb = db + if (pgPool !== undefined) this._explicitPgPool = pgPool + this._resetSqliteStatements() + } + + _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 + } + + get hasPersistentStore() { + return this.isPgAsyncMode || this._ensureSqliteStatements() !== 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) + this._hasSessionStmt = db.prepare(SQLITE_HAS_SESSION_SQL) + this._findAccountsForSessionStmt = db.prepare(SQLITE_FIND_ACCOUNTS_FOR_SESSION_SQL) + this._countUsedStmt = db.prepare(SQLITE_COUNT_USED_SQL) + this._countPendingStmt = db.prepare(SQLITE_COUNT_PENDING_SQL) + this._countOtherPendingStmt = db.prepare(SQLITE_COUNT_OTHER_PENDING_SQL) + this._hasPendingSessionStmt = db.prepare(SQLITE_HAS_PENDING_SESSION_SQL) + this._upsertResStmt = db.prepare(SQLITE_UPSERT_RESERVATION_SQL) + this._deleteExpiredResStmt = db.prepare(SQLITE_DELETE_EXPIRED_RES_SQL) + this._deleteResByTokenStmt = db.prepare(SQLITE_DELETE_RES_BY_TOKEN_SQL) + this._deleteResBySessionStmt = db.prepare(SQLITE_DELETE_RES_BY_SESSION_SQL) + this._touchResStmt = db.prepare(SQLITE_TOUCH_RES_SQL) + this._listActiveResStmt = db.prepare(SQLITE_LIST_ACTIVE_RES_SQL) + } + return db + } + + _reportError(op, err) { + if (this._onError) { + try { + this._onError(op, err) + return + } catch {} + } + try { + console.warn(`[daily-session-gate-repo] ${op} failed:`, err?.message || err) + } catch {} + } + + 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 listSinceAsync(platform, sinceMs) { + const pgPool = this._resolvePgPool() + if (pgPool) return listDailySessionCreationsSincePgAsync(pgPool, platform, sinceMs) + return this.listSince(platform, sinceMs) + } + + hasCommittedSession(platform, accountKey, sessionId) { + if (this.isPgAsyncMode) return false + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const sid = cleanText(sessionId) + if (!plat || !acc || !sid) return false + const db = this._ensureSqliteStatements() + if (!db) return false + return Boolean(this._hasSessionStmt.get(plat, acc, sid)) + } + + async hasCommittedSessionAsync(platform, accountKey, sessionId) { + const pgPool = this._resolvePgPool() + if (pgPool) return hasCommittedSessionPgAsync(pgPool, platform, accountKey, sessionId) + return this.hasCommittedSession(platform, accountKey, sessionId) + } + + findCommittedAccountsForSession(platform, sessionId) { + if (this.isPgAsyncMode) return [] + const plat = cleanText(platform) + const sid = cleanText(sessionId) + if (!plat || !sid) return [] + const db = this._ensureSqliteStatements() + if (!db) return [] + return this._findAccountsForSessionStmt + .all(plat, sid) + .map((r) => cleanText(r?.account_key)) + .filter(Boolean) + } + + async findCommittedAccountsForSessionAsync(platform, sessionId) { + const pgPool = this._resolvePgPool() + if (pgPool) return findCommittedAccountsForSessionPgAsync(pgPool, platform, sessionId) + return this.findCommittedAccountsForSession(platform, sessionId) + } + + accountCounts(platform, accountKey, dayStartMs, now) { + if (this.isPgAsyncMode) return null + const plat = cleanText(platform) + const acc = cleanText(accountKey) + if (!plat || !acc) return null + const db = this._ensureSqliteStatements() + if (!db) return null + const used = Number(this._countUsedStmt.get(plat, acc, dayStartMs)?.c || 0) + const pending = Number(this._countPendingStmt.get(plat, acc, now, dayStartMs)?.c || 0) + return { used, pending } + } + + tryReserveAtomic({ platform, accountKey, sessionId, vmId, leaseToken, dayStartMs, limit, active, now, expiresAt }) { + if (this.isPgAsyncMode) return null + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const sid = cleanText(sessionId) + const tok = cleanText(leaseToken) + if (!plat || !acc || !sid || !tok) return null + const db = this._ensureSqliteStatements() + if (!db) return null + + return withSqliteImmediateTx(db, () => { + this._deleteExpiredResStmt.run(plat, acc, now) + + const committedHit = Boolean(this._hasSessionStmt.get(plat, acc, sid)) + const used = Number(this._countUsedStmt.get(plat, acc, dayStartMs)?.c || 0) + const pending = Number(this._countPendingStmt.get(plat, acc, now, dayStartMs)?.c || 0) + + if (committedHit) { + return { ok: true, alreadyCommitted: true, reserved: false, duplicate: true, used, pending } + } + + const alreadyPending = Boolean(this._hasPendingSessionStmt.get(plat, acc, sid, now)) + if (!alreadyPending && active && limit > 0 && used + pending >= limit) { + return { ok: false, alreadyCommitted: false, reserved: false, duplicate: false, used, pending } + } + + this._upsertResStmt.run(tok, plat, acc, sid, cleanText(vmId) || acc, now, expiresAt) + return { + ok: true, + alreadyCommitted: false, + reserved: !alreadyPending, + duplicate: alreadyPending, + used, + pending: alreadyPending ? pending : pending + 1, + } + }) + } + + async tryReserveAtomicAsync(params) { + const pgPool = this._resolvePgPool() + if (pgPool) return tryReserveDailySessionPgAsync(pgPool, params) + return this.tryReserveAtomic(params) + } + + commitAtomic({ platform, accountKey, dayKey, sessionId, vmId, leaseToken, dayStartMs, limit, active, now }) { + if (this.isPgAsyncMode) return null + const plat = cleanText(platform) + const acc = cleanText(accountKey) + const dKey = cleanText(dayKey) + const sid = cleanText(sessionId) + const vid = cleanText(vmId) || acc + const tok = cleanText(leaseToken) + if (!plat || !acc || !dKey || !sid) return null + const db = this._ensureSqliteStatements() + if (!db) return null + + return withSqliteImmediateTx(db, () => { + this._deleteExpiredResStmt.run(plat, acc, now) + if (tok) this._deleteResByTokenStmt.run(tok) + + const committedHit = Boolean(this._hasSessionStmt.get(plat, acc, sid)) + const used = Number(this._countUsedStmt.get(plat, acc, dayStartMs)?.c || 0) + const otherPending = Number(this._countOtherPendingStmt.get(plat, acc, now, sid, dayStartMs)?.c || 0) + + if (committedHit) { + this._deleteResBySessionStmt.run(plat, acc, sid) + return { recorded: false, duplicate: true, rejected: false, persisted: true, used, pending: otherPending } + } + + if (active && limit > 0 && used + otherPending >= limit) { + return { + recorded: false, + duplicate: false, + rejected: true, + reason: 'daily_session_limit', + persisted: false, + used, + pending: otherPending, + } + } + + const info = this._insertStmt.run(plat, acc, dKey, sid, vid, now) + const inserted = Number(info?.changes || 0) > 0 + this._deleteResBySessionStmt.run(plat, acc, sid) + return { + recorded: inserted, + duplicate: !inserted, + rejected: false, + persisted: true, + used: used + (inserted ? 1 : 0), + pending: otherPending, + } + }) + } + + async commitAtomicAsync(params) { + const pgPool = this._resolvePgPool() + if (pgPool) return commitDailySessionPgAsync(pgPool, params) + return this.commitAtomic(params) + } + + releaseReservation(leaseToken) { + const tok = cleanText(leaseToken) + if (!tok) return false + const pgPool = this._resolvePgPool() + if (pgPool) { + if (typeof pgPool.connect === 'function') { + releaseDailySessionReservationPgAsync(pgPool, tok).catch((err) => this._reportError('releaseReservation', err)) + } + return true + } + const db = this._ensureSqliteStatements() + if (!db) return false + const info = this._deleteResByTokenStmt.run(tok) + return Number(info?.changes || 0) > 0 + } + + async releaseReservationAsync(leaseToken) { + const tok = cleanText(leaseToken) + if (!tok) return false + const pgPool = this._resolvePgPool() + if (pgPool) { + if (typeof pgPool.connect !== 'function') return false + return releaseDailySessionReservationPgAsync(pgPool, tok) + } + return this.releaseReservation(tok) + } + + touchReservations(leaseTokens, expiresAt) { + const tokens = Array.isArray(leaseTokens) ? leaseTokens.map(cleanText).filter(Boolean) : [] + if (!tokens.length) return 0 + const pgPool = this._resolvePgPool() + if (pgPool) { + if (typeof pgPool.connect === 'function') { + touchDailySessionReservationsPgAsync(pgPool, tokens, expiresAt).catch((err) => + this._reportError('touchReservations', err), + ) + } + return tokens.length + } + const db = this._ensureSqliteStatements() + if (!db) return 0 + return withSqliteImmediateTx(db, () => { + let updated = 0 + for (const tok of tokens) { + const info = this._touchResStmt.run(expiresAt, tok) + updated += Number(info?.changes || 0) + } + return updated + }) + } + + listActiveReservations(platform, now) { + if (this.isPgAsyncMode) return [] + const plat = cleanText(platform) + if (!plat) return [] + const db = this._ensureSqliteStatements() + if (!db) return [] + return this._listActiveResStmt.all(plat, now) + } + + async listActiveReservationsAsync(platform, now) { + const pgPool = this._resolvePgPool() + if (pgPool) { + if (typeof pgPool.connect !== 'function') return [] + const res = await pgPool.query(PG_LIST_ACTIVE_RES_SQL, [cleanText(platform), now]) + return res?.rows || [] + } + return this.listActiveReservations(platform, now) + } + + /** + * Persist a committed session creation. + * SQLite executes synchronously; PostgreSQL fires non-blocking `pgPool.query` + * and returns the `promise` so callers can observe or handle failures. + */ + recordCreation(record) { + const norm = normalizeDailySessionCreationRecord(record) + if (!norm) return { inserted: false, async: false } + const pgPool = this._resolvePgPool() + if (pgPool) { + const promise = recordDailySessionCreationPgAsync(pgPool, norm).catch((err) => { + this._reportError('recordCreation', err) + throw err + }) + return { inserted: true, async: true, promise } + } + 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 } + } + + 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 } + } + + 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) + } + + 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 fa64a4bbf..ed461e360 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 000000000..7955d57f8 --- /dev/null +++ b/src/lib/pool/daily-session-gate.mjs @@ -0,0 +1,1966 @@ +/** + * 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`) + * - Cross-process atomic reservation & commit + 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 +// 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) + 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`. + * - Global switch `enabled: false`: master off (zero behavior change; per-VM overrides stay dormant). + * - Global switch `enabled: true`: + * - Per-VM `daily_session_limit === 0`: explicit unlimited override (exempts VM). + * - Per-VM `daily_session_limit >= 1`: explicit per-VM cap override. + * - Absent / `null`: inherit global `tier_limits[tier_key]` (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) + if (!gate.enabled) { + return { + enabled: false, + active: false, + limit: 0, + tier_key: tierKey, + source: 'disabled', + } + } + 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: true, + active: limit > 0, + limit, + tier_key: tierKey, + source: 'override', + } + } + 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. + * + * 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_admin_diagnostic) return false + const why = res?.explain?.affinity?.why + if (why === 'session_hit') return false + if (why === 'session_hit_after_wait') 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) +} + +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._onError = typeof options.onError === 'function' ? options.onError : null + this._onHydrated = typeof options.onHydrated === 'function' ? options.onHydrated : null + this._isLeaseActive = typeof options.isLeaseActive === 'function' ? options.isLeaseActive : null + this._repo = + options.repo || + new DailySessionGateRepo({ + db: options.db, + pgPool: options.pgPool, + onError: (op, err) => this._reportError(op, err), + }) + this._retentionMs = Math.max(1, Number(options.retentionDays ?? DEFAULT_RETENTION_DAYS)) * 86_400_000 + this._explicitPendingTtlMs = + options.pendingTtlMs != null && Number.isFinite(Number(options.pendingTtlMs)) + ? Math.max(1_000, Number(options.pendingTtlMs)) + : null + this._dbReservationTtlMs = this._explicitPendingTtlMs ?? DEFAULT_DB_RESERVATION_TTL_MS + this._window = null + /** @type {Map>} accountKey -> Map (current window) */ + this._committed = new Map() + /** @type {Map>} accountKey -> Set (retention window / cross-day) */ + this._committedHistory = new Map() + /** @type {Map boolean) | null }>} */ + this._pending = new Map() + /** @type {Map>>} accountKey -> Map> */ + this._pendingByAccount = new Map() + this._lastPrunedAt = 0 + this._hydrationPromise = null + this._hydrationGen = 0 + this._hydrating = false + this._hydrated = false + 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) { + if (this._onError) { + try { + this._onError(op, err) + return + } catch {} + } + try { + console.warn(`[daily-session-gate] ${op} failed:`, err?.message || err) + } catch {} + } + + getConfig() { + this._syncConfig(Date.now()) + return { + enabled: this._config.enabled, + reset_timezone: this._config.reset_timezone, + tier_limits: { ...this._config.tier_limits }, + } + } + + get isHydrating() { + return this._hydrating + } + + get hydrationError() { + return this._hydrationError + } + + get lastWriteError() { + return this._lastWriteError + } + + whenReady() { + return this._hydrationPromise || Promise.resolve() + } + + async flushPendingWrites() { + if (!this._pendingWrites.size) return { ok: true, failed: 0 } + const settled = await Promise.allSettled([...this._pendingWrites]) + const failed = settled.filter((r) => r.status === 'rejected').length + return { ok: failed === 0, failed } + } + + rebind(db, { pgPool } = {}) { + this._repo?.rebind?.(db, { pgPool }) + this._committed.clear() + this._committedHistory.clear() + this._window = null + this._hydrated = false + this._hydrationError = null + this._hydrating = false + this._hydrationPromise = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + } + + _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 newlyEnabled = !prev.enabled && nextConfig.enabled + const changed = + timezoneChanged || + prev.enabled !== nextConfig.enabled || + DAILY_SESSION_TIERS.some((tier) => prev.tier_limits[tier] !== nextConfig.tier_limits[tier]) + this._config = nextConfig + if (nextConfig.enabled && (newlyEnabled || (timezoneChanged && this._window))) { + this._handleWindowOrEnableTransition(now) + } else if (!nextConfig.enabled && prev.enabled) { + this._hydrating = false + this._hydrationError = null + this._hydrateRetryAttempt = 0 + this._lastHydrateRetryAt = 0 + this._clearHydrateRetryTimer() + } + return { changed, timezoneChanged, newlyEnabled } + } + + 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 (this._hydrationPromise) { + await this._hydrationPromise + } + return res + } + + _startAsyncHydration(ts) { + this._clearHydrateRetryTimer() + const gen = ++this._hydrationGen + this._hydrating = true + const p = this.hydrateAsync(ts) + .then((res) => { + if (this._hydrationGen === gen) { + this._hydrating = false + this._hydrationPromise = null + this._notifyHydrated(res) + } + return res + }) + .catch((err) => { + if (this._hydrationGen === gen) { + this._hydrating = false + this._hydrationPromise = null + this._hydrationError = err + this._scheduleHydrateRecovery(Date.now()) + } + throw err + }) + // Prevent unhandled rejection crashes when callers use sync reloadConfig; + // the error remains recorded in `this._hydrationError` so admission fails closed. + p.catch(() => {}) + this._hydrationPromise = p + return p + } + + _handleWindowOrEnableTransition(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._config.enabled) return + 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) + 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) + } + } + } + + _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._handleWindowOrEnableTransition(ts) + return this._window + } + if (this._window.dayStartMs !== nextWindow.dayStartMs) { + this._window = nextWindow + this._pruneInMemoryCommitted(nextWindow.dayStartMs) + this._rebuildPendingIndex(nextWindow.dayStartMs) + if (this._config.enabled) 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) + } + } + + /** + * Preserve ALL live in-flight reservations across midnight rollovers and timezone switches + * because an in-flight request that commits after midnight will land in the new day window. + */ + _rebuildPendingIndex(dayStartMs) { + this._pendingByAccount.clear() + for (const entry of this._pending.values()) { + 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) + } + + _isEntryLive(entry) { + if (typeof entry?.isActive === 'function') { + try { + return Boolean(entry.isActive()) + } catch { + return true + } + } + if (this._isLeaseActive) { + try { + return Boolean(this._isLeaseActive(entry.leaseToken)) + } catch { + return true + } + } + // Without an explicit TTL override, in-process tracked reservations stay alive until + // explicitly committed or released (never prematurely dropped at 180s while in-flight). + return this._explicitPendingTtlMs === null + } + + _sweepExpiredPending(now) { + if (this._pending.size === 0) return + for (const [token, entry] of this._pending.entries()) { + if (this._isEntryLive(entry)) continue + const ttl = this._explicitPendingTtlMs ?? this._dbReservationTtlMs + if (now - entry.reservedAt >= ttl) { + this._pending.delete(token) + this._unindexPendingEntry(entry) + } + } + } + + /** Renew DB lease expiry for all live in-process reservations so peer instances respect them. */ + heartbeatReservations(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + if (!this._pending.size) return 0 + const liveTokens = [] + for (const [token, entry] of this._pending.entries()) { + if (this._isEntryLive(entry)) liveTokens.push(token) + } + if (!liveTokens.length) return 0 + try { + return this._repo?.touchReservations?.(liveTokens, ts + this._dbReservationTtlMs) || 0 + } catch { + return 0 + } + } + + _syncLiveSqliteReservations(now) { + if (!this._pending.size || this._repo?.isPgAsyncMode) return + if (typeof this._repo?.touchReservations !== 'function') return + const liveTokens = [] + for (const [token, entry] of this._pending.entries()) { + if (this._isEntryLive(entry)) liveTokens.push(token) + } + if (!liveTokens.length) return + try { + this._repo.touchReservations(liveTokens, now + this._dbReservationTtlMs) + } catch {} + } + + _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)) + } + + _isCommittedInHistory(accountKey, sessionId) { + return Boolean( + this._committed.get(accountKey)?.has(sessionId) || this._committedHistory.get(accountKey)?.has(sessionId), + ) + } + + _recordCommittedInMemory(accountKey, sessionId, createdAt, { inWindow = true } = {}) { + let history = this._committedHistory.get(accountKey) + if (!history) { + history = new Set() + this._committedHistory.set(accountKey, history) + } + history.add(sessionId) + if (!inWindow) return false + 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 + } + + _rollbackCommittedInMemory(accountKey, sessionId, { hadInHistory = false } = {}) { + const sessions = this._committed.get(accountKey) + if (sessions) { + sessions.delete(sessionId) + if (sessions.size === 0) this._committed.delete(accountKey) + } + if (!hadInHistory) { + const history = this._committedHistory.get(accountKey) + if (history) { + history.delete(sessionId) + if (history.size === 0) this._committedHistory.delete(accountKey) + } + } + } + + _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 + const inWindow = createdAt >= dayStartMs + if (this._recordCommittedInMemory(accountKey, sessionId, Math.floor(createdAt), { inWindow })) { + loaded += 1 + this._clearPendingSession(accountKey, sessionId) + } + } + return loaded + } + + /** Synchronous startup / re-hydration for SQLite. Skips DB query when disabled. */ + hydrate(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + if (!this._config.enabled) { + 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 + 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) + const rows = this._repo.listSince(this._platform, sinceMs) + const loaded = this._mergeRows(rows, window.dayStartMs) + this._rebuildPendingIndex(window.dayStartMs) + this._hydrated = true + this._hydrationError = null + 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 + } + } + + /** Async startup / re-hydration for PostgreSQL 18 (and SQLite fallback). Skips DB query when disabled. */ + async hydrateAsync(now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + if (!this._config.enabled) { + 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 + 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) + const rows = await this._repo.listSinceAsync(this._platform, sinceMs) + const activeWindow = this._window || window + const loaded = this._mergeRows(rows, activeWindow.dayStartMs) + this._rebuildPendingIndex(activeWindow.dayStartMs) + this._hydrated = true + this._hydrationError = null + 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 + } + } + + _usedCount(accountKey) { + return this._committed.get(accountKey)?.size || 0 + } + + _pendingCount(accountKey) { + return this._pendingByAccount.get(accountKey)?.size || 0 + } + + _effectiveCounts(accountKey, window, now) { + if (!accountKey) return { used: 0, pending: 0 } + if (!this._repo?.isPgAsyncMode && typeof this._repo?.accountCounts === 'function') { + try { + this._syncLiveSqliteReservations(now) + const dbCounts = this._repo.accountCounts(this._platform, accountKey, window.dayStartMs, now) + if (dbCounts) return dbCounts + } catch (err) { + this._reportError('accountCounts', err) + } + } + return { + used: this._usedCount(accountKey), + pending: this._pendingCount(accountKey), + } + } + + _buildStatus(vm, window, { now = Date.now(), countsOverride = null } = {}) { + 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', + } + } + if (!policy.enabled) { + return { + enabled: false, + 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: 'disabled', + } + } + const accountKey = resolveAccountSessionKey(vm) + const { used, pending } = countsOverride || this._effectiveCounts(accountKey, window, now) + const limit = policy.limit + const active = policy.active && limit > 0 + const degraded = active && (this._hydrating || this._hydrationError != null) + const remaining = active ? (degraded ? 0 : Math.max(0, limit - used - pending)) : null + const blocked = active && (degraded || used + pending >= limit) + return { + enabled: policy.enabled, + active, + used, + pending, + limit, + remaining, + blocked, + ...(this._hydrating ? { hydrating: true } : {}), + ...(this._hydrationError ? { degraded: true } : {}), + 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 ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + return this._buildStatus(vm, window, { now: ts }) + } + + isVmNewSessionsBlocked(vm, now = Date.now()) { + return this.statusForVm(vm, now).blocked + } + + /** + * Recognize sessions committed on `vm`'s account either today OR on a prior day + * so cross-day session resumes are allowed even when today's cap is full. + */ + 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) + if (!accountKey) return false + if (this._isCommittedInHistory(accountKey, sid)) return true + if (!this._repo?.isPgAsyncMode && typeof this._repo?.hasCommittedSession === 'function') { + try { + if (this._repo.hasCommittedSession(this._platform, accountKey, sid)) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + return true + } + } catch (err) { + this._reportError('hasCommittedSession', err) + } + } + return false + } + + async hasCommittedSessionAsync(vm, sessionId, now = Date.now()) { + if (!isAnthropicSessionVm(vm)) return false + const sid = String(sessionId || '').trim() + if (!sid) return false + await this.whenReady().catch(() => {}) + this._ensureWindow(now) + const accountKey = resolveAccountSessionKey(vm) + if (!accountKey) return false + if (this._isCommittedInHistory(accountKey, sid)) return true + if (typeof this._repo?.hasCommittedSessionAsync === 'function') { + const hit = await this._repo.hasCommittedSessionAsync(this._platform, accountKey, sid) + if (hit) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + return true + } + } + return false + } + + /** Find all `accountKey`s where `sessionId` was previously committed (any day). */ + async findCommittedAccountsForSessionAsync(sessionId, now = Date.now()) { + const sid = String(sessionId || '').trim() + if (!sid) return [] + if (!this._config.enabled) return [] + await this.whenReady().catch(() => {}) + this._ensureWindow(now) + const accounts = new Set() + for (const [acc, set] of this._committedHistory.entries()) { + if (set.has(sid)) accounts.add(acc) + } + for (const [acc, map] of this._committed.entries()) { + if (map.has(sid)) accounts.add(acc) + } + if (typeof this._repo?.findCommittedAccountsForSessionAsync === 'function') { + try { + const dbAccounts = await this._repo.findCommittedAccountsForSessionAsync(this._platform, sid) + for (const acc of dbAccounts || []) { + accounts.add(acc) + this._recordCommittedInMemory(acc, sid, 0, { inWindow: false }) + } + } catch (err) { + this._reportError('findCommittedAccountsForSessionAsync', err) + } + } + return [...accounts] + } + + canAcceptNewSession(vm, sessionId, now = Date.now()) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + const status = this._buildStatus(vm, window, { now: ts }) + if (!isAnthropicSessionVm(vm) || !status.active) { + return { ok: true, reason: null, status } + } + const sid = String(sessionId || '').trim() + const accountKey = resolveAccountSessionKey(vm) + if (sid && accountKey) { + if (this.hasCommittedSession(vm, sid, ts) || this._pendingByAccount.get(accountKey)?.has(sid)) { + return { ok: true, reason: null, status } + } + } + if (this._hydrating) { + return { ok: false, reason: 'daily_session_gate_hydrating', hydrating: true, status } + } + if (this._hydrationError) { + return { ok: false, reason: 'daily_session_gate_unavailable', error: this._hydrationError, status } + } + if (status.blocked) { + return { ok: false, reason: 'daily_session_limit', status } + } + return { ok: true, reason: null, status } + } + + async canAcceptNewSessionAsync(vm, sessionId, now = Date.now()) { + await this.whenReady().catch(() => {}) + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + if (this._config.enabled && this._hydrationError) { + await this.hydrateAsync(ts).catch(() => {}) + } + if (sessionId && (await this.hasCommittedSessionAsync(vm, sessionId, ts).catch(() => false))) { + return { ok: true, reason: null, status: this.statusForVm(vm, ts) } + } + return this.canAcceptNewSession(vm, sessionId, ts) + } + + /** + * Synchronous check & reserve (atomic via SQLite `BEGIN IMMEDIATE` when SQLite DB is bound). + * - Global disabled (`enabled: false`): strict no-op (zero memory/DB mutations). + * - Cross-day committed session: allowed without consuming today's cap. + * - Hydrating or hydrate-failed (PG): fail closed when active. + */ + tryReserveNewSession({ vm, sessionId, leaseToken, now = Date.now(), isActive = null } = {}) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + const window = this._ensureWindow(ts) + if (!this._config.enabled || !isAnthropicSessionVm(vm)) { + return { + ok: true, + reserved: false, + duplicate: false, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: leaseToken || null, + status: this._buildStatus(vm, window, { now: ts }), + } + } + + 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, { now: ts }), + } + } + + 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, { now: ts }), + } + } + if (existingToken) { + this._pending.delete(token) + this._unindexPendingEntry(existingToken) + } + + const beforeStatus = this._buildStatus(vm, window, { now: ts }) + + // Cross-day or same-day committed session -> never double-count or reject. + if (this.hasCommittedSession(vm, sid, ts)) { + return { + ok: true, + reserved: false, + duplicate: true, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + + if (beforeStatus.active && this._hydrating) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_gate_hydrating', + hydrating: true, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + if (beforeStatus.active && this._hydrationError) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_gate_unavailable', + error: this._hydrationError, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + + // Atomic SQLite cross-process reservation path. + if ( + !this._repo?.isPgAsyncMode && + typeof this._repo?.tryReserveAtomic === 'function' && + this._repo.hasPersistentStore + ) { + this._syncLiveSqliteReservations(ts) + let dbRes + try { + dbRes = this._repo.tryReserveAtomic({ + platform: this._platform, + accountKey, + sessionId: sid, + vmId: String(vm?.id || accountKey), + leaseToken: token, + dayStartMs: window.dayStartMs, + limit: beforeStatus.limit, + active: beforeStatus.active, + now: ts, + expiresAt: ts + this._dbReservationTtlMs, + }) + } catch (err) { + this._reportError('tryReserveAtomic', err) + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_gate_unavailable', + error: err, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + if (dbRes) { + const counts = { used: dbRes.used, pending: dbRes.pending } + const afterStatus = this._buildStatus(vm, window, { now: ts, countsOverride: counts }) + if (dbRes.alreadyCommitted) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + return { + ok: true, + reserved: false, + duplicate: true, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: afterStatus, + } + } + if (!dbRes.ok) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_limit', + newlyCapped: false, + leaseToken: token, + status: afterStatus, + } + } + const entry = { + leaseToken: token, + accountKey, + vmId: String(vm?.id || accountKey), + sessionId: sid, + reservedAt: ts, + dayStartMs: window.dayStartMs, + vm, + isActive: typeof isActive === 'function' ? isActive : null, + } + this._pending.set(token, entry) + this._indexPendingEntry(entry) + return { + ok: true, + reserved: Boolean(dbRes.reserved), + duplicate: Boolean(dbRes.duplicate), + tracked: true, + reason: null, + newlyCapped: !beforeStatus.blocked && afterStatus.blocked, + leaseToken: token, + status: afterStatus, + } + } + } + + // In-memory (no DB bound or PG sync fallback) path. + 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, + isActive: typeof isActive === 'function' ? isActive : null, + } + this._pending.set(token, entry) + this._indexPendingEntry(entry) + + const afterStatus = this._buildStatus(vm, window, { now: ts }) + return { + ok: true, + reserved: !alreadyPending, + duplicate: alreadyPending, + tracked: true, + reason: null, + newlyCapped: !beforeStatus.blocked && afterStatus.blocked, + leaseToken: token, + status: afterStatus, + } + } + + /** + * Async admission & atomic cross-process reservation (preferred on async hot paths & PG 18). + * - Awaits pending timezone/startup hydration (`whenReady()`), eliminating PG hot-switch gaps. + * - Recovers from prior hydrate failure or fails closed if DB remains unreachable. + * - Uses `pg_advisory_xact_lock` in PG mode and `BEGIN IMMEDIATE` in SQLite mode. + */ + async tryReserveNewSessionAsync({ vm, sessionId, leaseToken, now = Date.now(), isActive = null } = {}) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + this._ensureWindow(ts) + if (!this._config.enabled || !isAnthropicSessionVm(vm)) { + return this.tryReserveNewSession({ vm, sessionId, leaseToken, now: ts, isActive }) + } + + // Always wait for any in-flight timezone/startup hydration before admitting. + if (this._hydrationPromise) { + await this._hydrationPromise.catch(() => {}) + } + if (this._hydrationError) { + await this.hydrateAsync(ts).catch(() => {}) + } + + const window = this._ensureWindow(ts) + if (!this._repo?.isPgAsyncMode) { + return this.tryReserveNewSession({ vm, sessionId, leaseToken, now: ts, isActive }) + } + + const accountKey = resolveAccountSessionKey(vm) + const sid = String(sessionId || '').trim() + const token = String(leaseToken || '').trim() || crypto.randomUUID() + if (!accountKey || !sid) { + return { + ok: true, + reserved: false, + duplicate: false, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: this._buildStatus(vm, window, { now: ts }), + } + } + + const beforeStatus = this._buildStatus(vm, window, { now: ts }) + if (beforeStatus.active && this._hydrationError) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_gate_unavailable', + error: this._hydrationError, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + + // Full PG pool with `.connect()`: run cross-process atomic advisory-locked transaction. + const pgPool = this._repo?._resolvePgPool?.() + if (pgPool && typeof pgPool.connect === 'function' && typeof this._repo.tryReserveAtomicAsync === 'function') { + let dbRes + try { + dbRes = await this._repo.tryReserveAtomicAsync({ + platform: this._platform, + accountKey, + sessionId: sid, + vmId: String(vm?.id || accountKey), + leaseToken: token, + dayStartMs: window.dayStartMs, + limit: beforeStatus.limit, + active: beforeStatus.active, + now: ts, + expiresAt: ts + this._dbReservationTtlMs, + }) + } catch (err) { + this._reportError('tryReserveAtomicAsync', err) + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_gate_unavailable', + error: err, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + if (dbRes) { + const afterStatus = this._buildStatus(vm, window, { + now: ts, + countsOverride: { used: dbRes.used, pending: dbRes.pending }, + }) + if (dbRes.alreadyCommitted) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + return { + ok: true, + reserved: false, + duplicate: true, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: afterStatus, + } + } + if (!dbRes.ok) { + return { + ok: false, + reserved: false, + duplicate: false, + tracked: false, + reason: 'daily_session_limit', + newlyCapped: false, + leaseToken: token, + status: afterStatus, + } + } + const entry = { + leaseToken: token, + accountKey, + vmId: String(vm?.id || accountKey), + sessionId: sid, + reservedAt: ts, + dayStartMs: window.dayStartMs, + vm, + isActive: typeof isActive === 'function' ? isActive : null, + } + this._pending.set(token, entry) + this._indexPendingEntry(entry) + return { + ok: true, + reserved: Boolean(dbRes.reserved), + duplicate: Boolean(dbRes.duplicate), + tracked: true, + reason: null, + newlyCapped: !beforeStatus.blocked && afterStatus.blocked, + leaseToken: token, + status: afterStatus, + } + } + } + + // Lightweight PG mock pool (no `.connect()`): hydration already completed above, delegate safely. + if (await this.hasCommittedSessionAsync(vm, sid, ts).catch(() => false)) { + return { + ok: true, + reserved: false, + duplicate: true, + tracked: false, + reason: null, + newlyCapped: false, + leaseToken: token, + status: beforeStatus, + } + } + return this.tryReserveNewSession({ vm, sessionId, leaseToken: token, now: ts, isActive }) + } + + /** + * Commit a reserved (or directly supplied) new primary Anthropic session. + * - Global disabled (`enabled: false`): strict no-op, ZERO DB writes. + * - Re-verifies the cap at commit time so even after an explicit TTL expiry or direct commit, + * `used` cannot exceed `limit`. + * - On PG async mode, surfaces write errors via `onError` + `lastWriteError` and rolls back + * optimistic in-memory dedup so retries persist cleanly instead of silently dropping records. + */ + 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 (!this._config.enabled) { + return { + recorded: false, + duplicate: false, + rejected: false, + persisted: false, + newlyCapped: false, + vmId: targetVm?.id || pendingEntry?.vmId || null, + accountKey: null, + status: targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null, + } + } + + if (targetVm && !isAnthropicSessionVm(targetVm)) { + return { + recorded: false, + duplicate: false, + rejected: false, + persisted: false, + newlyCapped: false, + vmId: targetVm?.id || null, + accountKey: null, + status: this._buildStatus(targetVm, window, { now: ts }), + } + } + + 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, + rejected: false, + persisted: false, + newlyCapped: false, + vmId, + accountKey: accountKey || null, + status: targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null, + } + } + + const beforeStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + const policy = targetVm ? resolveEffectiveDailySessionPolicy(targetVm, this._config) : { active: false, limit: 0 } + + // Atomic SQLite cross-process commit path. + if (!this._repo?.isPgAsyncMode && typeof this._repo?.commitAtomic === 'function' && this._repo.hasPersistentStore) { + this._syncLiveSqliteReservations(ts) + let dbRes + try { + dbRes = this._repo.commitAtomic({ + platform: this._platform, + accountKey, + dayKey: window.dayKey, + sessionId: sid, + vmId: vmId || accountKey, + leaseToken: token, + dayStartMs: window.dayStartMs, + limit: policy.limit, + active: policy.active, + now: ts, + }) + } catch (err) { + this._lastWriteError = err + this._reportError('commitAtomic', err) + return { + recorded: false, + duplicate: false, + rejected: false, + persisted: false, + error: err, + newlyCapped: false, + vmId, + accountKey, + status: beforeStatus, + } + } + if (dbRes) { + const afterStatus = targetVm + ? this._buildStatus(targetVm, window, { + now: ts, + countsOverride: { used: dbRes.used, pending: dbRes.pending }, + }) + : null + if (dbRes.rejected) { + this._clearPendingSession(accountKey, sid) + return { + recorded: false, + duplicate: false, + rejected: true, + reason: dbRes.reason || 'daily_session_limit', + persisted: false, + newlyCapped: false, + vmId, + accountKey, + status: afterStatus, + } + } + if (dbRes.recorded) { + this._recordCommittedInMemory(accountKey, sid, ts, { inWindow: true }) + } else if (dbRes.duplicate) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + } + this._clearPendingSession(accountKey, sid) + return { + recorded: Boolean(dbRes.recorded), + duplicate: Boolean(dbRes.duplicate), + rejected: false, + persisted: Boolean(dbRes.persisted), + newlyCapped: Boolean(beforeStatus && afterStatus && !beforeStatus.blocked && afterStatus.blocked), + vmId, + accountKey, + status: afterStatus, + } + } + } + + // In-memory / PG sync path: check cross-day dedup first. + if (this._isCommittedInHistory(accountKey, sid)) { + this._clearPendingSession(accountKey, sid) + const afterStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + return { + recorded: false, + duplicate: true, + rejected: false, + persisted: true, + newlyCapped: false, + vmId, + accountKey, + status: afterStatus, + } + } + + // Re-check cap excluding this session's own pending tokens. + if (policy.active && policy.limit > 0) { + const used = this._usedCount(accountKey) + let otherPending = 0 + const bySession = this._pendingByAccount.get(accountKey) + if (bySession) { + for (const otherSid of bySession.keys()) { + if (otherSid !== sid) otherPending += 1 + } + } + if (used + otherPending >= policy.limit) { + this._clearPendingSession(accountKey, sid) + const afterStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + return { + recorded: false, + duplicate: false, + rejected: true, + reason: 'daily_session_limit', + persisted: false, + newlyCapped: false, + vmId, + accountKey, + status: afterStatus, + } + } + } + + const hadInHistory = Boolean(this._committedHistory.get(accountKey)?.has(sid)) + const inserted = this._recordCommittedInMemory(accountKey, sid, ts, { inWindow: true }) + let pendingWrite = null + if (inserted) { + this._clearPendingSession(accountKey, sid) + if (this._repo?.isPgAsyncMode && typeof this._repo.commitAtomicAsync === 'function') { + const writeP = this._repo + .commitAtomicAsync({ + platform: this._platform, + accountKey, + dayKey: window.dayKey, + sessionId: sid, + vmId: vmId || accountKey, + leaseToken: token, + dayStartMs: window.dayStartMs, + limit: policy.limit, + active: policy.active, + now: ts, + }) + .then((res) => { + if (res?.rejected) { + this._rollbackCommittedInMemory(accountKey, sid, { hadInHistory }) + } + return res + }) + .catch((err) => { + this._lastWriteError = err + this._rollbackCommittedInMemory(accountKey, sid, { hadInHistory }) + this._reportError('commitReservation', err) + throw err + }) + .finally(() => { + this._pendingWrites.delete(writeP) + }) + // Attach a passive handler so callers who do not inspect `pendingWrite` + // do not crash Node with UnhandledPromiseRejection, while `pendingWrite` + // itself still rejects if awaited explicitly. + writeP.catch(() => {}) + this._pendingWrites.add(writeP) + pendingWrite = writeP + } else if (typeof this._repo?.recordCreation === 'function') { + try { + this._repo.recordCreation({ + platform: this._platform, + accountKey, + dayKey: window.dayKey, + sessionId: sid, + vmId: vmId || accountKey, + createdAt: ts, + }) + } catch (err) { + this._lastWriteError = err + this._rollbackCommittedInMemory(accountKey, sid, { hadInHistory }) + this._reportError('commitReservation', err) + return { + recorded: false, + duplicate: false, + rejected: false, + persisted: false, + error: err, + newlyCapped: false, + vmId, + accountKey, + status: targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null, + } + } + } + } + + const afterStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + return { + recorded: inserted, + duplicate: !inserted, + rejected: false, + persisted: !pendingWrite, + ...(pendingWrite ? { pendingWrite } : {}), + newlyCapped: Boolean(beforeStatus && afterStatus && !beforeStatus.blocked && afterStatus.blocked), + vmId, + accountKey, + status: afterStatus, + } + } + + /** + * Async durable commit (used by `schedulerRuntime.commitLease` and PG 18 callers). + * Awaits PG durability before marking in-memory dedup; DB errors return `{ recorded: false, persisted: false, error }` + * instead of silently swallowing and losing the count across restarts. + */ + async commitReservationAsync(leaseToken, { vm = null, sessionId = null, now = Date.now() } = {}) { + const ts = Number.isFinite(Number(now)) ? Math.floor(Number(now)) : Date.now() + if (!this._config.enabled) { + return this.commitReservation(leaseToken, { vm, sessionId, now: ts }) + } + if (this._hydrationPromise) { + await this._hydrationPromise.catch(() => {}) + } + if (!this._repo?.isPgAsyncMode) { + return this.commitReservation(leaseToken, { vm, sessionId, now: ts }) + } + + 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, + rejected: false, + persisted: false, + newlyCapped: false, + vmId: targetVm?.id || null, + accountKey: null, + status: this._buildStatus(targetVm, window, { now: ts }), + } + } + + 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, + rejected: false, + persisted: false, + newlyCapped: false, + vmId, + accountKey: accountKey || null, + status: targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null, + } + } + + const beforeStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + const policy = targetVm ? resolveEffectiveDailySessionPolicy(targetVm, this._config) : { active: false, limit: 0 } + + if (this._isCommittedInHistory(accountKey, sid)) { + this._clearPendingSession(accountKey, sid) + const afterStatus = targetVm ? this._buildStatus(targetVm, window, { now: ts }) : null + return { + recorded: false, + duplicate: true, + rejected: false, + persisted: true, + newlyCapped: false, + vmId, + accountKey, + status: afterStatus, + } + } + + let dbRes + try { + dbRes = await this._repo.commitAtomicAsync({ + platform: this._platform, + accountKey, + dayKey: window.dayKey, + sessionId: sid, + vmId: vmId || accountKey, + leaseToken: token, + dayStartMs: window.dayStartMs, + limit: policy.limit, + active: policy.active, + now: ts, + }) + } catch (err) { + this._lastWriteError = err + this._reportError('commitReservationAsync', err) + return { + recorded: false, + duplicate: false, + rejected: false, + persisted: false, + error: err, + newlyCapped: false, + vmId, + accountKey, + status: beforeStatus, + } + } + + if (dbRes?.rejected) { + this._clearPendingSession(accountKey, sid) + const afterStatus = targetVm + ? this._buildStatus(targetVm, window, { + now: ts, + countsOverride: dbRes.used != null ? { used: dbRes.used, pending: dbRes.pending ?? 0 } : null, + }) + : null + return { + recorded: false, + duplicate: false, + rejected: true, + reason: dbRes.reason || 'daily_session_limit', + persisted: false, + newlyCapped: false, + vmId, + accountKey, + status: afterStatus, + } + } + + const recorded = Boolean(dbRes?.recorded) + if (recorded) { + this._recordCommittedInMemory(accountKey, sid, ts, { inWindow: true }) + } else if (dbRes?.duplicate) { + this._recordCommittedInMemory(accountKey, sid, 0, { inWindow: false }) + } + this._clearPendingSession(accountKey, sid) + + const afterStatus = targetVm + ? this._buildStatus(targetVm, window, { + now: ts, + countsOverride: dbRes?.used != null ? { used: dbRes.used, pending: dbRes.pending ?? 0 } : null, + }) + : null + return { + recorded, + duplicate: !recorded, + rejected: false, + persisted: true, + 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. */ + _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 && shouldSyncRepoRelease) { + try { + this._repo?.releaseReservation?.(token) + } catch {} + } + return { released: false, uncapped: false, vmId: null, accountKey: null, status: null } + } + const beforeBlocked = entry.vm ? this._buildStatus(entry.vm, window, { now: ts }).blocked : false + this._pending.delete(token) + this._unindexPendingEntry(entry) + 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 { + released: true, + uncapped: Boolean(beforeBlocked && afterStatus && !afterStatus.blocked), + vmId: entry.vmId, + accountKey: entry.accountKey, + status: afterStatus, + } + } + + releaseReservation(leaseToken, now = Date.now()) { + return this._releaseReservationLocal(leaseToken, now, { skipPgFireAndForget: false }) + } + + async releaseReservationAsync(leaseToken, now = Date.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 { + await this._repo.releaseReservationAsync(token) + } catch (err) { + this._reportError('releaseReservationAsync', err) + } + } + return res + } +} + +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 6104846b6..93029906f 100644 --- a/src/lib/pool/failover-runner.mjs +++ b/src/lib/pool/failover-runner.mjs @@ -298,6 +298,9 @@ const TERMINAL_SWITCH_ERROR_CODES = new Set([ 'session_queue_timeout', '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/pool/pool-scheduler.mjs b/src/lib/pool/pool-scheduler.mjs index 3da1ef894..a47561499 100644 --- a/src/lib/pool/pool-scheduler.mjs +++ b/src/lib/pool/pool-scheduler.mjs @@ -27,6 +27,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' @@ -145,6 +146,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 ee46ff00d..1f331161c 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. ] @@ -360,6 +361,7 @@ export function resolveSlotState({ circuit = null, seats = null, sessions = null, + dailySessions = null, now = Date.now(), } = {}) { const textOf = (reason) => stateOfReason(reason)?.text || null @@ -437,5 +439,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 9caca5a3b..f04182ce8 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 9724b9bf7..c5b227d9d 100644 --- a/src/lib/protocol/handle-agent-sessions.mjs +++ b/src/lib/protocol/handle-agent-sessions.mjs @@ -457,13 +457,13 @@ export function createHandleAgentSessions(deps = {}) { const managedKey = req.apiKeyRecord || null if (managedKey) { - const gate = await acquireManagedKey(managedKey) - if (!gate.ok) { + const keyGate = await acquireManagedKey(managedKey) + if (!keyGate.ok) { 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) @@ -476,7 +476,12 @@ export function createHandleAgentSessions(deps = {}) { const clientAbort = bindClientAbort(req, res) let activeLeaseId = null let leaseCommitted = false + let commitLeasePromise = null const releaseActiveLeaseNow = async (payload) => { + if (commitLeasePromise) { + await commitLeasePromise.catch(() => {}) + commitLeasePromise = null + } const lid = activeLeaseId activeLeaseId = null if (!lid) return @@ -611,9 +616,9 @@ export function createHandleAgentSessions(deps = {}) { maxRequestBytes: inboundBodyLimit(routing, cfg?.limits?.max_body_bytes), admitCragInference, onHeaders: (status, upstreamHeaders) => { - if (!leaseCommitted && activeLeaseId) { + if (!leaseCommitted && activeLeaseId && (status || 200) < 400) { leaseCommitted = true - rt.commitLease?.(activeLeaseId).catch(() => {}) + commitLeasePromise = Promise.resolve(rt.commitLease?.(activeLeaseId)).catch(() => {}) } if (streamingHeadersSent || responseClosed(res)) return streamingHeadersSent = true diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index c11f7d939..3887bda36 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -142,6 +142,7 @@ import { finalizeAssembledAssistantHop, mergeAssembledAssistantHop, incompleteAssistantClientError, + retryAfterSeconds, ErrorType, ErrorCode, } from '../core/errors.mjs' @@ -689,6 +690,46 @@ 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 === '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 1d1b2ee7e..4bee88555 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -74,6 +74,7 @@ import { readVmTempPark } from '../oauth/oauth-credentials.mjs' import { buildApiEndpointTelemetryUpdate, endpointMatchesModel, stripPrefix } from '../pool/api-scheduler.mjs' import { isLeftoverQuotaScheduleOff } from '../pool/availability.mjs' import { isCodexSlotParked } from '../pool/codex-slot-pool.mjs' +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' @@ -1122,6 +1123,7 @@ export class SchedulerRuntime { #apiEndpointStore #accountQuota #codexRuntimeStore + #dailySessionGate #poolScheduler #geminiScheduler #geminiSlotPrefs @@ -1167,6 +1169,8 @@ export class SchedulerRuntime { #geminiOwnersInflight = null #unsubAuxInvalidate = null #unsubLocalClearer = null + #dailySessionLeases = new Map() + #dailySessionHeartbeatTimer = null constructor(options = {}) { this.#cfg = options.cfg || {} @@ -1199,6 +1203,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 @@ -1530,6 +1535,144 @@ 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 + } + + #ensureDailySessionHeartbeat() { + if (this.#dailySessionHeartbeatTimer || this.#dailySessionLeases.size === 0) return + this.#dailySessionHeartbeatTimer = setInterval(() => { + if (this.#dailySessionLeases.size === 0) { + this.#stopDailySessionHeartbeat() + return + } + const dailyGate = this.#resolveDailySessionGate() + try { + dailyGate?.heartbeatReservations?.(Date.now()) + } catch {} + }, 60_000) + this.#dailySessionHeartbeatTimer.unref?.() + } + + #stopDailySessionHeartbeat() { + if (this.#dailySessionHeartbeatTimer) { + clearInterval(this.#dailySessionHeartbeatTimer) + this.#dailySessionHeartbeatTimer = null + } + } + + #isClaudeQuotaGuardBlocking(vm, now = Date.now()) { + if (!vm?.id || isCodexVm(vm)) return false + const cache = this.#resolveSnapshotCache() + const schedSnap = + cache?.getSchedulingSnapshotSync?.(() => this.#loadSchedulingSnapshotSync({ vmsHint: [vm] }), { now }) || null + const raw = schedSnap?.byVmId?.get?.(vm.id) || this.#rawVm(vm) || vm + const accountId = + schedSnap?.accountIdByVmId?.get?.(vm.id) || raw?.claude?.account_uuid || raw?.account_uuid || vm.id + const entry = + (accountId ? schedSnap?.byAccountId?.get?.(String(accountId)) : null) || + schedSnap?.byAccountVmId?.get?.(vm.id) || + null + const account = entry?.account || rawAccountForVm(this.#accountQuota, raw, accountId) || null + if (!account?.unified) return false + return this.#claudeQuotaGuardLevel({ raw, accountId, account, state: entry?.state || null }, 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(() => {}) + } + } + + async #releaseTrackedDailySessionLeaseAsync(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) + if (this.#dailySessionLeases.size === 0) this.#stopDailySessionHeartbeat() + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate && (entry.tracked || entry.reserved)) { + 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) + } + return rel + } + return null + } + + #clearTrackedDailySessionLeases(now = Date.now()) { + this.#stopDailySessionHeartbeat() + 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) @@ -2543,6 +2686,13 @@ export class SchedulerRuntime { } if (schedulable && !codex) { + const dailyGate = this.#resolveDailySessionGate() + if (dailyGate?.hydrationError) { + dailyGate.maybeRetryHydration?.(now) + } + if (dailyGate?.isVmNewSessionsBlocked?.(vm, now)) { + newSessionsBlocked = true + } const reason = claudeQuotaGate({ vm, account: acct, routing, now }) if (reason) { schedulable = false @@ -2942,6 +3092,7 @@ export class SchedulerRuntime { async shutdown({ drain = true, stopProcess = true, timeoutMs = 2_000 } = {}) { this.#stopTelemetryLoop() + this.#clearTrackedDailySessionLeases() this.#started = false try { this.#unsubAuxInvalidate?.() @@ -3550,7 +3701,96 @@ 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 } : {}), + }) + } + + #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_admin_diagnostic) { + 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 + if (this.#isDailySessionUnavailableOnly(statuses)) { + return this.#dailySessionUnavailableError(statuses, err.explain ?? null) + } + return this.#dailySessionLimitError(statuses, err.explain ?? null, now) + } + + #rethrowGated(err, req, dailyRejectedStatuses = []) { if (err instanceof SchedulerApiError && err.code === 'pool_exhausted') { if (fableRequiresMaxFromExhausted(err.explain, req?.[JS_GATE])) { throw fableRequiresMaxError(err.explain) @@ -3559,9 +3799,128 @@ export class SchedulerRuntime { throw quotaGuardTooLargeError(err.explain) } } + const dailyErr = this.#dailySessionExhaustedError(err, req, dailyRejectedStatuses) + if (dailyErr) throw dailyErr throw err } + async #prepareDailySessionContinuingHints(req) { + const dailyGate = this.#resolveDailySessionGate() + if (!dailyGate) return + const cfg = dailyGate.getConfig?.() + if (!cfg?.enabled) return + if (typeof dailyGate.whenReady === 'function') { + await dailyGate.whenReady().catch(() => {}) + } + 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) + if (!committedAccounts?.length) return + const accSet = new Set(committedAccounts) + const keys = new Set(Array.isArray(req.continuing_node_keys) ? req.continuing_node_keys : []) + for (const vm of this.#candidateClaudeVms()) { + if (accSet.has(resolveAccountSessionKey(vm))) { + keys.add(formatNodeKey('claude_vm', vm.id)) + } + } + for (const vm of this.#getVms() || []) { + if (!vm?.id || isCodexVm(vm)) continue + if (accSet.has(resolveAccountSessionKey(vm))) { + keys.add(formatNodeKey('claude_vm', vm.id)) + } + } + if (keys.size) { + req.continuing_node_keys = [...keys] + } + } + + 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 leaseId = res.lease_id + const reserveArgs = { + vm, + sessionId: activeReq.session_id, + leaseToken: leaseId, + now, + isActive: () => this.#dailySessionLeases.has(leaseId), + } + const reserve = + typeof dailyGate.tryReserveNewSessionAsync === 'function' + ? await dailyGate.tryReserveNewSessionAsync(reserveArgs) + : dailyGate.tryReserveNewSession(reserveArgs) + if (reserve.ok) { + if (reserve.tracked || reserve.reserved) { + this.#dailySessionLeases.set(leaseId, { + vm, + nodeKey, + sessionId: activeReq.session_id, + reserved: Boolean(reserve.reserved), + tracked: Boolean(reserve.tracked ?? reserve.reserved), + shouldTrack: true, + }) + this.#ensureDailySessionHeartbeat() + } + if (reserve.newlyCapped) { + this.#notifyDailySessionBlock(vm, nodeKey, true, now) + } + return { res, req: activeReq } + } + await this.releaseLease(leaseId, 'aborted').catch(() => {}) + if (reserve.reason === 'daily_session_gate_unavailable' || reserve.reason === 'daily_session_gate_hydrating') { + throw new SchedulerApiError({ + status: 503, + code: reserve.reason, + 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 } : {}), + }) + } + raceRejectedStatuses.push(reserve.status) + 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)) { + const checked = await this.#ensureGeminiLeaseHasQuota(res, activeReq, requestedEffort, callOpts) + res = checked.res + activeReq = checked.req + } + } + throw this.#dailySessionLimitError(raceRejectedStatuses, res?.explain ?? null, Date.now()) + } + #poolTimeoutsFor(poolId, opts = {}) { const pool = this.#poolsById.get(String(poolId || '')) return { @@ -3578,6 +3937,7 @@ export class SchedulerRuntime { const snapOrPromise = this.#getOrWarmSnapshotForRequest(params) const snapshot = snapOrPromise && typeof snapOrPromise.then === 'function' ? await snapOrPromise : snapOrPromise const req = this.#buildAcquireRequest(params, { snapshot }) + await this.#prepareDailySessionContinuingHints(req) const callOpts = this.#poolTimeoutsFor(req.jev_downgrade_pool_id || req.origin_pool_id, opts) let res try { @@ -3597,11 +3957,15 @@ export class SchedulerRuntime { res = checked.res finalReq = checked.req } - return { ...res, _request: finalReq } + const guarded = await this.#guardDailySessionLease(res, finalReq, 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() + await this.#releaseTrackedDailySessionLeaseAsync(release_lease_id) const rawFailure = params.failure || {} const http_status = Number(rawFailure.http_status ?? rawFailure.httpStatus ?? 0) || 0 const error_class = @@ -3635,6 +3999,7 @@ export class SchedulerRuntime { const snapOrPromise = this.#getOrWarmSnapshotForRequest(nextParams) const snapshot = snapOrPromise && typeof snapOrPromise.then === 'function' ? await snapOrPromise : snapOrPromise const next_attempt = this.#buildAcquireRequest(nextParams, { snapshot }) + await this.#prepareDailySessionContinuingHints(next_attempt) const callOpts = this.#poolTimeoutsFor(next_attempt.jev_downgrade_pool_id || next_attempt.origin_pool_id, opts) let res @@ -3655,7 +4020,10 @@ export class SchedulerRuntime { res = checked.res finalNextAttempt = checked.req } - return { ...res, _request: finalNextAttempt } + const guarded = await this.#guardDailySessionLease(res, finalNextAttempt, callOpts, { + requestedEffort: rawNext.requestedEffort ?? rawNext.requested_effort, + }) + return { ...guarded.res, _request: guarded.req } } switchLease(params = {}, opts = {}) { @@ -3666,7 +4034,58 @@ export class SchedulerRuntime { 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 } this.invalidateLiveSnapshot() - return this.#client.commit(id, opts) + // Claim the daily-session reservation BEFORE awaiting IPC so a fast streaming + // finish cannot race releaseLease() ahead of commitReservationAsync(). + const entry = this.#dailySessionLeases.get(id) || null + if (entry) { + this.#dailySessionLeases.delete(id) + if (this.#dailySessionLeases.size === 0) this.#stopDailySessionHeartbeat() + } + let commitRes + try { + commitRes = await this.#client.commit(id, opts) + } catch (err) { + if (entry && (entry.tracked || entry.reserved)) { + const dailyGate = this.#resolveDailySessionGate() + 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, { + vm: entry.vm, + sessionId: entry.sessionId, + now, + }) + : dailyGate.commitReservation(id, { + vm: entry.vm, + sessionId: entry.sessionId, + now, + }) + if (committed?.newlyCapped) { + this.#notifyDailySessionBlock(entry.vm, entry.nodeKey, true, now) + } + } catch {} + } + } + return commitRes } async releaseLease(leaseIdOrPayload, outcomeOrPayload = {}, maybeOpts = {}) { @@ -3710,8 +4129,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() + await this.#releaseTrackedDailySessionLeaseAsync(leaseIdToRelease) const payload = { - lease_id: String(raw.lease_id).trim(), + lease_id: leaseIdToRelease, outcome, ...(parsedStatus != null ? { http_status: parsedStatus } : {}), ...(errorClass ? { error_class: errorClass } : {}), @@ -3736,6 +4157,7 @@ export class SchedulerRuntime { const snapOrPromise = this.#getOrWarmSnapshotForRequest(params) const snapshot = snapOrPromise && typeof snapOrPromise.then === 'function' ? await snapOrPromise : snapOrPromise const req = this.#buildAcquireRequest(params, { snapshot }) + await this.#prepareDailySessionContinuingHints(req) let res try { res = await this.#client.explain(req, opts) @@ -3749,6 +4171,18 @@ export class SchedulerRuntime { if (quotaGuardTooLargeFromExhausted(res.explain, req[JS_GATE])) { return { ...res, error_code: 'quota_guard_request_too_large' } } + const dailyStatuses = this.#dailySessionBlockedStatusesFromExplain(res.explain, req) + if (dailyStatuses.length) { + const dailyErr = this.#isDailySessionUnavailableOnly(dailyStatuses) + ? this.#dailySessionUnavailableError(dailyStatuses, res.explain ?? null) + : this.#dailySessionLimitError(dailyStatuses, res.explain ?? null) + return { + ...res, + error_code: dailyErr.code, + retry_after_sec: dailyErr.retryAfterSec, + message: dailyErr.message, + } + } } return res } diff --git a/src/server.mjs b/src/server.mjs index 0440a1bbc..32c576073 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, formatNodeKey } 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' @@ -335,6 +336,21 @@ async function activateStandby(reason = 'signal') { console.warn(`[standby] ${name} failed`, e?.message || e) } } + if (dailySessionGate?.getConfig?.().enabled) { + 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 }) @@ -552,6 +568,7 @@ let poolScheduler let failoverRunner let groupsRepo let schedulerRuntime = null +let dailySessionGate = null const routingRt = createRoutingRuntime({ get routingConfig() { @@ -575,6 +592,10 @@ const routingRt = createRoutingRuntime({ get accountQuota() { return accountQuota }, + get dailySessionGate() { + return dailySessionGate + }, + getDailySessionGate: () => dailySessionGate, get poolScheduler() { return poolScheduler }, @@ -662,6 +683,28 @@ 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?.(), + onError: (op, err) => console.warn(`[db] daily session gate ${op} failed:`, err?.message || err), + onHydrated: () => { + void schedulerRuntime?.pushTelemetryNow?.().catch(() => {}) + }, +}) +if (dailySessionGate.getConfig().enabled) { + 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, @@ -1072,6 +1115,7 @@ notifyMonitor = createNotifyMonitor({ poolScheduler, proxyPool, requestLog, + dailySessionGate, }), }) @@ -1108,6 +1152,16 @@ backupService.onRestored(async (db) => { stickyRouter.reloadConfig(routingConfig) accountQuota.reloadConfig(routingConfig) accountQuota.loadVmQuotaOverrides(listVms(cfg.paths.project)) + dailySessionGate?.rebind?.(db, { pgPool: getPgPool?.() }) + dailySessionGate?.reloadConfig?.(routingConfig) + if (dailySessionGate?.getConfig?.().enabled) { + try { + if (getDbEngine() === 'postgres' && getPgPool()) await dailySessionGate?.hydrateAsync?.() + else dailySessionGate?.hydrate?.() + } catch (err) { + console.warn('[backup-restore] daily session gate hydration failed:', err?.message || err) + } + } requestLog.setConfig({ mode: process.env.KIN_REQUEST_LOG_MODE || routingConfig.logging?.mode, retainDays: routingConfig.logging?.retain_days, @@ -1126,6 +1180,7 @@ backupService.onRestored(async (db) => { initPoolRuntime() void schedulerRuntime?.syncConfigNow?.('backup_restore').catch(() => {}) + void schedulerRuntime?.pushTelemetryNow?.().catch(() => {}) reloadActiveVm(cfg) vmTestSchedule.reload() try { @@ -1915,6 +1970,7 @@ schedulerRuntime = createSchedulerRuntime({ apiEndpointStore, accountQuota, codexRuntimeStore, + dailySessionGate, poolScheduler: () => poolScheduler, geminiScheduler: () => geminiScheduler, geminiSlotPrefs, @@ -1964,6 +2020,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 a79a185c4..992d4fb21 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 mig077 = fs.readFileSync(path.join(SQLITE_DIR, '077_vm_daily_session_creations.sql'), 'utf8') + const v077 = checkAdditive({ ...sqlite('077_vm_daily_session_creations.sql', mig077), rowCount: () => 0 }) + assert.equal(v077.additive, true, JSON.stringify(v077.reasons)) }) // bg-deploy.sh 的调用方式:脚本经 stdin 交给 node,迁移文件名作参数 diff --git a/test/unit/error-class.test.mjs b/test/unit/error-class.test.mjs index bed8d523c..3d7552912 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 b51d8fe92..6df32442c 100644 --- a/test/unit/errors-map.test.mjs +++ b/test/unit/errors-map.test.mjs @@ -104,6 +104,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 85170cb8a..946a6b8ab 100644 --- a/test/unit/pool-scheduler.test.mjs +++ b/test/unit/pool-scheduler.test.mjs @@ -29,6 +29,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, @@ -684,3 +685,85 @@ 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 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' }, + 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) + assert.equal( + shouldGateSchedulerLease({ ...baseReq, is_ephemeral_probe: true }, claudeRes('ephemeral_follow_session')), + false, + ) + + // 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, 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, + ) + + // 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' }, + claudeRes('tier_ranked'), + ), + false, + ) + 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) + 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 6606001ac..8672c97ff 100644 --- a/test/unit/routing-runtime-load.test.mjs +++ b/test/unit/routing-runtime-load.test.mjs @@ -3,12 +3,14 @@ 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 { mergeCodexRuntimeIntoVm, setActiveCodexRuntimeStore } from '../../src/lib/pool/codex-runtime-store.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 }) @@ -899,6 +901,304 @@ test('persistRoutingPatch merges and normalizes batch_group and loadRoutingConfi } }) +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 = await 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') +}) + test('applyRoutingOpenAIQuota and legacy OpenAI migration read disk VM without persisting CodexRuntimeStore overlay (m2)', () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-routing-codex-overlay-')) const vmsDir = path.join(root, 'vms') diff --git a/test/unit/rust-kernel-health.test.mjs b/test/unit/rust-kernel-health.test.mjs index 11d19f5d6..62d63d337 100644 --- a/test/unit/rust-kernel-health.test.mjs +++ b/test/unit/rust-kernel-health.test.mjs @@ -18,6 +18,8 @@ import { createHandleAgentSessions, deriveScopedKernelSessionId, } 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' import { createSchedulerRuntime } from '../../src/lib/scheduler/scheduler-runtime.mjs' import { createMockSchedulerRuntime } from '../helpers/mock-scheduler-runtime.mjs' @@ -669,11 +671,16 @@ function makeHarness(root, slot, timeoutMs = 1000, extraDeps = {}) { return { logs, billing, - async request(body, signal = null, configureResponse = null) { + 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 }, } @@ -1265,3 +1272,170 @@ test('L2-11: POST /v1/agent/sessions fails closed without Rust scheduler, enforc assert.equal(/\bvmInflight\b/.test(src), false, 'vmInflight read must be removed') assert.equal(/\bstickyRouter\b/.test(src), false, 'Node stickyRouter bypass must be removed') }) + +test('handleAgentSessions + real kin-scheduler + DailySessionGate: pre-header release, cross-day resume, admin pin exemption, acquireManagedKey throw safety, and tenant isolation', async (t) => { + const binPath = resolveSchedulerBin() + assert.ok(binPath, 'kin-scheduler binary must exist for Agent Sessions daily gate test') + const root = temp(t) + const db = createDatabase({ dbPath: path.join(root, 'kin.db') }) + t.after(() => db.close()) + + 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 }) + + 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 realVm = { + id: 'vm-a', + name: 'vm-a', + platform: 'anthropic', + dataplane: 'crag', + status: 'running', + schedulable: true, + shm_profile: 'native_multisession', + policy: { maxConcurrency: 4, concurrencyOverride: true }, + claude: { + account_uuid: 'acc-agent-dsg', + subscription_type: 'pro', + access_token: 'at-a', + refresh_token: 'rt-a', + expires_at: Math.floor(Date.now() / 1000) + 3600, + }, + } + + // Seed a prior-day committed session for tenantA (`old-agent-sess`) to verify cross-day resume (Major 5) + const tenantA = { id: 'key-agent-a', group_type: 'all' } + const tenantB = { id: 'key-agent-b', group_type: 'all' } + const oldKernelSessionId = deriveScopedKernelSessionId('managed:key-agent-a', 'old-agent-sess') + db.prepare( + 'INSERT INTO vm_daily_session_creations (platform, account_key, day_key, session_id, vm_id, created_at) VALUES (?, ?, ?, ?, ?, ?)', + ).run('anthropic', 'acc-agent-dsg', '2026-11-30', oldKernelSessionId, 'vm-a', Date.now() - 30 * 3_600_000) + dailySessionGate.hydrate() + + const routing = { + inference: { engine: 'rust', dataplane: 'crag', crag_kernel_version: 'v2' }, + agent_sessions: { allowed_key_ids: ['key-agent-a', 'key-agent-b'] }, + quota: { daily_session_gate: gateConfig }, + } + + const schedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-dsg-sched-')) + const rt = createSchedulerRuntime({ + cfg: { paths: { data: schedDir, project: schedDir } }, + getDb: () => db, + getVms: () => [realVm], + getRoutingConfig: () => routing, + dailySessionGate, + telemetryIntervalMs: 0, + clientOptions: { + binPath, + socketPath: path.join(schedDir, 'run', 'scheduler.sock'), + tokenPath: path.join(schedDir, 'run', 'scheduler.token'), + capFile: path.join(schedDir, 'run', 'scheduler.cap.json'), + manageProcess: true, + }, + }) + t.after(async () => { + try { + await rt.shutdown({ drain: false, stopProcess: true }) + } catch {} + fs.rmSync(schedDir, { recursive: true, force: true }) + }) + await rt.start({ waitMs: 5_000, startLoops: false }) + await rt.syncConfigNow('agent_dsg_init') + await rt.pushTelemetryNow() + + let throwOnAcquireKey = false + const reqBodies = new Map() + const { handleAgentSessions } = createHandleAgentSessions({ + json: writeJsonRes, + readBody: async (req) => reqBodies.get(req), + requireAuth: () => true, + cfg: { paths: { project: root }, limits: { max_body_bytes: 1024 * 1024, upstream_timeout_ms: 5_000 } }, + apiKeyStore: { + acquire: async () => { + if (throwOnAcquireKey) throw new Error('managed_key_store_boom') + return { ok: true } + }, + release: () => {}, + recordUsage: () => {}, + }, + schedulerRuntime: rt, + getRoutingConfig: () => routing, + listVms: () => [realVm], + slotExec: () => ({ vmId: 'vm-a', homeDir: slot.homeDir, vm: { id: 'vm-a', dataplane: 'crag' } }), + dispatchAgentSession: (opts) => dispatchRustAgentSession({ ...opts, checkAdmission: () => null }), + env: {}, + }) + + const send = async (body, { apiKeyRecord = tenantA, apiKeyKind = 'managed', headers = {} } = {}) => { + const req = makeAgentReq({ apiKeyRecord, apiKeyKind, headers }) + reqBodies.set(req, body) + const res = makeAgentRes() + await handleAgentSessions(req, res) + return res + } + + // 1. Major 6: acquireManagedKey() rejection leaks ZERO pending reservations and keeps slot unblocked + throwOnAcquireKey = true + await assert.rejects(() => send({ session_id: 'key-boom', prompt: 'hi' }), /managed_key_store_boom/) + throwOnAcquireKey = false + assert.equal(dailySessionGate.statusForVm(realVm).pending, 0) + assert.equal(dailySessionGate.statusForVm(realVm).blocked, false) + + // 2. Pre-header 500 error releases reservation without counting + mode = 'fail' + const rFail = await send({ session_id: 'agent-fail-1', prompt: 'hello', stream: false }) + assert.equal(rFail.statusCode, 500) + assert.equal(dailySessionGate.statusForVm(realVm).used, 0) + assert.equal(dailySessionGate.statusForVm(realVm).pending, 0) + + // 3. Streaming 200 commits once and caps slot (1/1) + mode = 'ok' + const rOk = await send({ session_id: 'default', prompt: 'hello from A' }) + assert.equal(rOk.statusCode, 200) + assert.equal(dailySessionGate.statusForVm(realVm).used, 1) + assert.equal(dailySessionGate.statusForVm(realVm).blocked, true) + await rt.pushTelemetryNow() + + // 4. Major 5: Cross-day resume of yesterday's committed session succeeds even when today's cap is full! + const rOld = await send({ session_id: 'old-agent-sess', prompt: 'resume yesterday' }) + assert.equal(rOld.statusCode, 200) + assert.equal(dailySessionGate.statusForVm(realVm).used, 1) + + // 5. Major 10: Admin x-kin-pin-vm bypasses daily limit on Agent Sessions without counting + const rPin = await send( + { session_id: 'admin-diag-sess', prompt: 'diag' }, + { apiKeyRecord: null, apiKeyKind: 'master', headers: { 'x-kin-pin-vm': 'vm-a' } }, + ) + assert.equal(rPin.statusCode, 200) + assert.equal(dailySessionGate.statusForVm(realVm).used, 1) + + // 6. Cross-tenant isolation: Tenant B using the same raw session_id ("default") is rejected with 429 daily_session_limit + const rTenantB = await send({ session_id: 'default', prompt: 'hello from B' }, { apiKeyRecord: tenantB }) + assert.equal(rTenantB.statusCode, 429) + const bBody = JSON.parse(Buffer.concat(rTenantB.chunks).toString('utf8')) + assert.equal(bBody.error?.code, 'daily_session_limit') + assert.ok(Number(rTenantB.headers['retry-after']) >= 1) +}) diff --git a/test/unit/schedule-state.test.mjs b/test/unit/schedule-state.test.mjs index ee618443a..81f7c9e29 100644 --- a/test/unit/schedule-state.test.mjs +++ b/test/unit/schedule-state.test.mjs @@ -114,6 +114,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', () => { @@ -270,6 +276,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 50c629cd8..28486e249 100644 --- a/test/unit/scheduler-m0-migrations.test.mjs +++ b/test/unit/scheduler-m0-migrations.test.mjs @@ -84,6 +84,7 @@ test('SQLite 071 upgrades pre-071 DB cleanly, preserves existing api_keys, and e '074_codex_slot_runtime.sql', '075_scheduler_pool_required_capabilities.sql', '076_optimize_risk_indexes.sql', + '077_vm_daily_session_creations.sql', ]) // Re-applying is idempotent @@ -768,6 +769,7 @@ test('072 SQLite / 009 PG migrations safely repair untouched legacy vm_pools bac '074_codex_slot_runtime.sql', '075_scheduler_pool_required_capabilities.sql', '076_optimize_risk_indexes.sql', + '077_vm_daily_session_creations.sql', ]) const modeOf = (id) => diff --git a/test/unit/scheduler-m3-runtime.test.mjs b/test/unit/scheduler-m3-runtime.test.mjs index 80e27a081..dd07e24c9 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, @@ -1592,6 +1593,633 @@ test('M3 runtime: default Anthropic pool inherits global official policy and sna 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) 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') + 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 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, '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! + 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 (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() + + // 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 + await assert.rejects( + () => + runtime.acquireNode({ + ...baseReq, + sessionId: '550e8400-e29b-41d4-a716-446655440198', + parentSessionId: 'forged-parent-never-existed', + }), + (err) => err instanceof SchedulerApiError && err.status === 429 && err.code === 'daily_session_limit', + ) + + 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) + + // 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) => { + 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('M3 runtime + DailySessionGate: releasing daily reservation preserves active 5h/7d quota guard continuing block, and cross-day resume succeeds after restart', async (t) => { + // Part A (Major 7): active 5h/7d quota guard in `continuing` band must NOT be cleared on daily reservation release + { + const tmp = makeTempDir('vm2api-m3-dsg-qguard-') + const fx = makeFixtureState(tmp) + fx.vms[0].claude = { ...(fx.vms[0].claude || {}), account_uuid: 'acc-qguard-1', subscription_type: 'pro' } + const gateConfig = { enabled: true, reset_timezone: 'UTC', tier_limits: { default: 1, pro: 1 } } + const dailySessionGate = createDailySessionGate({ config: gateConfig, db: fx.db }) + dailySessionGate.hydrate() + + const enqueuedTelemetry = [] + let leaseSeq = 0 + const fakeClient = { + stopped: false, + async acquire() { + leaseSeq += 1 + return { + lease_id: `lease-qg-${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 nowSec = Math.floor(Date.now() / 1000) + const mockAccountQuota = { + repo: { + get(id) { + if (id !== 'acc-qguard-1') return null + return { + account_id: 'acc-qguard-1', + vm_id: 'vm-c1', + unified: { + '5h': { utilization: 0.9, reset: nowSec + 3600 }, + '7d': { utilization: 0.5, reset: nowSec + 86400 }, + }, + } + }, + }, + } + const runtime = createSchedulerRuntime({ + getDb: () => fx.db, + getVms: () => [fx.vms[0]], + getRoutingConfig: () => ({ + quota: { + exhaustion_guard: true, + exhaustion_guard_new_session: 0.85, + exhaustion_guard_stop: 0.98, + daily_session_gate: gateConfig, + }, + }), + accountQuota: mockAccountQuota, + 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 acq = await runtime.acquireNode({ + 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-446655440301', + }) + enqueuedTelemetry.length = 0 + await runtime.releaseLease(acq.lease_id, 'aborted') + const flattened = enqueuedTelemetry.flat() + assert.equal( + flattened.some((u) => u.node_key === 'claude_vm:vm-c1' && u.new_sessions_blocked === false), + false, + 'releasing daily reservation must NOT clear new_sessions_blocked when 5h/7d quota guard is in continuing mode', + ) + } + + // Part B (Major 5): cross-day committed session resumes through real kin-scheduler even when today is capped + { + const tmp = makeTempDir('vm2api-m3-dsg-xday-') + 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 yesterdayMs = Date.now() - 30 * 3_600_000 + const accKey = fx.vms[0].claude?.account_uuid || fx.vms[0].id + fx.db + .prepare( + 'INSERT INTO vm_daily_session_creations (platform, account_key, day_key, session_id, vm_id, created_at) VALUES (?, ?, ?, ?, ?, ?)', + ) + .run('anthropic', accKey, '2026-11-30', '550e8400-e29b-41d4-a716-446655440401', fx.vms[0].id, yesterdayMs) + + const dailySessionGate = createDailySessionGate({ config: gateConfig, db: fx.db }) + dailySessionGate.hydrate() + const runtime = createSchedulerRuntime({ + getDb: () => fx.db, + getVms: () => [fx.vms[0]], + 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, 'xday.sock'), + tokenPath: path.join(tmp, 'xday.token'), + capFile: path.join(tmp, 'xday.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: false }) + const baseReq = { + originPoolId: fx.poolAnth.id, + apiKeyRecord: { ...fx.strictKey, allowed_pool_ids: [fx.poolAnth.id] }, + apiKeyKind: 'managed', + model: 'claude-sonnet-4-6', + protocol: 'anthropic', + } + // Cap today (1/1) with a new session + const todayAcq = await runtime.acquireNode({ ...baseReq, sessionId: '550e8400-e29b-41d4-a716-446655440402' }) + await runtime.commitLease(todayAcq.lease_id) + await runtime.releaseLease(todayAcq.lease_id, 'ok') + await runtime.pushTelemetryNow() + + // Resuming yesterday's session MUST succeed through real Rust scheduler without increasing today's count + const resumeAcq = await runtime.acquireNode({ ...baseReq, sessionId: '550e8400-e29b-41d4-a716-446655440401' }) + assert.equal(resumeAcq.selected_node.node_key, 'claude_vm:vm-c1') + await runtime.commitLease(resumeAcq.lease_id) + await runtime.releaseLease(resumeAcq.lease_id, 'ok') + assert.equal(dailySessionGate.statusForVm(fx.vms[0]).used, 1) + + // A brand-new session is still rejected with 429 daily_session_limit + await assert.rejects( + () => runtime.acquireNode({ ...baseReq, sessionId: '550e8400-e29b-41d4-a716-446655440403' }), + (err) => err instanceof SchedulerApiError && err.status === 429 && err.code === 'daily_session_limit', + ) + } +}) + +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 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', + ) +}) + test('M3 runtime: persisted pool required_runtime_capabilities syncs to Rust Stage 0 admission', async (t) => { const tmp = makeTempDir('vm2api-m3-reqcaps-') const fx = makeFixtureState(tmp) diff --git a/test/unit/sqlite-to-pg-migration.test.mjs b/test/unit/sqlite-to-pg-migration.test.mjs index c88f24d17..70f6e5cba 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/018_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/timezone.test.mjs b/test/unit/timezone.test.mjs index 4359cbf46..35f126cd3 100644 --- a/test/unit/timezone.test.mjs +++ b/test/unit/timezone.test.mjs @@ -1,6 +1,14 @@ import { test } from 'node:test' import assert from 'node:assert/strict' -import { DEFAULT_TIMEZONE, normalizeTimezone, US_TIMEZONES, validTimezone } from '../../src/lib/core/timezone.mjs' +import { + DEFAULT_TIMEZONE, + normalizeTimezone, + US_TIMEZONES, + validTimezone, + zonedDayStartMs, + zonedParts, + zonedWallToMs, +} from '../../src/lib/core/timezone.mjs' test('slot timezone preserves valid IANA zones outside America', () => { for (const timezone of ['Asia/Tokyo', 'Asia/Shanghai', 'Europe/London', 'UTC']) { @@ -40,3 +48,31 @@ test('invalid zones and numeric offsets use the default instead of reaching TZ', assert.equal(normalizeTimezone(timezone), DEFAULT_TIMEZONE) } }) + +test('zonedDayStartMs & zonedWallToMs handle America/Santiago 2026-09-06 skipped-midnight DST cleanly', () => { + // In America/Santiago, 2026-09-06 00:00 does not exist: 03:59:59Z is 2026-09-05 23:59:59 (-04), + // and 04:00:00Z jumps straight to 2026-09-06 01:00:00 (-03). + const beforeJump = Date.parse('2026-09-06T03:30:00.000Z') // local 2026-09-05 23:30 + const sep5Start = zonedDayStartMs(beforeJump, 'America/Santiago', 0) + const sep6Reset = zonedDayStartMs(beforeJump, 'America/Santiago', 1) + assert.equal(sep5Start, Date.parse('2026-09-05T04:00:00.000Z')) + assert.equal(sep6Reset, Date.parse('2026-09-06T04:00:00.000Z')) + assert.ok(sep6Reset > beforeJump, 'reset_at must be strictly in the future before midnight spring-forward') + + const afterJump = Date.parse('2026-09-06T04:30:00.000Z') // local 2026-09-06 01:30 + const sep6Start = zonedDayStartMs(afterJump, 'America/Santiago', 0) + const sep7Start = zonedDayStartMs(afterJump, 'America/Santiago', 1) + assert.equal(sep6Start, Date.parse('2026-09-06T04:00:00.000Z')) + assert.equal(sep7Start, Date.parse('2026-09-07T03:00:00.000Z')) + assert.equal(sep7Start - sep6Start, 23 * 3_600_000) + const startParts = zonedParts(sep6Start, 'America/Santiago') + assert.deepEqual( + { year: startParts.year, month: startParts.month, day: startParts.day }, + { year: 2026, month: 9, day: 6 }, + 'start of 2026-09-06 must stay on local date 2026-09-06, never roll back to 2026-09-05 23:00', + ) + + // Fall-back ambiguous wall time resolves to the earliest occurrence (America/New_York 2026-11-01 01:30) + const fallBack = zonedWallToMs({ year: 2026, month: 11, day: 1, hour: 1, minute: 30 }, 'America/New_York') + assert.equal(fallBack, Date.parse('2026-11-01T05:30:00.000Z')) +}) diff --git a/test/unit/vm-quota-override.test.mjs b/test/unit/vm-quota-override.test.mjs index 781f6bd33..323e6a6d8 100644 --- a/test/unit/vm-quota-override.test.mjs +++ b/test/unit/vm-quota-override.test.mjs @@ -4,7 +4,32 @@ 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, + shouldGateSchedulerLease, + 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 +93,856 @@ 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 -> master off (zero behavior change; per-VM positive overrides stay dormant) + 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: false, + limit: 0, + tier_key: 'max_5x', + source: 'disabled', + }) + // When global gate is enabled, per-VM positive override activates with source='override' + assert.deepEqual(resolveEffectiveDailySessionPolicy(cappedWhileOff, gateOn), { + enabled: true, + 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' } } + // Global disabled -> zero behavior change: skips hydrate and performs zero DB writes + 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) + + const disabledHydrate = gate.hydrate(tEarlyUtc) + assert.equal(disabledHydrate.skipped, true) + const disabledRes = gate.tryReserveNewSession({ vm, sessionId: 's-off', leaseToken: 'lt-off', now: tEarlyUtc }) + assert.equal(disabledRes.tracked, false) + const disabledCommit = gate.commitReservation('lt-off', { vm, sessionId: 's-off', now: tEarlyUtc }) + assert.equal(disabledCommit.recorded, false) + assert.equal(db.prepare('SELECT COUNT(*) AS c FROM vm_daily_session_creations').get().c, 0) + const offStatus = gate.statusForVm(vm, tEarlyUtc + 1000) + assert.equal(offStatus.used, 0) + assert.equal(offStatus.active, false) + assert.equal(offStatus.blocked, false) + + // Enable gate -> records s-early & s-late in UTC, hits 2/2 cap + gate.reloadConfig({ enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, tEarlyUtc) + 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 }) + 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) +}) + +test('DailySessionGate cross-process SQLite & PG cap enforcement prevents over-issuance across two instances', async (t) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-dsg-xproc-')) + 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 vm = { id: 'vm-x', claude: { account_uuid: 'acc-x', subscription_type: 'pro' } } + const config = { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 1 } } + + const gateA = createDailySessionGate({ config, db }) + const gateB = createDailySessionGate({ config, db }) + gateA.hydrate(t0) + gateB.hydrate(t0) + + // Gate A reserves s1 -> Gate B must immediately see shared pending reservation and reject s2 + const rA = gateA.tryReserveNewSession({ vm, sessionId: 's1', leaseToken: 'tok-a', now: t0 }) + assert.equal(rA.ok, true) + const rBWhilePending = gateB.tryReserveNewSession({ vm, sessionId: 's2', leaseToken: 'tok-b', now: t0 + 10 }) + assert.equal(rBWhilePending.ok, false) + assert.equal(rBWhilePending.reason, 'daily_session_limit') + + // Gate A commits s1 -> Gate B still cannot reserve OR directly commit s2 + const cA = gateA.commitReservation('tok-a', { now: t0 + 20 }) + assert.equal(cA.recorded, true) + const rBAfterCommit = gateB.tryReserveNewSession({ vm, sessionId: 's2', leaseToken: 'tok-b2', now: t0 + 30 }) + assert.equal(rBAfterCommit.ok, false) + const cBDirect = gateB.commitReservation('tok-b2', { vm, sessionId: 's2', now: t0 + 40 }) + assert.equal(cBDirect.recorded, false) + assert.equal(cBDirect.rejected, true) + assert.equal(db.prepare('SELECT COUNT(*) AS c FROM vm_daily_session_creations').get().c, 1) + assert.equal(gateB.statusForVm(vm, t0 + 50).used, 1) + assert.equal(gateB.statusForVm(vm, t0 + 50).blocked, true) +}) + +test('DailySessionGate keeps live in-flight reservations past 180s and across midnight, and re-checks cap on commit', (t) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-dsg-inflight-')) + t.after(() => fs.rmSync(tmpDir, { recursive: true, force: true })) + const db = createDatabase({ dbPath: path.join(tmpDir, 'kin.db') }) + t.after(() => db.close()) + + const vm = { id: 'vm-inf', claude: { account_uuid: 'acc-inf', subscription_type: 'pro' } } + const config = { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 1 } } + + // 1. Live in-flight reservation does NOT expire at 180_001ms or 600_001ms + const gate = createDailySessionGate({ config, db }) + const t0 = Date.parse('2026-12-01T10:00:00.000Z') + assert.equal(gate.tryReserveNewSession({ vm, sessionId: 's1', leaseToken: 'tok-1', now: t0 }).ok, true) + assert.equal(gate.tryReserveNewSession({ vm, sessionId: 's2', leaseToken: 'tok-2', now: t0 + 180_001 }).ok, false) + assert.equal(gate.tryReserveNewSession({ vm, sessionId: 's2', leaseToken: 'tok-2', now: t0 + 600_001 }).ok, false) + assert.equal(gate.releaseReservation('tok-1', t0 + 600_010).released, true) + + // 2. Reservation acquired at 23:59:30 stays accounted across midnight (00:00:01) so s2 cannot over-issue + const tPreMidnight = Date.parse('2026-12-01T23:59:30.000Z') + const tPostMidnight = Date.parse('2026-12-02T00:00:01.000Z') + assert.equal( + gate.tryReserveNewSession({ vm, sessionId: 's-mid-1', leaseToken: 'tok-m1', now: tPreMidnight }).ok, + true, + ) + const rMid2 = gate.tryReserveNewSession({ vm, sessionId: 's-mid-2', leaseToken: 'tok-m2', now: tPostMidnight }) + assert.equal(rMid2.ok, false) + assert.equal(rMid2.reason, 'daily_session_limit') + assert.equal(gate.commitReservation('tok-m1', { now: tPostMidnight + 1_000 }).recorded, true) + assert.equal(gate.statusForVm(vm, tPostMidnight + 2_000).used, 1) + + // 3. Even with an explicit short pendingTtlMs, commitReservation re-checks cap and refuses used=2 + const ttlGate = createDailySessionGate({ config, db, pendingTtlMs: 5_000 }) + const tNextDay = Date.parse('2026-12-03T10:00:00.000Z') + assert.equal( + ttlGate.tryReserveNewSession({ vm, sessionId: 's-ttl-1', leaseToken: 'tok-ttl-1', now: tNextDay }).ok, + true, + ) + // After explicit 5s TTL expires, s-ttl-2 takes the slot and commits + assert.equal( + ttlGate.tryReserveNewSession({ vm, sessionId: 's-ttl-2', leaseToken: 'tok-ttl-2', now: tNextDay + 6_000 }).ok, + true, + ) + assert.equal(ttlGate.commitReservation('tok-ttl-2', { now: tNextDay + 6_100 }).recorded, true) + // Late commit from expired tok-ttl-1 must be REJECTED by commit cap re-check + const lateCommit = ttlGate.commitReservation('tok-ttl-1', { vm, sessionId: 's-ttl-1', now: tNextDay + 6_200 }) + assert.equal(lateCommit.recorded, false) + assert.equal(lateCommit.rejected, true) + assert.equal(ttlGate.statusForVm(vm, tNextDay + 6_300).used, 1) +}) + +test('DailySessionGate PG timezone hot-switch blocks admission until async hydrate finishes, and surfaces PG write/hydrate failures', async () => { + const vm = { id: 'vm-pg-tz', claude: { account_uuid: 'acc-pg-tz', subscription_type: 'pro' } } + const tEarly = Date.parse('2026-12-01T10:00:00.000Z') + const tLate = Date.parse('2026-12-01T18:00:00.000Z') + + let releaseHydrate = null + let failInsert = false + let failHydrate = false + const rows = [ + { + platform: 'anthropic', + account_key: 'acc-pg-tz', + day_key: '2026-12-01', + session_id: 's-early', + vm_id: 'vm-pg-tz', + created_at: String(tEarly), + }, + { + platform: 'anthropic', + account_key: 'acc-pg-tz', + day_key: '2026-12-01', + session_id: 's-late', + vm_id: 'vm-pg-tz', + created_at: String(tLate), + }, + ] + const errors = [] + const fakePgPool = { + async query(sql, params) { + const q = String(sql) + if (/^SELECT /i.test(q)) { + if (failHydrate) throw new Error('pg_select_boom') + if (releaseHydrate) { + await new Promise((resolve) => { + const fn = releaseHydrate + releaseHydrate = null + fn(resolve) + }) + } + const since = Number(params[1] || 0) + return { rows: rows.filter((r) => Number(r.created_at) >= since) } + } + if (/^INSERT /i.test(q)) { + if (failInsert) throw new Error('pg_insert_conn_lost') + rows.push({ + platform: params[0], + account_key: params[1], + day_key: params[2], + session_id: params[3], + vm_id: params[4], + created_at: String(params[5]), + }) + return { rows: [], rowCount: 1 } + } + return { rows: [], rowCount: 0 } + }, + } + + const gate = new DailySessionGate({ + config: { enabled: true, reset_timezone: 'Asia/Shanghai', tier_limits: { pro: 2 } }, + pgPool: fakePgPool, + onError: (op, err) => errors.push({ op, msg: err?.message }), + }) + await gate.hydrateAsync(tLate) + assert.equal(gate.statusForVm(vm, tLate).used, 1) + + // Hot-switch timezone Shanghai -> UTC at 18:00Z with delayed PG hydrate + let unblockHydrate = null + releaseHydrate = (resolve) => { + unblockHydrate = resolve + } + gate.reloadConfig({ enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 2 } }, tLate + 1_000) + assert.equal(gate.isHydrating, true) + + // Sync attempt during hydration MUST fail closed (no admission gap!) + const syncDuringHydrate = gate.tryReserveNewSession({ + vm, + sessionId: 's-gap', + leaseToken: 'tok-gap', + now: tLate + 1_100, + }) + assert.equal(syncDuringHydrate.ok, false) + assert.equal(syncDuringHydrate.reason, 'daily_session_gate_hydrating') + + // Async attempt awaits whenReady(), sees hydrated used=2 (s-early + s-late), and rejects with daily_session_limit! + const asyncAttempt = gate.tryReserveNewSessionAsync({ + vm, + sessionId: 's-gap-2', + leaseToken: 'tok-gap-2', + now: tLate + 1_200, + }) + await new Promise((r) => setTimeout(r, 15)) + unblockHydrate?.() + const asyncRes = await asyncAttempt + assert.equal(asyncRes.ok, false) + assert.equal(asyncRes.reason, 'daily_session_limit') + assert.equal(gate.statusForVm(vm, tLate + 1_300).used, 2) + + // PG INSERT failure must NOT silently drop or permanently deduplicate the session + gate.reloadConfig({ enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 3 } }, tLate + 2_000) + failInsert = true + const r3 = await gate.tryReserveNewSessionAsync({ + vm, + sessionId: 's-pg-retry', + leaseToken: 'tok-r3', + now: tLate + 2_100, + }) + assert.equal(r3.ok, true) + const failedCommit = await gate.commitReservationAsync('tok-r3', { vm, sessionId: 's-pg-retry', now: tLate + 2_200 }) + assert.equal(failedCommit.recorded, false) + assert.equal(failedCommit.persisted, false) + assert.ok(failedCommit.error) + assert.ok(errors.some((e) => e.msg === 'pg_insert_conn_lost')) + assert.equal(gate.statusForVm(vm, tLate + 2_300).used, 2, 'failed PG insert must not claim used=3 in memory') + + // Retry after PG recovers persists cleanly! + failInsert = false + const retryCommit = await gate.commitReservationAsync('tok-r3-retry', { + vm, + sessionId: 's-pg-retry', + now: tLate + 2_400, + }) + assert.equal(retryCommit.recorded, true) + assert.equal(retryCommit.persisted, true) + assert.equal(gate.statusForVm(vm, tLate + 2_500).used, 3) + + // Hydrate failure must fail closed rather than silently serving an empty ledger + failHydrate = true + const failingGate = new DailySessionGate({ + config: { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 1 } }, + pgPool: fakePgPool, + onError: (op, err) => errors.push({ op, msg: err?.message }), + }) + await assert.rejects(() => failingGate.hydrateAsync(tLate), /pg_select_boom/) + const deniedOnHydrateFail = await failingGate.tryReserveNewSessionAsync({ + vm, + sessionId: 's-unhyd', + leaseToken: 'tok-u', + now: tLate, + }) + assert.equal(deniedOnHydrateFail.ok, false) + assert.equal(deniedOnHydrateFail.reason, 'daily_session_gate_unavailable') +}) + +test('DailySessionGate cross-day resume & shouldGateSchedulerLease parent_session_id security guard', (t) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-dsg-xday-')) + t.after(() => fs.rmSync(tmpDir, { recursive: true, force: true })) + const db = createDatabase({ dbPath: path.join(tmpDir, 'kin.db') }) + t.after(() => db.close()) + + const vm = { id: 'vm-xd', claude: { account_uuid: 'acc-xd', subscription_type: 'pro' } } + const config = { enabled: true, reset_timezone: 'UTC', tier_limits: { pro: 1 } } + const day1 = Date.parse('2026-12-01T10:00:00.000Z') + const day2 = Date.parse('2026-12-02T10:00:00.000Z') + + const g1 = createDailySessionGate({ config, db }) + g1.hydrate(day1) + assert.equal(g1.tryReserveNewSession({ vm, sessionId: 'old-session', leaseToken: 'tok-d1', now: day1 }).ok, true) + assert.equal(g1.commitReservation('tok-d1', { now: day1 }).recorded, true) + + // Restart on Day 2 and fill Day 2 cap (1/1) with a new session + const g2 = createDailySessionGate({ config, db }) + g2.hydrate(day2) + assert.equal(g2.tryReserveNewSession({ vm, sessionId: 'day2-session', leaseToken: 'tok-d2', now: day2 }).ok, true) + assert.equal(g2.commitReservation('tok-d2', { now: day2 }).recorded, true) + assert.equal(g2.statusForVm(vm, day2 + 100).blocked, true) + + // Resuming yesterday's committed session MUST be allowed without consuming today's quota + assert.equal(g2.hasCommittedSession(vm, 'old-session', day2 + 200), true) + assert.equal(g2.canAcceptNewSession(vm, 'old-session', day2 + 200).ok, true) + const resumeRes = g2.tryReserveNewSession({ vm, sessionId: 'old-session', leaseToken: 'tok-resume', now: day2 + 200 }) + assert.equal(resumeRes.ok, true) + assert.equal(resumeRes.reserved, false) + assert.equal(g2.statusForVm(vm, day2 + 300).used, 1) + + // Brand-new session on Day 2 is still blocked + assert.equal(g2.canAcceptNewSession(vm, 'brand-new-day2', day2 + 300).ok, false) + + // 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' }, + { selected_node: { node_type: 'claude_vm' }, explain: { affinity: { why: 'load_balanced' } } }, + ), + true, + 'forged parent_session_id on fresh placement must still be gated', + ) + assert.equal( + shouldGateSchedulerLease( + { 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, + '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) +}) diff --git a/web/src/features/pools/pool-rules.ts b/web/src/features/pools/pool-rules.ts index 641acf6e1..c71360cd4 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 58dd22844..86607a638 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, @@ -490,6 +491,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('今日新会话上限') const customSummary = formatExplainSummary({ prompt_policy: { mode: 'custom', applies: true }, diff --git a/web/src/features/settings/index.tsx b/web/src/features/settings/index.tsx index ff61d7f01..da1b6af75 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 1e76707ce..5b8d80857 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 5fa5c8fec..84c539b5c 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 5de2975bf..6cc76a379 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 ffdacd6ab..b7bb9286c 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 dd29e650c..d6e1db429 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: () => ({}) })) @@ -81,7 +82,7 @@ function withStorage(entries: Record, run: () => T): T { 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)] @@ -1373,6 +1374,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', () => { 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 000000000..c7607d370 --- /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 a514b0b47..e55b10cbe 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, @@ -565,19 +361,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 ? (
@@ -1062,9 +878,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 fa61e8c5a..53cc4650c 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 22687c771..7a98632f5 100644 --- a/web/src/lib/vm-status.ts +++ b/web/src/lib/vm-status.ts @@ -548,8 +548,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 fa993c59a..792bc246a 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 = {