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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion docs/PANEL_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_*`。
Expand All @@ -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 上限
Expand Down Expand Up @@ -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`。
Expand Down
4 changes: 3 additions & 1 deletion scheduler/crates/scheduler-core/src/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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(),
Expand Down
67 changes: 67 additions & 0 deletions scheduler/crates/scheduler-core/tests/admission_affinity_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ fn base_req(
model_gated_node_keys: vec![],
skip_session_gate: false,
session_affinity_first: true,
continuing_node_keys: vec![],
}
}

Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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![],
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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![],
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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![],
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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![],
}
}

Expand Down
4 changes: 4 additions & 0 deletions scheduler/crates/scheduler-proto/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<NodeKey>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down
1 change: 1 addition & 0 deletions scheduler/crates/scheduler-proto/tests/proto_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 2 additions & 0 deletions scripts/migrate-sqlite-to-pg.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
13 changes: 13 additions & 0 deletions scripts/seed-mock-sqlite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 (?, ?, ?, ?, ?)',
Expand Down
2 changes: 2 additions & 0 deletions src/lib/admin/error-class.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down
64 changes: 61 additions & 3 deletions src/lib/admin/panel-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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()`;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -1046,6 +1055,7 @@ export async function buildVmList({
requestLog = null,
clusterNodes = [],
supplierTagStore = null,
dailySessionGate = null,
bypass = false,
} = {}) {
const active = getActiveVmId(cfg.paths.project)
Expand Down Expand Up @@ -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 || []
Expand Down Expand Up @@ -1118,6 +1129,7 @@ export async function buildVmDetail({
slotProcessStatus = readSlotProcessStatus,
clusterNodes = [],
supplierTagStore = null,
dailySessionGate = null,
role = 'admin',
bypass = false,
}) {
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 || {},
Expand Down Expand Up @@ -1978,6 +1994,7 @@ export async function snapshotAccountPool({
poolScheduler = null,
proxyPool = null,
requestLog = null,
dailySessionGate = null,
bypass = false,
}) {
const active = getActiveVmId(cfg.paths.project)
Expand Down Expand Up @@ -2010,6 +2027,7 @@ export async function snapshotAccountPool({
runtimeById,
codexInflightByVmId: codexObs.inflightByVmId,
codexRpmByVmId: codexObs.rpmByVmId,
dailySessionGate,
}),
)
const accounts = snap?.accounts || []
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading