Repository navigation
Conversation
Anchors session detail lookups, origin chain queries, and termination cleanup to the immutable key owner of each request rather than the session-level canonical identity. This prevents cross-owner data leakage when multiple API keys share a physical session ID. - resolveSessionRequestLocator now resolves directly by requestId when provided, returning canonicalSessionId, keyId, and userId so callers can scope all downstream reads to the request owner - findSessionOriginChain queries by requestId and keyId, selecting the nearest initial-selection provider chain within the same key epoch instead of the first request in the session - getNextRequestSequence uses an atomic Lua script to PERSIST the sequence key and write the owner marker in a single round trip - storeSessionResponse, storeSessionResponseHeaders, storeSessionUpstreamResponseMeta, and phase snapshot methods now accept and refresh the keyId owner marker, keeping late-arriving response artifacts readable - getSessionDetails and hasSessionMessages resolve the locator before loading stats when a requestId is supplied, then use the locator's userId for all subsequent queries; Redis-backed artifacts are skipped (returning null) when the owner marker is missing instead of failing closed, while database-backed audit data is still returned - terminateResolvedSessionIdentity now always calls terminateObservedSession and returns sourceSessionIds so the caller can invalidate detail caches for every physical alias - terminateSession fails closed when the owner key lookup throws with an expected keyId, preventing unauthorized cleanup - Scoped getSessionMessages and getSessionResponse no longer fall through to legacy unscoped keys when the per-request key is absent
Add sessionIdentityKind and sessionFingerprint to each setSessionDetailsCache fixture so the cached session details satisfy the canonical identity contract enforced by the cache layer.
…served lookups Reserved session identities with an ownerUserId now also match message_request rows whose session_identity is null but whose session_id equals the queried identity. This supports legacy physical session ids that use reserved prefixes. The fallback is only added when ownerUserId is present so that unscoped canonical lookups remain narrow and do not pick up unrelated null-identity rows.
🧪 测试结果
总体结果: ✅ 所有测试通过 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9a894d1b9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| `cch:replay:owner:${replayId}`, | ||
| `cch:replay:meta:${replayId}`, | ||
| `cch:replay:chunks:${replayId}`, |
There was a problem hiding this comment.
Keep Replay Lua keys in one Redis Cluster slot
On Redis Cluster deployments, these differently prefixed owner, metadata, and chunk keys have no shared hash tag and normally map to different slots, so this three-key EVAL fails with CROSSSLOT. The exception is converted to null, which makes ReplaySpool.bootstrap() disable the spool; consequently Replay never records responses on cluster-backed installations. Apply a common hash tag derived from replayId to every key used by the multi-key Replay scripts, including completion and abort.
Useful? React with 👍 / 👎.
| const runtime = attempt.session as ProxySessionWithAttemptRuntime; | ||
| attempt.responseController = runtime.responseController ?? null; | ||
| attempt.clearResponseTimeout = runtime.clearResponseTimeout ?? null; | ||
| attempt.releaseAgent = runtime.releaseAgent ?? null; |
There was a problem hiding this comment.
Keep per-attempt transport callbacks off the shared session
When Discovery is enabled and an alternative wins while the original attempt's doForward() continuation is still pending, syncWinningAttemptSession() overwrites the original session's transport callbacks with the winner's callbacks. The late loser continuation then reads those winner callbacks here, and cleanupAttempt() can release the winner's agent and remove its client-abort wiring while leaking the original attempt's agent reference. Capture the transport callbacks in attempt-local state before winner synchronization instead of rereading the mutable parent session.
Useful? React with 👍 / 👎.
| void this.store | ||
| .renewOwnerLease(this.identity.replayId, this.ownerToken) | ||
| .then((leaseHeld) => { | ||
| if (!leaseHeld && !this.released) this.halt("owner_lease_lost"); |
There was a problem hiding this comment.
Refresh Replay metadata during owner heartbeats
When live Replay deduplication is enabled and an upstream emits no bytes for more than 30 seconds, this timer renews only the owner lease while ReplayMeta.heartbeatAt remains unchanged. Both tryServe() and an attached reader's stall check use that metadata timestamp, so new identical requests cannot attach and then execute upstream after their claim fails against the renewed lease, while existing attached streams terminate as stalled even though the owner is healthy. Perform a fenced metadata heartbeat alongside the lease renewal.
Useful? React with 👍 / 👎.
When persistCompleted detected an existing matching durable row or hit a conflict during concurrent writes, the spool previously wrote an aborted terminal state to the hot layer, masking the already-persisted PG winner. persistCompleted now returns a discriminated result so the spool can detect existing winners, and conflicts raise a dedicated ReplayDurableConflictError. In both cases the spool calls the new discardOwned method to silently drop the losing hot-layer candidate without writing an aborted status. The sourceMessageRequestId check was also relaxed from the persisted-row equality test so replays of the same content from different source requests are accepted.
…ueues Statistics resets previously wiped all Redis cost-cache keys including the fixed 5h rolling windows, causing post-cutoff quota state to be lost. A new prepareUserStatisticsResetFixed5h function atomically deletes only the fixed 5h keys and records a monotonic cutoff timestamp, and clearUserCostCache now accepts preserveFixed5hCostKeys to skip those keys during the broader cleanup. The reset queue now runs this preparation phase before enqueuing and tracks a preparation version on the stored record so legacy queued jobs are reconciled idempotently on retry. Enqueue failures after preparation leave the record queued rather than discarding it, and the next enqueue attempt recovers the prepared claim. Per-batch deletion progress is persisted to the status store so retries cumulate instead of restarting, and active-claim release errors no longer mask the original business error code.
…code Re-throwing the raw DOMException exposed browser-specific error text to callers. Replace it with a stable FETCH_SESSIONS_CANCELLED error so consumers can match on a known code regardless of the browser runtime.
The statistics-reset poll loop retried transient network errors indefinitely at a fixed interval. Switch to exponential backoff with a cap of five consecutive retryable failures, after which the reset is marked failed instead of leaving the UI in a perpetual loading state.
Skip the failed-job handler when job data is missing recoverable fields so undefined resetId or userId values do not corrupt status records. Wrap status persistence in a try-catch so a transient store failure still releases the active-reset claim and propagates the original business error. Use optional chaining on job.opts for null safety.
getReadyRedis threw immediately when the shared client was in a connecting state, causing spurious failures during startup or reconnect. Make it async and await the ready or end event with a configurable timeout so callers tolerate transient connection states.
When the Redis pipeline threw after some scan calls had already failed, the returned errorCount omitted those earlier scan failures. Include the accumulated scan error count so callers see the true failure total.
The 404 response for a not-found statistics reset leaked an implementation-specific detail string. Use the shared publicActionErrorDetail helper so the message matches other 404 responses across the API surface.
Replace the old behaviour of marking a reset as failed when polling retries were exhausted: the authoritative server status is now preserved and a recoverable error banner with a retry button is shown instead. Each poll request is given a 15 s AbortSignal timeout so a hung request no longer blocks subsequent retries. Guard prepareUserStatisticsResetFixed5h against invalid or missing Redis cutoff values by returning null instead of constructing an epoch date. Throw early when getResetQueue is called in development to prevent accidental Bull/Redis processor creation outside production. Add i18n strings for statusUnavailable and retryStatus across all supported locales.
resetUserAllStatistics previously rejected requests with a cold/unready Redis client when fixed 5h cost windows were active, surfacing a CONNECTION_FAILED error before the job was even enqueued. The reset queue itself already handles Redis readiness, so this pre-enqueue guard was redundant and blocked otherwise valid reset requests during cold-start windows. The guard and its associated fixed-5h detection logic are removed; the corresponding test now verifies that enqueue proceeds and the queue receives the request without the action layer checking Redis status.
Replace assertions that expected resetUserAllStatistics to fail with CONNECTION_FAILED when Redis is unavailable. The reset now succeeds and delegates fixed 5h readiness to the background queue via enqueueUserStatisticsReset, so Redis is never contacted directly during the action call.
…cal ledger rows Reserved canonical identities (prefix-affinity or owner-scoped session IDs) could match unrelated physical ledger rows via the session_id fallback in the OR branch of the lookup condition. For reserved identities the lookup now requires both the COALESCE expression and the explicit session_identity column to match, preserving the COALESCE expression index while avoiding aliasing. The canonical lookup used by aggregateSessionStats and aggregateMultipleSessionStats now also applies the stricter reserved-identity condition so owner-scoped queries do not silently pick up physical sessions that happen to share the same ID value.
🧪 测试结果
总体结果: ✅ 所有测试通过 |
There was a problem hiding this comment.
💡 Codex Review
claude-code-hub/src/repository/message.ts
Lines 258 to 260 in b16fdb7
When Redis or the rollup write is transiently unavailable as a request reaches its terminal commit, this branch only removes the in-memory finalized marker. Nothing schedules the retained seed for another attempt, and the terminal database fence prevents that request from committing again, so the request is permanently absent from public availability, latency, and TPS statistics unless an unrelated duplicate finalization occurs. Put retryable events in a durable outbox or actively schedule their retry.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| `cch:user-statistics-reset:fixed5h:${input.resetId}`, | ||
| `user:${input.userId}:cost_5h_fixed`, | ||
| buildLeaseKey("user", input.userId, "5h", "fixed"), |
There was a problem hiding this comment.
Keep reset-preparation keys in one Redis slot
On Redis Cluster deployments, every statistics reset reaches this preparation step, but the reset marker, user cost key, user lease key, and per-key entries have unrelated hash slots. Passing them together to the multi-key Lua script makes EVAL fail with CROSSSLOT, so enqueueUserStatisticsReset() returns an error before any reset job is queued. Use a shared hash tag or perform slot-local operations instead.
Useful? React with 👍 / 👎.
| local sequence = redis.call('INCR', KEYS[1]) | ||
| redis.call('PERSIST', KEYS[1]) | ||
| local ownerKey = ARGV[1] .. sequence .. ':owner' | ||
| redis.call('SETEX', ownerKey, ARGV[2], ARGV[3]) |
There was a problem hiding this comment.
Avoid constructing a second Redis key inside the sequence script
On Redis Cluster deployments, this script is routed using only KEYS[1], then dynamically accesses ownerKey derived from ARGV; that owner key generally belongs to another slot and Redis rejects it as a non-local key. Every request then enters the catch fallback and receives a timestamp/random sequence instead of an atomic increment, allowing concurrent requests to collide and overwrite request artifacts. Use co-slotted keys or issue the owner write separately.
Useful? React with 👍 / 👎.
| const requestedAt = await prepareUserStatisticsResetFixed5h({ | ||
| resetId: jobData.resetId, | ||
| userId, | ||
| keyIds: jobData.fixed5hKeyIds ?? [], | ||
| }); |
There was a problem hiding this comment.
Recover prepared resets without requiring another admin request
When fixed-window preparation succeeds but the subsequent Bull queue.add() definitively fails, this step has already deleted the user's and keys' fixed-5h cost and lease counters. The catch returns an error while retaining only a queued Redis record, and no background process scans such records, so unless an administrator manually submits the reset again the user receives a quota reset but the database statistics are never deleted. Enqueue before applying irreversible effects or schedule automatic reconciliation of prepared records.
Useful? React with 👍 / 👎.
| const lastWindowResult = await tx.execute(sql` | ||
| SELECT MAX(window_end) AS last_end FROM provider_cache_effectiveness |
There was a problem hiding this comment.
Advance cache aggregation across empty windows
When an aggregation tick finds no requests with a cache compatibility key, the INSERT writes no rows, so this MAX(window_end) watermark never advances. On a busy deployment whose traffic is not cache-eligible, every five-minute tick consequently rescans the entire message_request interval since the initial lookback, and that interval grows without bound until a qualifying request arrives. Persist a separate watermark or an empty-window marker.
Useful? React with 👍 / 👎.
🧪 测试结果
总体结果: ✅ 所有测试通过 |
Release Note
本次 Release Note 汇总
v0.8.10至当前dev分支的用户可感知变化。同一新功能在发布前的后续完善与修正已合并到对应功能条目,不再重复列入 Bug 修复。新增功能
reasoning.effort与 Anthropicoutput_config.effort,并标识供应商配置是否覆写了客户端请求;供应商设置同时新增max最高强度选项。Bug 修复
image_gennamespace 工具,避免请求仍被转发到不支持图片生成的上游。count_tokens请求识别:缺少metadata.user_id的 Token 计数请求仍可被正确识别为 Claude Code,避免被供应商客户端限制误拦截。functionCall或functionResponse的id字段拒绝请求时,能够正确清理并重试。cache_write_tokens,并修正普通输入、缓存读取和缓存写入 Token 的拆分,避免使用日志和费用统计出现漏记或重复计算。体验优化
其他杂项
ENDPOINT_PROBE_SCHEDULER_ENABLED=false完全关闭后台定时探测,默认行为保持不变。