feat(rate-limit): 用户组 × 模型组限额(Group Rate Limit)
Summary (English)
Refactors per-model rate limiting into a User Group x Model Group (Group Rate Limit) two-dimensional model:
- Model Groups: Mutually exclusive groups of models (one model belongs to exactly one group).
- Limit Subjects: User / User Group / Key.
Each (Subject x Model Group) pair supports cost caps across 5h / daily / weekly / monthly / total windows. Multiple sources (personal + user group) merge by taking the maximum value. User group limits are per-capita. Temporary quota boosts are also supported (per User x Model Group x Window, with expiry).
Controlled via ENABLE_MODEL_RATE_LIMIT feature flag (default off). When disabled, behavior is byte-for-byte identical to mainline (new DB columns have defaults, guard bypasses).
Key design decisions:
- Billing isolation: When a model-group rate limit axis (user or key) is hit, consumption on that axis skips and is excluded from mainline global cost gates, tracked via
counted_in_user_global/counted_in_key_globalmarkers. - Resilience: Redis failures trigger fail-open via
MODEL_RATE_LIMIT_FAIL_OPENwithout setting bypass markers (preventing double-release). - Data layer: 5 new tables + 2 enums, 2 new columns on
usage_ledger/message_request, single idempotent migration0105_broad_crystal.sql. - Management: Admin REST API (OpenAPI-synced) + Dashboard UI for model groups, user groups, limits, and quota boosts. Full 5-language i18n.
Scope: 206 files, +32,603 / -3,669 lines. Covers schema, proxy guard pipeline, bucket lease service, admin API, dashboard UI, i18n, and documentation.
概述
将「按模型限额」重构为**用户组 × 模型组限额(Group Rate Limit)**两维度模型:
- 模型组:一组模型,全局互斥归属(一个模型只能属于一个组)。
- 限额主体:用户 / 用户组 / 密钥。
可为每个 (主体 × 模型组) 设置 5h / 每日 / 每周 / 每月 / 总额 的成本上限。多来源(个人行 + 用户组上限)按取最大值合并,用户组限额为人均上限;并支持临时提额授予(按 用户 × 模型组 × 窗口,带有效期,到点即时生效/失效,叠加在有效上限之上)。
通过
ENABLE_MODEL_RATE_LIMIT开关控制,默认关闭;关闭时与主线逐字节一致(新增列均带默认值,guard 直接 bypass)。
主要改动
- 计费完全切分:命中某轴(用户或密钥)模型组限额后,该轴消费既跳过主线全局成本闸门、也不计入该轴主线全局额——通过
usage_ledger/message_request按轴打标counted_in_user_global/counted_in_key_global实现,DB 聚合、Redis 回填、展示分栏三处同源。RPM 与并发护栏始终生效。 - 韧性:Redis 故障时按
MODEL_RATE_LIMIT_FAIL_OPENfail-open,且 fail-open 不置旁路标记,防止双重放行。 - 数据层:schema 新增 5 表 + 2 枚举(
model_groups/model_group_members/model_group_limits/user_groups/quota_boost_grants,boost_window/limit_subject),usage_ledger/message_request各加 2 列打标,system_settings加 OPT-B 模型维度 lease 列。单个净增量迁移0105_broad_crystal.sql(幂等 DDL)。 - 解析/计量:解析快照缓存(SWR + pub/sub 失效)、桶 lease 检查/扣减服务、guard pipeline 接入。
- 管理面:模型组 / 用户组 / 限额 / 提额 Admin REST API(OpenAPI 同步)+ Dashboard 管理界面,覆盖 5 语言 i18n。
Changes
New Files (by area)
Schema & Migration:
drizzle/0105_broad_crystal.sql- Idempotent DDL migration (5 tables, 2 enums, column additions)
Proxy Pipeline:
src/app/v1/_lib/proxy/model-rate-limit-guard.ts- New guard for model group rate limitingsrc/app/v1/_lib/proxy/provider-session-cleanup.ts- Provider session cleanup logic
Admin REST API (OpenAPI-synced):
src/app/api/v1/resources/model-groups/- Model group CRUDsrc/app/api/v1/resources/model-limits/- Model limit CRUDsrc/app/api/v1/resources/quota-boosts/- Quota boost CRUDsrc/app/api/v1/resources/user-groups/- User group CRUDsrc/app/api/v1/resources/me/- Self-service quota extensions
Server Actions:
src/actions/model-group.ts,src/actions/model-limit.ts,src/actions/quota-boost.ts,src/actions/user-group.ts
Dashboard UI:
src/app/[locale]/dashboard/quotas/model-limits/- Model limits management pagessrc/app/[locale]/dashboard/quotas/model-limits/model-groups/- Model group managementsrc/app/[locale]/dashboard/quotas/model-limits/user-groups/- User group managementsrc/app/[locale]/my-usage/_components/model-group-quota-cards.tsx- User-facing quota display
Documentation:
docs/limit/group-rate-limit.md- Feature documentationdocs/limit/README.md- Limit system overviewdocs/api/v1/model-limits.md- API documentation
API Client & Schemas:
src/lib/api-client/v1/actions/- Client-side API actions for all new resourcessrc/lib/api/v1/schemas/- Zod schemas for model-groups, model-limits, quota-boosts
Modified Files (key changes)
src/drizzle/schema.ts(+132) - 5 new tables, 2 new enums, column additionssrc/app/v1/_lib/proxy/guard-pipeline.ts(+71/-6) - Integrated model rate limit guardsrc/app/v1/_lib/proxy/rate-limit-guard.ts(+385/-345) - Refactored for billing isolationsrc/app/v1/_lib/proxy/session.ts(+99) - Extended session contextsrc/app/v1/_lib/proxy/response-handler.ts(+44/-19) - Response handling for model group billingsrc/app/v1/_lib/proxy/forwarder.ts(+7/-2) - Forwarder integrationsrc/instrumentation.ts(+56) - Startup initialization for cache SWRsrc/lib/api/v1/openapi-types.gen.ts(+5567/-1478) - Generated OpenAPI typesmessages/*/quota.json- i18n strings for all 5 languages
Breaking Changes
None. The feature is behind ENABLE_MODEL_RATE_LIMIT (default off). All new DB columns have safe defaults. When disabled, the guard bypasses and behavior is identical to mainline.
Environment Variables
| Variable | Default | Description |
|---|---|---|
ENABLE_MODEL_RATE_LIMIT |
false |
Master switch for group rate limiting |
MODEL_RATE_LIMIT_FAIL_OPEN |
- | Redis failure behavior (fail-open when set) |
测试计划
- [x]
bun run typecheck通过 - [x]
bun run build通过 - [x]
bun run lint(无 error;warning 与基线同量级) - [x]
bun run i18n:audit-messages-no-emoji/i18n:audit-placeholders通过 - [x]
bun run validate:migrations通过(迁移 0105 幂等) - [x] 纯单元测试全绿:模型组 / 用户组 / 限额 / 提额 REST、
bucket-service、完全切分计费等 - [ ]
tests/api/*与集成/E2E 需真实 Redis + Postgres,待在具备数据库的环境补充验证
备注 / Checklist
- [x] 目标分支为
dev - [x] Conventional Commits
- [ ] Docker Build Test(CI 触发)
- 已知后续项:OPT-B 模型维度 lease 百分比(
quotaModelLeasePercent*/quotaModelLeaseMinSliceUsd)当前未配置时回退主线百分比;真实 PG + Redis 的集成/E2E 测试待补。
Description enhanced by Claude AI
Greptile Summary
This PR introduces a two-dimensional User Group × Model Group rate limiting system behind ENABLE_MODEL_RATE_LIMIT (default off). The core design — SWR in-process snapshot, per-axis bypass flags for billing isolation, BucketLeaseService for atomic Redis enforcement, and idempotent DDL migration — is well-architected with thorough test coverage and correct failover/fail-closed semantics.
- Proxy guard pipeline:
modelRateLimitis inserted beforerateLimitvia aglobalThis-backed extension registry; on a clean pass it setsbypassUser/KeyGlobalCostflags so the mainline cost gate is skipped for that axis and model-group spend is excluded from global aggregation viacounted_in_*_globalmarkers. - Billing isolation:
resolveCountedFlagsfreezes per-axis counted flags at settle time; model bucket lease decrements run unconditionally while mainline decrements are skipped for bypassed axes; the all-null-caps edge case (a limit row with every cost window set to null) causes bypass to be set with no enforcement in place, effectively making that subject unlimited. - Schema & API: five new tables with correct indexes and safe DDL defaults; the upsert schema allows rows where all five cost limits are omitted, which can create the all-null bypass condition without a validation error.
Confidence Score: 3/5
Safe to merge only after the all-null-caps bypass is addressed; until then a misconfigured or placeholder limit row silently removes all cost enforcement for the matched subject.
The bypass flag in the guard is set unconditionally for every bucket that passes checkCostLimits, including buckets where every cost window is null (no active limit). A model_group_limits row created with only the required foreign-key fields and no dollar limits — which the upsert schema and DB both permit — causes checkCostLimits to return { allowed: true, failOpen: false }, triggering bypass and removing both the model-group and the mainline global cost gate for the matched user or key. This is a present defect on the changed enforcement path, not a theoretical future concern.
src/app/v1/_lib/proxy/model-rate-limit-guard.ts (bypass loop) and src/lib/api/v1/schemas/model-limits.ts (upsert validation)
Important Files Changed
| Filename | Overview |
|---|---|
| src/app/v1/_lib/proxy/model-rate-limit-guard.ts | New guard step that resolves model-group buckets and sets per-axis bypass flags; contains the all-null-caps bypass bug where a limit row with no configured windows still bypasses the mainline global cost gate. |
| src/lib/api/v1/schemas/model-limits.ts | UpsertSchema allows all five cost fields to be null/omitted with no validation, enabling creation of all-null rows that trigger the bypass bug; a .refine() requiring at least one positive limit would close this. |
| src/lib/model-rate-limit/resolver.ts | Pure snapshot-based resolver implementing MAX-merge across user-group sources; 5h reset metadata inherits from first user-group source rather than the source contributing the maximum cap — documented design trade-off but can surprise admins. |
| src/lib/model-rate-limit/bucket-service.ts | Lease-based cost-window checker and decrementer for model group buckets; correctly guards against $0 misconfiguration; TOTAL_COST_CACHE_TTL tightened to 60s; logic is sound. |
| src/app/v1/_lib/proxy/guard-pipeline.ts | Adds globalThis-backed extension registry and bugfix #03 provider-session cleanup on guard throw; the provider-before-rateLimit reorder is intentional for post-redirect model lookup. |
| src/lib/model-rate-limit/cache.ts | SWR snapshot cache with Redis pub/sub invalidation; startup warm and read-your-writes on admin writes are correctly implemented. |
| src/app/v1/_lib/proxy/rate-limit-guard.ts | All mainline cost-gate checks and lease decrements are now wrapped in bypass-flag guards; billing isolation is correctly wired for all five windows and total. |
| src/app/v1/_lib/proxy/response-handler.ts | counted_in_*_global flags and model bucket lease decrements correctly integrated at billing time; bypass flags conditionally skip both fixed-5h counter writes and mainline lease decrements. |
| drizzle/0105_broad_crystal.sql | Idempotent DDL migration adding 5 tables, 2 enums, 4 new columns, and 9 indexes; all new columns have safe defaults and IF NOT EXISTS guards make it safe to re-run. |
| src/lib/model-rate-limit/backfill.ts | Correctly computes countedInUserGlobal/countedInKeyGlobal as !bypass* and fires model bucket decrements; clean separation from the guard enforcement path. |
Sequence Diagram
sequenceDiagram
participant C as Client
participant GP as GuardPipeline
participant MG as ModelRateLimitGuard
participant BC as BucketCheckService
participant RL as RateLimitGuard
participant FW as Forwarder
participant RH as ResponseHandler
C->>GP: POST /v1/chat
GP->>GP: auth / model / session / provider steps
GP->>MG: execute(session)
MG->>BC: resolveModelLimits(userId, keyId, model)
BC-->>MG: buckets[]
MG->>BC: checkCostLimits(bucket) x N
BC-->>MG: "{allowed, failOpen}"
alt violation
MG-->>GP: throw RateLimitError
GP->>GP: releaseProviderSessionRefs
else "all passed and failOpen=false"
MG->>MG: setBypassUser/KeyGlobalCost(true)
end
GP->>RL: execute(session)
RL->>RL: "skip cost gates where bypass=true"
GP->>FW: forward to upstream
FW-->>RH: response + cost
RH->>RH: resolveCountedFlags(!bypass)
RH->>RH: updateMessageRequest(countedFlags)
par model bucket decrements
RH->>BC: decrementLease(bucket, cost) x N
and mainline decrements non-bypassed axes
RH->>RL: decrementLeaseBudget(axis, cost)
end
RH-->>C: proxied response
Comments Outside Diff (1)
-
src/app/v1/_lib/proxy/guard-pipeline.ts, line 270-280 (link)providerstep now runs beforerateLimit, reversing the original cheap-gate orderIn the original
CHAT_PIPELINE,rateLimitran beforeprovider, so a rate-limited request was rejected with zero provider-selection overhead. The reordering means every rate-limited request now incurs a full provider-selection DB query and a Redis ZADD before failing.bugfix #03correctly cleans up the ZADD, but this adds overhead for the common "quota exhausted" rejection path.Prompt To Fix With AI
This is a comment left during a code review. Path: src/app/v1/_lib/proxy/guard-pipeline.ts Line: 270-280 Comment: **`provider` step now runs before `rateLimit`, reversing the original cheap-gate order** In the original `CHAT_PIPELINE`, `rateLimit` ran before `provider`, so a rate-limited request was rejected with zero provider-selection overhead. The reordering means every rate-limited request now incurs a full provider-selection DB query and a Redis ZADD before failing. `bugfix #03` correctly cleans up the ZADD, but this adds overhead for the common "quota exhausted" rejection path. How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 3
src/app/v1/_lib/proxy/model-rate-limit-guard.ts:183-187
**All-null-caps bucket bypasses mainline global cost gate**
A `model_group_limits` row with every limit column null (a valid, API-accepted state — `UsdLimitSchema` marks all fields optional/nullable) resolves into a bucket whose `checkCostLimits` returns `{ allowed: true, failOpen: false }` because every lease window is skipped and `totalUsage` is never fetched. The loop below then unconditionally sets `bypassUserGlobalCost` / `bypassKeyGlobalCost` to `true`, silently removing the mainline global cost gate with no model-group enforcement in its place. The user becomes truly unlimited: no model-bucket spend is tracked (all `decrementLease` specs are filtered out) and no global gate applies.
The bypass should only be set when the bucket actually has at least one active (non-null, positive) limit window, i.e. add `if (!hasActiveLimit(bucket.caps)) continue;` before the axis-dispatch, where `hasActiveLimit` checks any of the five USD fields is not null/zero.
### Issue 2 of 3
src/lib/model-rate-limit/resolver.ts:96-123
**5h reset metadata taken from first user-group source regardless of which source contributes the effective cap**
`metaSource = indiv ?? ugSources[0]` means `limit5hResetMode` and `limit5hCostResetAt` are always inherited from the individual row (if present) or the first user-group source (by tag iteration order). If a second user-group contributes the higher `limit5hUsd` via `groupMaxForField` but configures a different reset mode (e.g. `"fixed"` vs the first group's `"rolling"`), the merged bucket enforces the maximum dollar cap from Group B but with Group A's `"rolling"` semantics. The admin who configured Group B's `"fixed"` mode cannot predict this outcome, and the effective enforcement diverges from what either group specifies in isolation.
This is an inherent limitation of single-metadata MAX-merge and may be an acceptable trade-off, but it is not currently documented in the user-facing docs or admin UI tooltips.
### Issue 3 of 3
src/lib/api/v1/schemas/model-limits.ts:49-76
**Upsert schema permits all-null limit rows with no validation error**
`UsdLimitSchema` marks every limit field `.optional()` and `.nullable()`. A `POST /api/v1/resources/model-limits` body with only `subjectType`, `subjectId`, and `modelGroupId` (and all five cost fields omitted or `null`) passes Zod validation and creates a row that triggers the all-null-caps bypass bug described on the guard. Adding a `.refine()` that requires at least one non-null, positive cost limit on create/update would prevent such rows from being persisted and would also serve as a clear hint to API consumers.
Reviews (3): Last reviewed commit: "fix(rate-limit): 修复二轮代码审核问题(故障切换/总额缓存/fa..." | Re-trigger Greptile
[!IMPORTANT]
Review skipped
Too many files!
This PR contains 205 files, which is 55 over the limit of 150.
To get a review, narrow the scope: • coderabbit review --type committed # exclude uncommitted changes • coderabbit review --dir
# limit to a subdirectory • coderabbit review --base # compare against a closer base ⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID:
5bbf7719-ec70-4db4-b1fc-10f9bd267277📥 Commits
Reviewing files that changed from the base of the PR and between 52a3f3b2fb360bc82616e306a1dff00c7cddcad1 and 746ec5c6e172323501d8d64802e0dab6f1c46e3b.
📒 Files selected for processing (205)
.env.exampleCHANGELOG.mdCLAUDE.mddocker-compose.local.yamldocs/api/v1/README.mddocs/api/v1/model-limits.mddocs/limit/README.mddocs/limit/group-rate-limit.mddrizzle/0105_broad_crystal.sqldrizzle/meta/0105_snapshot.jsondrizzle/meta/_journal.jsonmessages/en/errors.jsonmessages/en/myUsage.jsonmessages/en/quota.jsonmessages/en/settings/providers/strings.jsonmessages/ja/errors.jsonmessages/ja/myUsage.jsonmessages/ja/quota.jsonmessages/ja/settings/providers/strings.jsonmessages/ru/errors.jsonmessages/ru/myUsage.jsonmessages/ru/quota.jsonmessages/ru/settings/providers/strings.jsonmessages/zh-CN/errors.jsonmessages/zh-CN/myUsage.jsonmessages/zh-CN/quota.jsonmessages/zh-CN/settings/providers/strings.jsonmessages/zh-TW/errors.jsonmessages/zh-TW/myUsage.jsonmessages/zh-TW/quota.jsonmessages/zh-TW/settings/providers/strings.jsonscripts/audit-settings-placeholders.allowlist.jsonsrc/actions/key-quota.tssrc/actions/keys.tssrc/actions/model-group.tssrc/actions/model-limit.tssrc/actions/my-usage.tssrc/actions/quota-boost.tssrc/actions/system-config.tssrc/actions/user-group.tssrc/actions/users.tssrc/app/[locale]/dashboard/_components/user/key-quota-usage-dialog.tsxsrc/app/[locale]/dashboard/_components/user/user-limit-badge.tsxsrc/app/[locale]/dashboard/my-quota/page.tsxsrc/app/[locale]/dashboard/quotas/_components/quota-tabs-nav.tsxsrc/app/[locale]/dashboard/quotas/layout.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/edit-model-limit-dialog.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/model-combobox.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/model-limits-client.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/model-limits-sub-nav.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/quota-boost-dialog.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/quota-boost-panel.tsxsrc/app/[locale]/dashboard/quotas/model-limits/_components/searchable-select.tsxsrc/app/[locale]/dashboard/quotas/model-limits/layout.tsxsrc/app/[locale]/dashboard/quotas/model-limits/model-groups/_components/create-model-group-dialog.tsxsrc/app/[locale]/dashboard/quotas/model-limits/model-groups/_components/manage-members-dialog.tsxsrc/app/[locale]/dashboard/quotas/model-limits/model-groups/_components/model-group-client.tsxsrc/app/[locale]/dashboard/quotas/model-limits/model-groups/_components/model-members-select.tsxsrc/app/[locale]/dashboard/quotas/model-limits/model-groups/page.tsxsrc/app/[locale]/dashboard/quotas/model-limits/page.tsxsrc/app/[locale]/dashboard/quotas/model-limits/user-groups/_components/user-group-client.tsxsrc/app/[locale]/dashboard/quotas/model-limits/user-groups/page.tsxsrc/app/[locale]/my-usage/_components/model-group-quota-cards.tsxsrc/app/[locale]/my-usage/_components/quota-cards.tsxsrc/app/[locale]/my-usage/page.tsxsrc/app/[locale]/settings/providers/_components/provider-manager.tsxsrc/app/[locale]/settings/providers/_components/provider-model-view.tsxsrc/app/api/v1/_root/app.tssrc/app/api/v1/resources/me/handlers.tssrc/app/api/v1/resources/me/router.tssrc/app/api/v1/resources/model-groups/handlers.tssrc/app/api/v1/resources/model-groups/router.tssrc/app/api/v1/resources/model-limits/handlers.tssrc/app/api/v1/resources/model-limits/router.tssrc/app/api/v1/resources/quota-boosts/handlers.tssrc/app/api/v1/resources/quota-boosts/router.tssrc/app/api/v1/resources/user-groups/handlers.tssrc/app/api/v1/resources/user-groups/router.tssrc/app/v1/_lib/proxy-handler.tssrc/app/v1/_lib/proxy/errors.tssrc/app/v1/_lib/proxy/forwarder.tssrc/app/v1/_lib/proxy/guard-pipeline.tssrc/app/v1/_lib/proxy/model-rate-limit-guard.tssrc/app/v1/_lib/proxy/provider-session-cleanup.tssrc/app/v1/_lib/proxy/rate-limit-guard.tssrc/app/v1/_lib/proxy/response-handler.tssrc/app/v1/_lib/proxy/session.tssrc/drizzle/schema.tssrc/instrumentation.tssrc/lib/api-client/v1/actions/model-groups.tssrc/lib/api-client/v1/actions/model-limits.tssrc/lib/api-client/v1/actions/my-usage.tssrc/lib/api-client/v1/actions/quota-boosts.tssrc/lib/api-client/v1/actions/user-groups.tssrc/lib/api-client/v1/openapi-types.gen.tssrc/lib/api/v1/action-migration-matrix.tssrc/lib/api/v1/schemas/model-groups.tssrc/lib/api/v1/schemas/model-limits.tssrc/lib/api/v1/schemas/quota-boosts.tssrc/lib/api/v1/schemas/system-config.tssrc/lib/api/v1/schemas/user-groups.tssrc/lib/api/v1/schemas/users.tssrc/lib/config/system-settings-cache.tssrc/lib/dashboard/user-limit-usage-cache.tssrc/lib/ledger-backfill/trigger.sqlsrc/lib/model-rate-limit/backfill.tssrc/lib/model-rate-limit/boost-cleanup.tssrc/lib/model-rate-limit/bucket-lease.tssrc/lib/model-rate-limit/bucket-service.tssrc/lib/model-rate-limit/cache.tssrc/lib/model-rate-limit/keys.tssrc/lib/model-rate-limit/lease.tssrc/lib/model-rate-limit/register.tssrc/lib/model-rate-limit/resolver.tssrc/lib/model-rate-limit/types.tssrc/lib/notification/tasks/cost-alert.tssrc/lib/quota/limit-usage-split.tssrc/lib/rate-limit/index.tssrc/lib/rate-limit/lease-service.tssrc/lib/rate-limit/lease.tssrc/lib/rate-limit/service.tssrc/lib/redis/cost-cache-cleanup.tssrc/lib/redis/cost-display-cache-singleflight.tssrc/lib/redis/cost-display-cache.tssrc/lib/redis/lua-scripts.tssrc/lib/utils/error-messages.tssrc/lib/validation/schemas.tssrc/lib/webhook/templates/cost-alert.tssrc/lib/webhook/templates/placeholders.tssrc/lib/webhook/types.tssrc/repository/_shared/transformers.test.tssrc/repository/_shared/transformers.tssrc/repository/key.tssrc/repository/message-write-buffer.tssrc/repository/message.tssrc/repository/model-group-limit.tssrc/repository/model-group.tssrc/repository/provider.tssrc/repository/quota-boost.tssrc/repository/statistics.tssrc/repository/system-config.tssrc/repository/user-group.tssrc/types/system-config.tstests/api/v1/model-groups/model-groups.test.tstests/api/v1/model-limits/model-limits.test.tstests/api/v1/quota-boosts/quota-boosts.test.tstests/api/v1/user-groups/user-groups.test.tstests/configs/integration.config.tstests/e2e/_helpers/grl-harness.tstests/e2e/group-rate-limit-scenarios-extra-live.test.tstests/e2e/group-rate-limit-scenarios-live.test.tstests/e2e/model-rate-limit-lease-live.test.tstests/e2e/quota-boosts-live.test.tstests/integration/cost-cache-rolling-flow.test.tstests/integration/model-group-complete-split.test.tstests/integration/usage-ledger.test.tstests/integration/user-5h-reset-flow.test.tstests/unit/actions/key-quota-concurrent-inherit.test.tstests/unit/actions/key-quota-cost-reset.test.tstests/unit/actions/my-usage-user-5h-reset-boundary.test.tstests/unit/actions/total-usage-semantics.test.tstests/unit/actions/user-all-limit-window.test.tstests/unit/api/v1/action-migration-matrix.test.tstests/unit/app/proxy/guard-pipeline-error-cleanup.test.tstests/unit/lib/model-rate-limit/keys.test.tstests/unit/lib/model-rate-limit/lease.test.tstests/unit/lib/model-rate-limit/register.test.tstests/unit/lib/model-rate-limit/types.test.tstests/unit/lib/rate-limit/cache-filter-consistency.test.tstests/unit/lib/rate-limit/cost-limits.test.tstests/unit/lib/rate-limit/failover-bucket-resolve.test.tstests/unit/lib/rate-limit/get-current-cost-batch-parallel.test.tstests/unit/lib/rate-limit/get-current-cost-batch.test.tstests/unit/lib/rate-limit/get-current-cost-rolling.test.tstests/unit/lib/rate-limit/lease-overspend.test.tstests/unit/lib/rate-limit/rolling-boundary-cache.test.tstests/unit/lib/rate-limit/rolling-window-5h.test.tstests/unit/lib/rate-limit/rolling-window-cache-warm.test.tstests/unit/lib/rate-limit/service-extra.test.tstests/unit/lib/rate-limit/user-5h-reset-boundary.test.tstests/unit/lib/redis/cleanup-legacy-rolling-zsets.test.tstests/unit/lib/redis/cost-display-cache-singleflight.test.tstests/unit/lib/redis/cost-display-cache.test.tstests/unit/model-rate-limit/backfill.test.tstests/unit/model-rate-limit/boost-cleanup.test.tstests/unit/model-rate-limit/bucket-lease-service.test.tstests/unit/model-rate-limit/bucket-lease.test.tstests/unit/model-rate-limit/bucket-service.test.tstests/unit/model-rate-limit/cache.test.tstests/unit/model-rate-limit/guard.test.tstests/unit/model-rate-limit/resolver.test.tstests/unit/notification/cost-alert-window.test.tstests/unit/proxy/guard-pipeline-extension.test.tstests/unit/proxy/guard-pipeline-registry-shared.test.tstests/unit/proxy/model-rate-limit-guard.test.tstests/unit/proxy/rate-limit-guard.test.tstests/unit/quota-boost-repository.test.tstests/unit/repository/key-resolve-outcome.test.tstests/unit/repository/model-group.test.tstests/unit/repository/statistics-cost-by-model.test.tstests/unit/repository/sum-provider-cost-batch.test.tstests/unit/repository/system-config-update-missing-columns.test.tstests/unit/repository/user-group.test.tstests/unit/validation/system-settings-quota-lease.test.tstests/unit/webhook/templates/templates.test.tsYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
- [ ] 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
代码审核问题修复说明
已在 0ebebe96 统一处理 Codex / Gemini / Greptile / CI 的审核意见。typecheck / build / lint(无新增 error)/ validate:migrations 均通过,相关单测全绿。
已修复
| # | 来源 | 文件 | 处理 |
|---|---|---|---|
| 1 | Codex P1 | drizzle/0105_broad_crystal.sql |
追加 fn_upsert_usage_ledger 的 CREATE OR REPLACE(镜像 trigger.sql),让 usage_ledger.counted_in_*_global 与 message_request 同源;否则重启后切分计费会被重新计入全局额 |
| 2 | CI HIGH | drizzle/0105_broad_crystal.sql |
ADD COLUMN → IF NOT EXISTS,4 个 ADD CONSTRAINT 包 DO/EXCEPTION;validate:migrations 不再标记 0105 |
| 3 | Gemini HIGH | docker-compose.yaml |
恢复 app 的 postgres 依赖 + DSN 及 AUTO_MIGRATE/ENABLE_RATE_LIMIT/... 环境变量(本地测试配置已分流到 docker-compose.local.yaml),修复容器化开箱即用 |
| 4 | Gemini HIGH | src/repository/model-group.ts |
createSingletonModelGroup 事务内先查冲突,命中即抛 ModelGroupMemberConflictError 回滚,遵守 D6 全局互斥(原 onConflictDoNothing 会静默留下空组) |
| 5 | CI HIGH | src/repository/user-group.ts |
updateUserGroup 对不存在行抛错,符合 Promise<UserGroupRow> 契约 |
| 6 | Codex P2 | src/actions/quota-boost.ts |
create/delete 后调用 publishModelLimitCacheInvalidation(),提额/撤销即时生效 |
| 7 | Greptile P2 | src/lib/model-rate-limit/bucket-service.ts |
total 上限加 limitTotalUsd > 0 守卫,避免 $0 误配置永久封锁 |
| 8 | Greptile P1 | src/lib/model-rate-limit/bucket-service.ts |
total 窗口读穿缓存 TTL 300s → 60s,缩小全局额超支窗口(仅配置 total 上限时才触发全量聚合,开销可控) |
| 9 | CI MEDIUM | src/app/v1/_lib/proxy/model-rate-limit-guard.ts |
re-resolve 违规「只记日志」路径补 logger.warn |
| 10 | CI MEDIUM | src/actions/model-limit.ts |
补 errorCode(UNAUTHORIZED/OPERATION_FAILED/DELETE_FAILED),handler 状态映射不再依赖中文字符串匹配 |
| 11 | CI MEDIUM | src/repository/user-group.ts、src/actions/user-group.ts |
新增 countUsersByTags 单次扫描批量计数,消除 listUserGroups 的 N+1 |
| 12 | CI LOW | src/lib/model-rate-limit/bucket-lease.ts |
decrementLeaseBudget 增加 try/catch fail-open,避免污染 response handler 的 Promise.all |
| 13 | CI LOW | src/lib/model-rate-limit/lease.ts |
Lua 返回字符串元组 + Number() 解析,保留小数美元余额精度(同步更新单测) |
暂不修改(设计取舍)
provider排在rateLimit之前(Greptile P2):这是该特性必需的——模型组查找需用 redirect 后的上游模型名(匹配usage_ledger.model),必须先选定 provider;bugfix #03已清理失败路径的 ZADD。回退会破坏功能,代码注释已说明。model_group_limits.subject_id多态外键无级联(Greptile P2):多态列无法建单一外键;残留行在 resolver 中惰性(仅按存活主体匹配),不影响判定,仅占少量内存,目标规模(≤10k)可忽略。建议后续仿boost-cleanup.ts加周期清理任务,不在本次审核修复范围内改动用户/密钥删除路径。
测试备注
tests/api/* 与 k8s-deploy-shell-helpers 在本地无 Redis/Postgres 环境下的失败属基础设施依赖(鉴权 403 / openssl fallback),与本次改动无关,待具备数据库的环境验证——与 PR 测试计划中已声明的待补项一致。
二轮代码审核修复(commit 746ec5c6)
复评(Codex / Greptile)针对 0ebebe96 新增的 4 项问题已全部处理。typecheck / build / lint(无新增 error)/ i18n:audit-placeholders / i18n:audit-messages-no-emoji 均通过;model-rate-limit 单测 124 全绿。
| # | 来源 | 文件 | 处理 |
|---|---|---|---|
| 1 | Codex P1 | model-rate-limit-guard.ts / session.ts / forwarder.ts |
故障切换强制限额:非 hedge 的 provider 故障切换在发送下一次上游请求前以 changeProvider(p, { enforce: true }) 重解析并对违规抛错中止(hedge winner 提交路径不传 enforce,仍仅记日志)。RateLimitError 经现有 ProxyErrorHandler → 402/429,provider ref 由 proxy-handler 兜底清理 |
| 2 | Codex P1 | bucket-service.ts |
总额缓存随结算更新:settle 时对已存在的 total_cost:model:* 键做条件 INCRBYFLOAT(Lua EXISTS 守卫 + 保留 TTL),消除缓存窗口内越界仍放行的超支 |
| 3 | Greptile P1 | model-rate-limit-guard.ts / error-messages.ts / messages/* |
MODEL_RATE_LIMIT_FAIL_OPEN 生效:fail-closed 时无法评估的桶在强制路径拒绝请求;新增 MODEL_RATE_LIMIT_UNAVAILABLE 错误码 + 5 语言文案。默认 fail-open 不变 |
| 4 | Codex P2 | actions/model-group.ts |
成员变更失效快照缓存:add/remove member、createSingleton、deleteModelGroup 后 publishModelLimitCacheInvalidation(),新成员/限额即时生效 |
新增单测:guard fail-closed、故障切换 enforce:true 抛错、hedge 仅记日志、总额缓存 folding(配置/未配置 total 上限两种)。