diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index ff2a8c3..99d7693 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -17,11 +17,12 @@ import { saveJson, } from './config.mjs'; -export const QR_LEASE_TTL_MS = 10 * 60 * 1000; -export const QR_LEASE_GRACE_MS = 90 * 1000; +export const QR_LEASE_TTL_MS = 45 * 60 * 1000; +export const QR_LEASE_GRACE_MS = 15 * 60 * 1000; export const QR_LEASE_IDLE_EXPIRY_MS = QR_LEASE_TTL_MS + QR_LEASE_GRACE_MS; -export const QR_LEASE_MAX_AGE_MS = 22 * 60 * 1000; +export const QR_LEASE_MAX_AGE_MS = 90 * 60 * 1000; export const QR_PENDING_COST_TTL_MS = 60 * 1000; +export const QR_CONSUME_LAG_GRACE_MS = 25 * 1000; export const QR_CYCLE_RESET_SHIFT_MS = 30 * 60 * 1000; export const QR_MIN_JUMP_EXCESS_PCT = 0.35; export const QR_COLD_START_JUMP_PCT = 0.45; @@ -29,8 +30,8 @@ export const QR_COLD_START_MAX_COST_USD = 0.25; export const QR_REFUND_EPSILON_PCT = 0.04; export const QR_MIN_DISPLAY_RESERVED_PCT = 0.05; export const QR_IDLE_CONFIRM_REFUND_MS = 5 * 60 * 1000; -export const QR_REFUND_CONFIRM_WINDOW_MS = 90 * 1000; -export const QR_REFUND_CONFIRM_MIN_SAMPLES = 3; +export const QR_REFUND_CONFIRM_WINDOW_MS = 4 * 60 * 1000; +export const QR_REFUND_CONFIRM_MIN_SAMPLES = 4; export const QR_RATE_BOUNCE_COOLDOWN_MS = 60 * 1000; export const QR_RATE_WINDOW_SIZE = 20; export const QR_RATE_OUTLIER_MIN_RATIO = 0.45; @@ -279,6 +280,7 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), pendingCostUsd: 0, pendingCostAtMs: 0, + pendingCostSinceMs: 0, ratePctPerUsd: rate, rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0, rateWindow, @@ -412,6 +414,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastUnpricedCalls: 0, pendingCostUsd: 0, pendingCostAtMs: 0, + pendingCostSinceMs: 0, ratePctPerUsd: null, rateSamples: 0, rateWindow: [], @@ -505,6 +508,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } st.pendingCostUsd = 0; st.pendingCostAtMs = 0; + st.pendingCostSinceMs = 0; st.activeLeases = []; st.pendingDrop = null; const out = qrFormatOutput(st, safeUsed); @@ -552,12 +556,18 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS; const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0); const rate = qrResolveEffectiveRate(st, safeUsed, safeCost); - const expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; - const excessPct = deltaOfficial - expectedDeltaPct; + let expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; + let excessPct = deltaOfficial - expectedDeltaPct; const isIdleRefundReady = poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS; let eventKind = 'idle'; + const clearPendingCost = () => { + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + st.pendingCostSinceMs = 0; + }; + const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { const amt = Math.max(0, Number(refundedPct) || 0); if (amt > 0) { @@ -568,8 +578,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastBounceAtMs = nowMs; st.pendingDrop = null; if (!keepPendingCost) { - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + clearPendingCost(); } if (qrSumLeases(st.activeLeases) < QR_MIN_DISPLAY_RESERVED_PCT) { st.activeLeases = []; @@ -584,10 +593,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu : st.lastOfficialUsedPct; const totalDrop = Math.max(0, prevHigh - safeUsed); st.lastBounceAtMs = nowMs; - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + clearPendingCost(); - if (isIdleRefundReady && st.activeLeases.length > 0) { + if (isIdleRefundReady) { confirmRefund(totalDrop); } else if (st.pendingDrop) { st.pendingDrop.preDropUsedPct = prevHigh; @@ -614,7 +622,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu eventKind = 'drop_pending'; } } else if (st.pendingDrop) { - // 4B-Pending. 当前处于回落观察窗内:判断是「弹回高副本」还是「持续低位确认退还」 + // 4B-Pending. 当前处于回落观察窗内:判断是「弹回高副本」「正常消耗自然越过前高」还是「持续低位确认退还」 const pd = st.pendingDrop; const costSinceDrop = Math.max(0, safeCost - pd.preDropCostUsd); const expectedSinceDrop = rate !== null ? costSinceDrop * rate : 0; @@ -630,8 +638,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop); st.pendingDrop = null; st.lastBounceAtMs = nowMs; - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + clearPendingCost(); if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) { st.activeLeases.push({ amountPct: excessAboveHighWater, @@ -647,6 +654,11 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } else { eventKind = 'replica_flip'; } + } else if (deltaOfficial > 1e-3 && safeUsed >= pd.preDropUsedPct - 1e-3) { + // 正常消耗已自然推高至回落前水位以上,立即解除残留观察窗,防止后续真实租约跳变被吞 + st.pendingDrop = null; + clearPendingCost(); + eventKind = 'normal'; } else { pd.lowSamples += 1; const sustainedLow = @@ -657,18 +669,21 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu if (rawDeltaCost > 0 && deltaOfficial <= 1e-3) { st.pendingCostUsd = effectiveDeltaCost; st.pendingCostAtMs = nowMs; + st.pendingCostSinceMs = + pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs; } const effectiveDrop = Math.max(0, pd.preDropUsedPct + expectedSinceDrop - safeUsed); confirmRefund(effectiveDrop > 0 ? Math.min(pd.dropPct, effectiveDrop) : pd.dropPct, { keepPendingCost: deltaOfficial <= 1e-3 && st.pendingCostUsd > 0, }); } else if (deltaOfficial > 1e-3) { - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + clearPendingCost(); eventKind = 'drop_pending'; } else if (rawDeltaCost > 0) { st.pendingCostUsd = effectiveDeltaCost; st.pendingCostAtMs = nowMs; + st.pendingCostSinceMs = + pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs; eventKind = 'lag_pending'; } } @@ -722,28 +737,57 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } eventKind = 'normal'; } - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + clearPendingCost(); } else if (rawDeltaCost > 0) { - // 4C. 官方已用比例持平但本地产生真实消耗 + // 4C. 官方已用比例持平但本地产生真实消耗:先缓冲短期记账延迟,跨过延迟窗仍持平再扣减租约 + const hasBufferedLeaseCost = st.pendingCostUsd > 0 && st.pendingCostSinceMs > 0; if (st.activeLeases.length > 0) { - // 正在原地消耗已预借租约:按换算率缩减可退差额并刷新租约活跃时刻 - const consumedPct = rate !== null ? rawDeltaCost * rate : 0; - if (consumedPct > 0) { - qrConsumeLeasesFifo(st.activeLeases, consumedPct); + const accCost = rawDeltaCost + (hasBufferedLeaseCost ? st.pendingCostUsd : 0); + const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs; + if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) { + const consumedPct = rate !== null ? accCost * rate : 0; + expectedDeltaPct = consumedPct; + excessPct = deltaOfficial - expectedDeltaPct; + if (consumedPct > 0) { + qrConsumeLeasesFifo(st.activeLeases, consumedPct); + } + for (let i = 0; i < st.activeLeases.length; i += 1) { + st.activeLeases[i].lastTouchedMs = nowMs; + } + clearPendingCost(); + eventKind = 'consume'; + } else { + st.pendingCostUsd = accCost; + st.pendingCostAtMs = nowMs; + st.pendingCostSinceMs = sinceMs; + eventKind = 'lag_pending'; } - for (let i = 0; i < st.activeLeases.length; i += 1) { - st.activeLeases[i].lastTouchedMs = nowMs; - } - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; - eventKind = 'consume'; } else { // 尚未租约:暂存短时待配对成本,吸收 10~30s 记账延迟或小额步长累积 st.pendingCostUsd = effectiveDeltaCost; st.pendingCostAtMs = nowMs; + st.pendingCostSinceMs = + pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs; eventKind = 'lag_pending'; } + } else if ( + st.activeLeases.length > 0 && + st.pendingCostUsd > 0 && + st.pendingCostSinceMs > 0 && + nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS + ) { + // 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化 + const consumedPct = rate !== null ? st.pendingCostUsd * rate : 0; + expectedDeltaPct = consumedPct; + excessPct = deltaOfficial - expectedDeltaPct; + if (consumedPct > 0) { + qrConsumeLeasesFifo(st.activeLeases, consumedPct); + } + for (let i = 0; i < st.activeLeases.length; i += 1) { + st.activeLeases[i].lastTouchedMs = nowMs; + } + clearPendingCost(); + eventKind = 'consume'; } st.lastQuotaTs = safeFetchTs; @@ -751,7 +795,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastCycleCostUsd = safeCost; st.lastUnpricedCalls = safeUnpriced; - // 5. 租约 TTL 超时兜底(租约本身超过 11.5 分钟无实质扣减或满 22 分钟自动清理) + // 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理) const beforePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); if (beforePrune > st.activeLeases.length && eventKind === 'idle') { diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 8c70bb5..9a4bc30 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { + QR_CONSUME_LAG_GRACE_MS, QR_LEASE_IDLE_EXPIRY_MS, QR_REFUND_CONFIRM_WINDOW_MS, createQuotaReservationTracker, @@ -132,9 +133,10 @@ test('quota-reservation: consumes inside active lease and snaps to 0 on partial }); assert.equal(r1.reservedPct, 1.0); - // Follow-up turns spend $0.35 inside the lease while official stays flat at 5.0% + // Follow-up turns spend $0.35 inside the lease while official stays flat at 5.0%: + // first flat tick buffers for reporting-lag grace, follow-up flat poll past grace confirms consume -> 0.6% const t2 = t1 + 30_000; - const r2 = tracker.observeBucket({ + const r2Pending = tracker.observeBucket({ bucketKey: key, officialUsedPct: 5.0, resetTimeMs: RESET_5H, @@ -143,10 +145,22 @@ test('quota-reservation: consumes inside active lease and snaps to 0 on partial poolLastActivityMs: t2, nowMs: t2, }); + assert.equal(r2Pending.reservedPct, 1.0); + + const t2Confirm = t2 + QR_CONSUME_LAG_GRACE_MS + 1_000; + const r2 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t2Confirm, + cycleCostUsd: 4.4, + poolLastActivityMs: t2, + nowMs: t2Confirm, + }); assert.equal(r2.reservedPct, 0.6); // 10 minutes idle: server refunds remaining 0.6% (official drops 5.0% -> 4.4%) - const t3 = t2 + 10 * 60 * 1000; + const t3 = t2Confirm + 10 * 60 * 1000; const r3 = tracker.observeBucket({ bucketKey: key, officialUsedPct: 4.4, @@ -575,12 +589,13 @@ test('quota-reservation: ignores sub-epsilon shortfall noise and drops polluted poolLastActivityMs: t1, nowMs: t1, }); - // Normal steps at ~0.666 %/$ (0.001% below cold-start 0.667) across 12 minutes -> lease expires normally + // Normal steps at ~0.666 %/$ (0.001% below cold-start 0.667) across idle expiry window -> lease expires normally let u = 11.0; let c = 15.0; let now = t1; + const stepMs = Math.ceil((QR_LEASE_IDLE_EXPIRY_MS + 60_000) / 12); for (let i = 0; i < 12; i += 1) { - now += 60_000; + now += stepMs; c += 0.09; u += 0.059; tracker.observeBucket({ @@ -619,6 +634,134 @@ test('quota-reservation: ignores sub-epsilon shortfall noise and drops polluted assert.equal(migSnap.buckets[0].ratePctPerUsd, null, 'polluted v1 rate cleared for clean recalibration'); }); +test('quota-reservation: buffers short reporting lag inside lease, survives 35m residency, and clears recovered pendingDrop', () => { + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::weekly'; + + // Seed baseline at 0.5 %/$ (20% / $40) + let ts = T0; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.0, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.0, + poolLastActivityMs: ts, + nowMs: ts, + }); + + // Trigger +0.8% lease + ts += 10_000; + const rLease = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.8, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.0, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLease.reservedPct, 0.8); + + // Short 8s upstream reporting lag: dCost=$0.20 (exp=0.1%), dUsed=0 -> buffered, then next tick catches up +0.1% + ts += 10_000; + const rLag = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.8, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.2, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLag.reservedPct, 0.8, 'first flat tick does not prematurely drain active lease'); + + ts += 8_000; + const rCatchUp = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.9, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.2, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rCatchUp.reservedPct, 0.8, 'catch-up tick keeps lease intact with zero false consume'); + + // Lease stays alive past 35 minutes idle when official has not refunded yet, then clears on real refund + const lastActTs = ts; + ts += 35 * 60 * 1000; + const rStillHeld = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.9, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.2, + poolLastActivityMs: lastActTs, + nowMs: ts, + }); + assert.equal(rStillHeld.reservedPct, 0.8, 'active lease survives 35m residency before upstream refund'); + + ts += 10 * 60 * 1000; + const rRefund = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 20.1, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 40.2, + poolLastActivityMs: lastActTs, + nowMs: ts, + }); + assert.equal(rRefund.reservedPct, 0); + assert.equal(rRefund.reservedLeaseCount, 0); + + // Small drop (-0.05%) recovered naturally by normal spending clears zombie pendingDrop, + // so a subsequent +1.0% jump is cleanly recognized as a real lease + const key5h = 'local::u@example.com::Gemini::5h'; + let t5 = T0; + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: 20.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t5, + cycleCostUsd: 10.0, + poolLastActivityMs: t5, + nowMs: t5, + }); + t5 += 10_000; + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: 19.95, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t5, + cycleCostUsd: 10.05, + poolLastActivityMs: t5, + nowMs: t5, + }); + t5 += 10_000; + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: 20.05, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t5, + cycleCostUsd: 10.1, + poolLastActivityMs: t5, + nowMs: t5, + }); + t5 += 10_000; + const rNewLease = tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: 21.05, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t5, + cycleCostUsd: 10.1, + poolLastActivityMs: t5, + nowMs: t5, + }); + assert.equal(rNewLease.reservedPct, 1.0, 'real +1.0% lease not swallowed by cleared pendingDrop'); + assert.equal(rNewLease.reservedLeaseCount, 1); +}); + test('experimentalQuotaReservation setting defaults false and round-trips through schema & backup', () => { const def = normalizeFullSettings({}); assert.equal(def.experimentalQuotaReservation, false);