claude-code-hub icon indicating copy to clipboard operation
claude-code-hub copied to clipboard

fix: 修复请求记录卡在【请求中】导致崩溃 (#854)

Open tesgth032 opened this issue 9 months ago • 35 comments

## 更新(2026-03-03)

  • proxy-status:快照刷新失败时回退到过期缓存并延长 TTL,避免 dashboard 轮询期间 DB 抖动导致 500 风暴
  • orphan sweeper:覆盖 status_code 已落库但 duration_ms 仍为空的记录;不覆写既有 status_code/error_message,duration_ms 保守填充为 ttfb_ms(或 0)
  • sealedCount:兼容 db.execute 返回 rowCount/rows 等不同形态
  • write buffer:costUsd 超出 [0, 1_000_000) 时节流告警并跳过
  • 新增单测:proxy-status stale cache 退化 + orphan sealer rowCount/SQL 覆盖 + costUsd 范围

背景

Issue #854:Dashboard 日志里 message_request 长期显示“请求中”,Tokens/成本/性能等字段为空或默认值,最终导致进程崩溃重启。

根因分析(可能叠加)

  1. 默认启用的 MESSAGE_REQUEST_WRITE_MODE=async 会把终态信息先写入内存队列再批量落库;当 DB 写入遇到数据/约束错误或暂态失败时,旧实现容易让队列卡住/丢失尾部更新,导致 duration_ms/status_code 长期为空。
  2. 进程被非优雅终止(OOM/SIGKILL)时,内存队列尾部更新无法落库,产生“孤儿请求”。
  3. proxy-status 追踪在异常情况下可能无限累积“活跃请求”明细,导致响应体膨胀与内存风险,进一步诱发 OOM -> 放大 (2)。

修复

  • 强化 message_request 异步批量写入:
    • 对 numeric/jsonb 字段做显式类型转换,并对 patch 做校验/清洗
    • 遇到数据类 DB 错误时自动降级为逐条写入(safe/minimal patch),避免卡死整条队列
    • 增加 maxPending 上限,溢出时优先丢弃非终态 patch,尽量保住 duration/status
  • 进程退出(SIGTERM/SIGINT)时尽力 stop/flush 写入队列,减少尾部丢失概率
  • 增加定时 sweeper:批量封闭超过阈值仍未落终态的“孤儿请求”,防止“请求中”无限累积
  • proxy-status 改为基于数据库聚合,并对活跃请求明细加 limit,避免异常情况下撑爆内存/响应体

针对 Review 的补强

  • 为 proxy-status 的 lastRequest LATERAL 查询新增部分索引迁移(仅包含已完成请求),避免孤儿积累时回溯过深
  • 为 activeRequests/orphan sweeper 新增部分索引 idx_message_request_active_created_at_id(duration_ms IS NULL),避免扫描退化
  • sealOrphanedMessageRequests 阈值改为基于 created_at,避免 updated_at 被非终态更新推迟封闭
  • updateMessageRequestDetails 对 rejected_invalid 直接 return,避免重复 sanitize/重复告警
  • token 相关字段改用 JS safe-int(匹配 bigint)sanitize,避免无声截断导致统计不一致
  • 批量 UPDATE 的 CASE 分支补齐 ::int/::bigint/::boolean 与 NULL::jsonb cast,降低类型推断 DB 错误风险
  • flushBatchPerItem 丢弃 patch 时记录 isTerminal 并按终态提升日志级别,便于监控“终态丢失”风险
  • 抽取 env snapshot/restore 工具到 tests/helpers/env.ts,避免测试重复与漂移
  • 停止写缓冲时若仍有 pending,记录 error 便于排障

测试

  • bun run build
  • bun run lint
  • bun run lint:fix
  • bun run typecheck
  • bun run test

Closes #854

tesgth032 avatar Mar 02 '26 07:03 tesgth032

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

新增后台孤立 message_request 清扫器;强化消息写缓冲的补丁校验、溢出策略与分级回退写入;消息仓储新增批量封闭过期请求;活跃请求查询加入排序与上限保护;新增/更新相关单元与集成测试及 CI lint 安装步骤。

Changes

Cohort / File(s) Summary
孤立请求清扫器
src/instrumentation.ts
新增 __CCH_ORPHANED_MESSAGE_REQUEST_SWEEPER_STARTED__ 与 __CCH_ORPHANED_MESSAGE_REQUEST_SWEEPER_INTERVAL_ID__;实现 startOrphanedMessageRequestSweeper()(动态导入消息仓库、每 60s 调用 sealOrphanedMessageRequests、首次立即运行、并发保护);在应用启动/关闭路径集成清扫器并增加日志与错误保护。
消息写缓冲:校验、溢出与降级写入
src/repository/message-write-buffer.ts
新增导出类型 MessageRequestUpdateEnqueueResult,使 enqueueMessageRequestUpdate 返回状态;大量补丁/字段 sanitize 工具;拒绝非法补丁并返回 rejected_invalid;溢出策略优先丢弃非终态,支持 dropped_overflow;批量写失败时按项降级重试(full→safe→minimal)、重排或丢弃,增强 JSON stringify 防护与重试/日志。
消息仓储:封闭孤立请求与写入回退
src/repository/message.ts
新增并导出 sealOrphanedMessageRequests(options?),实现对超时且仍为进行态的 message_request 批量更新(duration_ms、status_code、error_message)并返回 sealedCount;写入优先入队,回退路径提供同步 DB 写入。
活跃请求查询防护
src/lib/proxy-status-tracker.ts
在 loadActiveRequests 中添加 ORDER BY created_at DESC 与本地 limit = 1000,并在达到上限时记录警告以防无界结果。
测试与 CI 变更
tests/unit/repository/message-orphaned-requests.test.ts, tests/unit/repository/message-write-buffer.test.ts, tests/integration/usage-ledger.test.ts, .github/workflows/*
新增封闭孤立请求的单元测试并断言生成的 SQL/参数;扩展写缓冲相关测试(numeric 错误降级、非法补丁返回等);调整一处集成测试签名;在两个 workflow 中加入 Ensure Biome CLI 安装步骤。

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • ding113/claude-code-hub#791: 在 lifecycle 初始化/关闭 中加入非阻塞子系统启动/停止钩子,和本 PR 在 instrumentation.ts 中为新清扫器集成生命周期的改动在代码层面高度相关。
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed 代码变更全面解决了 Issue #854 的核心需求:强化异步写入、优雅处理溢出、添加孤儿请求 sweeper、限制活跃请求查询,防止请求卡顿和进程崩溃。
Out of Scope Changes check ✅ Passed 所有变更均在 Issue #854 的修复范围内;workflow 文件的 Biome CLI 步骤和集成测试的超时调整属于必要支撑性修改,无超范围变更。
Description check ✅ Passed 拉取请求描述详细阐述了背景、根因分析、修复方案和测试步骤,与代码变更高度相关。
Title check ✅ Passed PR 标题准确总结了主要变更——修复请求记录卡在【请求中】导致的崩溃问题,与 PR 的核心目标和 Issue #854 直接对应,简洁清晰。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Mar 02 '26 07:03 coderabbitai[bot]

Summary of Changes

Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

此拉取请求旨在解决系统在处理消息请求时,因异步写入机制缺陷、进程非正常终止以及活跃请求追踪累积等问题导致的记录卡顿和系统崩溃。通过引入更健壮的数据写入策略、优雅的进程关闭流程、定期的“孤儿请求”清理以及优化的状态追踪,显著提升了系统的稳定性和数据一致性,避免了因异常数据导致的资源耗尽。

Highlights

  • 修复请求记录卡顿与崩溃问题: 解决了 #854 中描述的 Dashboard 请求记录长期卡在“请求中”状态,最终导致进程崩溃的问题。
  • 增强异步批量写入健壮性: 强化了 message_request 异步批量写入机制,包括对 numeric/jsonb 字段的显式类型转换、patch 校验与清洗,以及在遇到数据类 DB 错误时自动降级为逐条写入,避免队列卡死。
  • 引入“孤儿请求”清理器: 新增了定时任务(sweeper),用于批量封闭那些因进程非优雅终止等原因导致长时间未落终态的“孤儿请求”,防止其无限累积。
  • 优化进程优雅退出: 在进程接收到 SIGTERM/SIGINT 信号时,会尽力停止并刷新写入队列,减少尾部更新丢失的概率。
  • 改进 Proxy Status 追踪: 将 proxy-status 的活跃请求追踪改为基于数据库聚合,并对活跃请求明细增加了 limit 限制,以避免在异常情况下响应体膨胀和内存风险。
Changelog
  • src/instrumentation.ts
    • 增加了孤儿消息请求清理器的状态管理和启动/停止逻辑。
  • src/lib/proxy-status-tracker.ts
    • 限制了活跃请求查询的结果数量并增加了排序。
  • src/repository/message-write-buffer.ts
    • 引入了数据清理、错误处理和降级写入机制,以增强异步批量写入的健壮性。
  • src/repository/message.ts
    • 更新了消息请求更新函数以利用新的异步写入机制,并添加了清理孤儿请求的功能。
  • tests/unit/repository/message-orphaned-requests.test.ts
    • 添加了针对孤儿消息请求清理功能的单元测试。
  • tests/unit/repository/message-write-buffer.test.ts
    • 增加了测试用例,验证了数据类DB错误时的降级写入行为。
Activity
  • 此拉取请求旨在解决 #854 中描述的问题。
  • 作者提供了详细的背景分析、根因分析和修复方案。
  • 作者列出了 bun run build, bun run lint, bun run lint:fix, bun run typecheck, bun run test 等测试步骤,以确保更改的质量。
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

[^1]: Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

gemini-code-assist avatar Mar 02 '26 07:03 gemini-code-assist

@coderabbitai review

tesgth032 avatar Mar 02 '26 14:03 tesgth032

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar Mar 02 '26 14:03 coderabbitai[bot]

@coderabbitai review

tesgth032 avatar Mar 02 '26 15:03 tesgth032

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar Mar 02 '26 15:03 coderabbitai[bot]

Additional Comments (2)

src/lib/proxy-status-tracker.ts loadLastRequests has no LIMIT — unbounded full-table scan

loadActiveRequests correctly caps results with .limit(1000) and logs a warning when it hits that cap. However, loadLastRequests has no limit at all.

DISTINCT ON (mr.user_id) ORDER BY mr.user_id, mr.updated_at DESC requires PostgreSQL to scan every non-deleted row in message_request, then sort and deduplicate. In a large deployment the table can grow to millions of rows. Without an index on (user_id, updated_at DESC) this becomes a full sequential scan + in-memory sort on every call to getAllUsersStatus.

Both queries run inside a single Promise.all (getAllUsersStatus line 83), so a slow loadLastRequests stalls the entire status endpoint.

Consider adding a reasonable limit — e.g., guard at the application level by limiting the per-user latest row using a CTE with ROW_NUMBER, or at minimum add an explicit .limit(maxUsers) constant similar to loadActiveRequests.

// Example defensive cap (adjust limit as appropriate)
private async loadLastRequests(): Promise<LastRequestRow[]> {
  const limit = 5000; // or configurable
  const query = sql<LastRequestRow>`
    SELECT DISTINCT ON (mr.user_id)
      ...
    FROM message_request mr
    ...
    ORDER BY mr.user_id, mr.updated_at DESC
    LIMIT ${limit}
  `;
  ...
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/proxy-status-tracker.ts
Line: 191-212

Comment:
**`loadLastRequests` has no LIMIT — unbounded full-table scan**

`loadActiveRequests` correctly caps results with `.limit(1000)` and logs a warning when it hits that cap. However, `loadLastRequests` has no limit at all.

`DISTINCT ON (mr.user_id) ORDER BY mr.user_id, mr.updated_at DESC` requires PostgreSQL to scan every non-deleted row in `message_request`, then sort and deduplicate. In a large deployment the table can grow to millions of rows. Without an index on `(user_id, updated_at DESC)` this becomes a full sequential scan + in-memory sort on every call to `getAllUsersStatus`.

Both queries run inside a single `Promise.all` (`getAllUsersStatus` line 83), so a slow `loadLastRequests` stalls the entire status endpoint.

Consider adding a reasonable limit — e.g., guard at the application level by limiting the per-user latest row using a CTE with `ROW_NUMBER`, or at minimum add an explicit `.limit(maxUsers)` constant similar to `loadActiveRequests`.

```typescript
// Example defensive cap (adjust limit as appropriate)
private async loadLastRequests(): Promise<LastRequestRow[]> {
  const limit = 5000; // or configurable
  const query = sql<LastRequestRow>`
    SELECT DISTINCT ON (mr.user_id)
      ...
    FROM message_request mr
    ...
    ORDER BY mr.user_id, mr.updated_at DESC
    LIMIT ${limit}
  `;
  ...
}
```

How can I resolve this? If you propose a fix, please make it concise.

src/lib/proxy-status-tracker.ts startRequest / endRequest are now silent no-ops with active callers

There are 5 production call-sites that still invoke these methods:

  • src/app/v1/_lib/proxy-handler.ts:69 — tracker.startRequest({...})
  • src/app/v1/_lib/proxy/response-handler.ts:681, 903, 2882, 3167 — tracker.endRequest(...)
  • src/app/v1/_lib/proxy/error-handler.ts:422 — tracker.endRequest(...)

With the rewrite to DB-based tracking these calls do nothing. While that is functionally correct (active requests are now detected via durationMs IS NULL in the DB), the silent no-op pattern is fragile:

  • Future developers reading call-sites will assume state is being mutated.
  • endRequest at response-handler.ts:3167 is inside a try/catch that logs "Failed to end request tracking" — this guard now provides a false sense of safety.

Consider either removing the call-sites and the methods, or adding // no-op: tracking is now DB-based to the method body and removing the catch-block guard where callers protect against tracker failure.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/proxy-status-tracker.ts
Line: 63-78

Comment:
**`startRequest` / `endRequest` are now silent no-ops with active callers**

There are **5 production call-sites** that still invoke these methods:
- `src/app/v1/_lib/proxy-handler.ts:69` — `tracker.startRequest({...})`
- `src/app/v1/_lib/proxy/response-handler.ts:681`, `903`, `2882`, `3167` — `tracker.endRequest(...)`
- `src/app/v1/_lib/proxy/error-handler.ts:422` — `tracker.endRequest(...)`

With the rewrite to DB-based tracking these calls do nothing. While that is functionally correct (active requests are now detected via `durationMs IS NULL` in the DB), the silent no-op pattern is fragile:

- Future developers reading call-sites will assume state is being mutated.
- `endRequest` at `response-handler.ts:3167` is inside a `try/catch` that logs `"Failed to end request tracking"` — this guard now provides a false sense of safety.

Consider either removing the call-sites and the methods, or adding `// no-op: tracking is now DB-based` to the method body and removing the catch-block guard where callers protect against tracker failure.

How can I resolve this? If you propose a fix, please make it concise.

greptile-apps avatar Mar 02 '26 15:03 greptile-apps

Additional Comments (1)

src/repository/message-write-buffer.ts stop() flushes twice to catch tail updates, but if new enqueues arrive between the two flushes, they could still be lost. The stopping flag prevents new timer scheduling but doesn't prevent enqueues. Consider rejecting enqueues when stopping === true or documenting that callers must stop enqueueing before calling stop().

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/repository/message-write-buffer.ts
Line: 767-775

Comment:
`stop()` flushes twice to catch tail updates, but if new enqueues arrive between the two flushes, they could still be lost. The `stopping` flag prevents new timer scheduling but doesn't prevent enqueues. Consider rejecting enqueues when `stopping === true` or documenting that callers must stop enqueueing before calling `stop()`.

How can I resolve this? If you propose a fix, please make it concise.

greptile-apps avatar Mar 02 '26 16:03 greptile-apps

已根据 AI review 意见做了针对性收敛修正:

  • ProxyStatusTracker.loadLastRequests:改为按 created_at DESC, id DESC 选取每个用户的“最后一次请求”,避免 updated_at 去重排序在大表上引入额外 sort/全表压力;同时在 startRequest/endRequest 明确标注 no-op(当前实现基于 DB 聚合)。
  • MessageRequestWriteBuffer:把 per-item 写入链路里重复的“暂态错误回队列 + 统一日志”抽成 helper,降低后续维护遗漏风险。
  • sealOrphanedMessageRequests:封闭条件扩展为“缺 duration_ms 或缺 status_code”的陈旧记录,覆盖更极端的孤儿场景。

CI:Code Quality / Unit / Integration / API / Docker build 已全部通过。

tesgth032 avatar Mar 02 '26 17:03 tesgth032

Additional Comments (4)

src/lib/proxy-status-tracker.ts, line 297 LATERAL join scales with user count, not request count

The new loadLastRequests query iterates over every non-deleted user in the users table and runs a LATERAL subquery for each. This means query cost is O(users), even for users who have never made a request.

The old DISTINCT ON approach started from message_request and was bounded by the number of non-warmup requests — a much smaller set on typical installs where most users are inactive.

For deployments with thousands of users but few recent requests, this refactor could introduce a significant performance regression compared to the previous query. Consider using LEFT JOIN LATERAL ... ON true combined with WHERE last IS NOT NULL or restructuring to start from message_request as before. Alternatively, verify that a composite index on message_request(user_id, created_at DESC, id DESC) exists to make the LATERAL scan efficient.


.github/workflows/pr-check.yml, line 13 Hardcoded linux-x64 architecture

@biomejs/cli-linux-x64 is hardcoded, which will fail on ARM-based runners (e.g., ubuntu-24.04-arm or self-hosted ARM machines). The same issue exists in test.yml at the equivalent step.

Consider detecting the platform dynamically:

- name: 📦 Ensure Biome CLI
  run: |
    BIOME_VERSION=$(bun -p "require('@biomejs/biome/package.json').version")
    ARCH=$(uname -m)
    if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
      bun install --no-save @biomejs/cli-linux-arm64@${BIOME_VERSION}
    else
      bun install --no-save @biomejs/cli-linux-x64@${BIOME_VERSION}
    fi

Or use the platform-agnostic @biomejs/biome package directly if it bundles the native binary.


src/repository/message-write-buffer.ts, line 712 nonTerminalIds not updated when ID already in pending

After this.pending.set(id, merged), if id was already in the map before this call (i.e., existing was non-empty), the nonTerminalIds Set is updated based on the merged patch. However, the original terminal-state tracking for this ID was based on the pre-merge state.

This is only relevant in the edge case where a non-terminal patch merges over a terminal one (or vice versa). In practice the flow is: non-terminal patches accumulate, then one terminal patch arrives and merges — at that point nonTerminalIds.delete(id) correctly removes the ID. The logic appears correct for the common case, but a comment explaining the invariant ("nonTerminalIds always reflects the current merged state in pending") would help future maintainers.


src/repository/message.ts, line 1266 EXCLUDE_WARMUP_CONDITION used without table alias in CTE

EXCLUDE_WARMUP_CONDITION is referenced as ${EXCLUDE_WARMUP_CONDITION} inside the candidates CTE, where the table is referenced as bare message_request. If EXCLUDE_WARMUP_CONDITION contains a column expression that assumes a specific alias (e.g., mr.blocked_by), this query will fail at runtime.

Please verify that EXCLUDE_WARMUP_CONDITION (from "./_shared/message-request-conditions") uses either bare column names or the same unaliased table reference as the CTE, and add a test or comment confirming this assumption.

greptile-apps avatar Mar 02 '26 18:03 greptile-apps

Additional Comments (5)

.github/workflows/pr-check.yml, line 39 Regex extraction fails without error handling if $schema format changes. If match() returns null, accessing [1] throws "Cannot read property '1' of null", breaking CI.

        BIOME_VERSION=$(bun -p 'require("./biome.json")["$schema"].match(/schemas\/(\d+\.\d+\.\d+)\/schema\.json/)?.[1] || ""')
        [ -z "$BIOME_VERSION" ] && { echo "Failed to extract Biome version from biome.json schema"; exit 1; }

.github/workflows/test.yml, line 35 Same regex brittleness as pr-check.yml - needs null check

        BIOME_VERSION=$(bun -p 'require("./biome.json")["$schema"].match(/schemas\/(\d+\.\d+\.\d+)\/schema\.json/)?.[1] || ""')
        [ -z "$BIOME_VERSION" ] && { echo "Failed to extract Biome version from biome.json schema"; exit 1; }

src/repository/message-write-buffer.ts, line 748 Consider adding patch sample to the drop log for debugging schema mismatches:

        logger.error("[MessageRequestWriteBuffer] Dropping invalid update to unblock queue", {
          requestId: item.id,
          keys: Object.keys(item.patch),
          sample: JSON.stringify(item.patch).slice(0, 200),
          failureKind: lastFailure.kind,

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!


src/repository/message-write-buffer.ts, line 515 Consider adding metrics counter for rejected patches to improve observability of type mismatches during development

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!


src/lib/proxy-status-tracker.ts, line 201 Check that created_at DESC ordering (vs previous updated_at DESC) matches product requirements for "last request"

greptile-apps avatar Mar 02 '26 18:03 greptile-apps

已根据 AI review 收敛并修正(仅限本 PR 改动范围):

  • CI:移除 workflow 中硬编码的 @biomejs/cli-linux-x64 安装;并将 package.json 的 @biomejs/biome 固定为 2.4.4,与 biome.json schema 对齐,避免随新版本漂移导致 schema mismatch。
  • message_request:补充 write buffer 的 nonTerminalIds 不变量说明;sealOrphanedMessageRequests 增加 EXCLUDE_WARMUP_CONDITION 相关说明,并在单测中断言 blocked_by/warmup 条件存在,避免 alias 假设风险。
  • tests:按 Biome 期望格式化 usage-ledger 集成测试,避免 format:check 失败。

Actions:PR Build Check / Test Suite 已通过(Greptile Review 仍为 pending)。

tesgth032 avatar Mar 02 '26 19:03 tesgth032

Additional Comments (7)

src/repository/message.ts, line 97 no verification that update actually modified any rows. if record was deleted or doesn't exist, function silently succeeds without writing anything. caller has no way to know update failed.

consider returning boolean or throwing if no rows affected, especially since this is fallback for enqueue failures where data integrity matters.


src/repository/message-write-buffer.ts, line 441 JSON.stringify failure logs warning but silently skips the field in SQL. entire column update is dropped without caller knowing. if providerChain or specialSettings contains circular reference or throws, batch SQL won't include that field at all.

this masks data integrity issues since caller thinks update succeeded but field wasn't written.


src/lib/proxy-status-tracker.ts, line 78 methods are now no-ops but still called throughout codebase (no deprecation warning). developers reading call sites will be confused why these exist but do nothing.

add @deprecated JSDoc comment explaining migration to DB-based aggregation, or remove calls entirely if truly unused.


src/repository/message.ts, line 228 calculates duration_ms as NOW() - created_at for orphaned requests. if request was created days ago due to bug/delay, this produces misleading duration (e.g., 604800000ms for 7-day-old request).

makes it impossible to distinguish "request actually took 7 days" vs "orphaned record sealed after 7 days". consider using sentinel value like INT32_MAX or separate flag to mark calculated vs actual durations.


src/instrumentation.ts, line 164 void runOnce("startup") runs in background without blocking app launch (good), but if DB query itself throws (not timeout), error is caught at line 155-160 and logged but there's no way to monitor if startup sweep actually succeeded.

startup sweep failures are silent in metrics/monitoring. consider emitting metric or structured log event on completion.


src/repository/message-write-buffer.ts, line 748 buildBatchUpdateSql failure triggers per-item fallback, which is correct for data errors. but if failure is due to persistent bug in SQL building logic itself (e.g., new field type added without sanitization), the fallback hides root cause.

per-item writes will also call same broken buildBatchUpdateSql at line 664, so if bug affects single-item queries too, this degrades into log spam without actually fixing anything.


src/repository/message-write-buffer.ts, line 518 after pending.set(id, merged), if isTerminalPatch(merged) throws (unlikely but possible if patch structure is unexpected), nonTerminalIds would be left inconsistent with pending state.

consider moving terminal check before the set, or wrapping both operations in try-finally to ensure consistency.

greptile-apps avatar Mar 02 '26 19:03 greptile-apps

Additional Comments (1)

src/lib/proxy-status-tracker.ts, line 215 Semantic change: "last request" now uses created_at DESC instead of updated_at DESC. This means you'll see the most recently created request per user, not the most recently updated one.

For a status display, this could show stale info—e.g., if user started request A at 10:00 (still processing) and completed request B at 10:02, you'll show A instead of B.

If this is intentional for index performance (user_id, created_at index), consider documenting the trade-off.

greptile-apps avatar Mar 02 '26 20:03 greptile-apps

本轮继续按 AI 审阅意见在本 PR 改动范围内收敛与加固(关键点:尽量让问题在更早阶段暴露/解决,避免兜底路径被用上):

  • message_request 异步写缓冲:dropped_overflow 现在会携带被丢弃的合并后 patch;仓储层同步写入兜底改为优先写入该 patch,避免在“duration/status 分两次更新”时因 overflow 丢失先前终态字段而再次出现“请求中”悬挂。
  • JSON 字段防御:对 providerChain/specialSettings 在入队 sanitize 阶段做深拷贝(基于 JSON round-trip),避免后续被外部对象突变/环引用导致 flush 时 stringify 失败而静默跳字段。
  • 同步兜底写入可观测性:writeMessageRequestUpdateToDb 增加 RETURNING 并在 0 行更新时记录 warn,避免记录不存在/被删除时静默成功。
  • orphaned sweeper:startup run 增加 completion 结构化日志,便于监控是否成功执行(scheduled 仍保持低噪声策略)。
  • proxy-status:startRequest/endRequest 增加 @deprecated 说明;lastRequest 查询排除进行中请求(duration_ms IS NOT NULL),避免把 active request 的 created_at/updated_at 当作“结束时间”展示。

本地检查:bun run build / bun run lint / bun run lint:fix / bun run format:check / bun run typecheck / bun run test 均通过。

tesgth032 avatar Mar 02 '26 20:03 tesgth032

Additional Comments (4)

src/repository/message-write-buffer.ts, line 521 Merge direction is opposite to requeueBatchForRetry

enqueue uses { ...existing, ...sanitized }, so the new sanitized patch wins over the existing buffered patch. But requeueBatchForRetry (line 849) uses { ...item.patch, ...existing }, so the newer in-pending data wins over the retry payload. This asymmetry is intentional (and documented), but it has a subtle consequence in one edge case:

If a prior non-terminal enqueue for the same id is still in pending (e.g. { inputTokens: 1000 }), and enqueue merges + immediately overflows dropping this ID, the caller in updateMessageRequestCost receives dropped_overflow with a non-terminal merged patch — and quietly returns without writing to DB (lines 143-146 in message.ts). The previously buffered inputTokens data is silently lost.

This is an edge case (queue must be exactly at capacity, and the ID in question must already have data in the buffer), but it is a possible silent data loss path. Consider adding a comment explaining why this is acceptable, or — if data fidelity for non-terminal patches matters here — routing the dropped patch to a sync write regardless of terminal status.


src/repository/message-write-buffer.ts, line 526 cacheTtlApplied invalid types are silently discarded without logging

In sanitizePatch, providerChain and specialSettings log a logger.warn when their types are unexpected. cacheTtlApplied (and the two booleans) do not — if a non-string, non-null value arrives at runtime it is silently omitted with no diagnostic. While the TypeScript type should prevent this, the sanitize function is explicitly written to handle runtime surprises for other fields, so this inconsistency could make debugging harder.

  if (patch.cacheTtlApplied === null) {
    sanitized.cacheTtlApplied = null;
  } else if (typeof patch.cacheTtlApplied === "string") {
    sanitized.cacheTtlApplied = patch.cacheTtlApplied;
  } else if (patch.cacheTtlApplied !== undefined) {
    logger.warn("[MessageRequestWriteBuffer] Invalid cacheTtlApplied type, skipping", {
      cacheTtlAppliedType: typeof patch.cacheTtlApplied,
    });
  }

src/repository/message.ts, line 105 Warning fires for soft-deleted records — misleading alert

writeMessageRequestUpdateToDb adds isNull(messageRequest.deletedAt) to the WHERE clause (line 98), so an update targeting a soft-deleted record will legitimately affect 0 rows. The warning logged here will fire in that case too, making it hard to distinguish a genuine "record not found" problem from an expected "record already deleted" situation.

Consider distinguishing the two, for example by checking deleted_at first:

if (updated.length === 0) {
  logger.warn("[MessageRepository] Message request update affected 0 rows", {
    requestId: id,
    keys: Object.keys(sanitized),
    // caller should verify record is not soft-deleted if this fires unexpectedly
  });
}

Or suppress the warning when the record is known to be deleted, to reduce noise in logs.


src/lib/proxy-status-tracker.ts, line 310 INNER JOIN excludes users whose only requests are still in-flight

JOIN LATERAL (...) last ON true is an implicit INNER JOIN. A user who has only ever had active/ongoing requests (no completed ones with duration_ms IS NOT NULL) will not appear in lastRequest at all. The comment explains this is intentional ("lastRequest 仅统计已结束请求"), but combined with the activeRequests path it means a brand-new user making their very first request would appear in activeRequests but never in lastRequest until that first request completes.

If the dashboard aggregates both arrays and the user is only visible via activeRequests, this is fine. But if any consumer expects lastRequest to be exhaustive for all currently-active users, it will silently miss them. A clarifying comment at the call site (getAllUsersStatus) confirming this deliberate gap would help future readers avoid confusion.

greptile-apps avatar Mar 02 '26 20:03 greptile-apps

已对 Greptile 在 2026-03-02 20:51:47Z 的 Additional Comments 做收敛(仅限本 PR 改动范围):

  • message-write-buffer: 对 cacheTtlApplied/context1mApplied/swapCacheTtlApplied 的异常类型补充 logger.warn,便于定位运行时脏数据来源。
  • message: 0 行更新的告警文案补充 “missing or soft-deleted” 语义,降低误解成本;同时对 overflow 下“非终态 patch 允许丢弃”的设计补充注释,明确这是有意取舍。
  • proxy-status-tracker: 在 getAllUsersStatus 补充注释说明 lastRequest 仅覆盖已结束请求,进行中由 activeRequests 负责展示。

tesgth032 avatar Mar 02 '26 21:03 tesgth032

Additional Comments (3)

src/repository/message-write-buffer.ts, line 218 Domain-specific constraint embedded in generic-named function

sanitizeNumericString contains a hard-coded business rule (0 <= value < 1_000_000) that is specific to costUsd's DB column schema (numeric(21, 15), integer part < 6 digits). The comment acknowledges this ("目前仅用于 costUsd"), but the function name is generic.

If a future numeric field (e.g., a pricing multiplier or a different cost column with a larger range) reuses sanitizeNumericString, its valid values would be silently rejected with no log message, causing confusing data loss. The constraint would need to be either parameterized or the function renamed to make the intended scope clear:

function sanitizeCostUsdString(value: unknown): string | undefined {
  // ... same implementation, name makes domain constraint explicit
}

Or make the range configurable:

function sanitizeNumericString(
  value: unknown,
  options?: { min?: number; max?: number }
): string | undefined {
  // ...
  const min = options?.min ?? 0;
  const max = options?.max ?? 1_000_000;
  if (parsed < min || parsed >= max) return undefined;
  // ...
}

src/lib/proxy-status-tracker.ts, line 238 updated_at used as end_time overstates how recently a request completed

The LATERAL subquery returns mr.updated_at AS end_time. With MESSAGE_REQUEST_WRITE_MODE=async, the write buffer flushes updates in batches (default every 250ms). This means:

  1. A request that completes at T=0 may have its duration_ms written at T=250ms (flush interval), making updated_at = T+250ms.
  2. Subsequent non-terminal updates (e.g., costUsd, token counts) written in a later flush batch will push updated_at even further from the true completion time — potentially by seconds.

For the proxy-status dashboard this may be acceptable (monitoring purposes), but the elapsed field computed from this endTime could show the request completed more recently than it did. Consider using created_at + duration_ms to approximate actual completion time for completed records, which is unaffected by async write timing:

(mr.created_at + (mr.duration_ms || ' milliseconds')::interval) AS end_time

This would give a more accurate completion timestamp, at the cost of a slightly more complex expression.


src/repository/message-write-buffer.ts, line 697 requeueBatchForRetry can push pending.size above maxPending, triggering unintended drops

requeueBatchForRetry does not check maxPending, by design (requeued items should not be discarded). However, during a slow flush with heavy traffic, this creates the following scenario:

  1. pending is at exactly maxPending.
  2. Flush takes a batch (size drops by batchSize).
  3. New high-traffic enqueue() calls fill pending back up to maxPending or slightly over.
  4. Flush fails transiently — requeueBatchForRetry adds the batch back, pushing pending.size to maxPending + batchSize.

Now, any subsequent enqueue() call that updates an existing id in pending will see pending.size > maxPending and trigger the overflow drop logic, potentially evicting a non-terminal entry even though the actual number of unique requests didn't increase. Under sustained transient DB errors this can cause unexpected data loss for non-terminal updates.

Consider tracking requeueBatchForRetry additions separately or skipping the overflow check for existing-key updates:

const isNewId = !this.pending.has(id);
this.pending.set(id, merged);
// Only check overflow if we actually added a new entry
if (isNewId && this.pending.size > this.config.maxPending) {
  // ... overflow handling
}

greptile-apps avatar Mar 02 '26 22:03 greptile-apps

Additional Comments (5)

src/repository/message.ts, line 119 rejected_invalid early return silently drops the update

When enqueueMessageRequestUpdate returns "rejected_invalid" (patch is empty after sanitization), the function returns early without writing to the DB. This is correct for truly empty patches. However the comment on the condition is confusing because the function name updateMessageRequestDuration guarantees a non-empty durationMs argument — the patch should never actually be rejected here. The concern is the pattern is copy-pasted to updateMessageRequestCost (line 139) and updateMessageRequestDetails (line 186), and in those callers a rejected patch does mean data is silently lost without any synchronous fallback.

For robustness, "rejected_invalid" should fall through to the synchronous write path just like "buffer_unavailable" does. Currently both "buffer_unavailable" and "rejected_invalid" bypass the sync fallback:

  const enqueueResult = enqueueMessageRequestUpdate(id, { durationMs });
  if (enqueueResult.kind === "enqueued") {
    return;
  }

Apply the same fix at lines 139 and 186.


src/repository/message.ts, line 248 Orphan condition seals records with only one NULL field, risking premature sealing

The WHERE clause treats a record as orphaned when either duration_ms IS NULL OR status_code IS NULL. This means a record that already has duration_ms set (i.e. the request finished and the primary terminal field was written) but is still missing status_code (which may arrive via a subsequent async patch) can be prematurely sealed with status_code = 520 / error_message = "ORPHANED_REQUEST", corrupting a perfectly valid completed record.

Consider requiring both fields to be NULL for the strict orphan case, or at minimum only sealing when duration_ms IS NULL (since duration_ms is the canonical "still in-flight" signal):

        AND duration_ms IS NULL
        AND updated_at < ${threshold}

And update the corresponding UPDATE … WHERE condition at line 268 to match.


src/repository/message-write-buffer.ts, line 693 requeueBatchForRetry may silently re-expand queue past maxPending then trim terminal patches

After requeue, trimPendingToMaxPending() is called with no currentId, meaning when all non-terminal IDs are exhausted it falls through to this.pending.keys().next() — the first (oldest) entry — which could be a terminal patch from the original failed batch. Terminal patches can therefore be silently dropped from the queue after a transient DB error, causing those requests to permanently miss their duration_ms/status_code.

Log output for droppedTerminalCount > 0 does exist, but the drop is still silent from the caller's perspective. Consider adding a structured warning that explicitly identifies the dropped terminal request IDs so operators can investigate, rather than only a count.


src/lib/proxy-status-tracker.ts, line 186 loadActiveRequests includes orphaned records with duration_ms IS NULL that will be sealed by sweeper

The active-requests query filters on durationMs IS NULL to find in-flight requests. After sealOrphanedMessageRequests runs, those records will have duration_ms filled in, so they'll drop out of the list — good. However, in the window between process restart and the sweeper's first run (up to 60 s), pre-existing orphaned records (which could be from a previous crash) are still returned as "active" and their duration is computed as now - createdAt, possibly returning multi-hour "active" requests to the UI.

This is a cosmetic issue rather than a crash risk, but the comment at line 183-184 says the limit is a defence against "异常情况下 durationMs 长期为空"— the root cause. Consider also filtering by createdAt > NOW() - INTERVAL '…' (e.g. staleAfterMs) here as an additional guard, so truly stale orphans don't appear as active before the sweeper runs.


src/repository/message-write-buffer.ts, line 631 Batch-size flush triggered while flushInFlight is running may silently do nothing

When this.pending.size >= this.config.batchSize, the code calls void this.flush(). But flush() returns immediately (setting flushAgainAfterCurrent = true) when flushInFlight is already set. That flag is correctly checked in the do … while loop — so the second flush will run after the first finishes.

However, this void this.flush() call is after the early-return block at line 617–620 that also sets flushAgainAfterCurrent = true and returns. When flushInFlight is active the code returns at line 619, and the batch-size check on line 629 is never reached. This means the batch-size fast-path is dead code during an in-flight flush — a minor correctness issue that could be clarified with a comment, or the batch-size check could be moved before the flushInFlight guard to make the intent explicit.

greptile-apps avatar Mar 02 '26 22:03 greptile-apps

Additional Comments (4)

src/repository/message-write-buffer.ts, line 343 No length limits on string fields may cause DB write failures

errorMessage, errorStack, errorCause, and model are accepted without any size constraints. An extremely long error stack trace (e.g., deeply recursive errors) or a pathologically long model name could exceed column-level varchar/text limits defined in the schema, causing DB write errors that would then trigger the per-item fallback and potentially exhaust all three patch strategies before dropping the update.

Consider truncating at a reasonable maximum, e.g.:

if (typeof patch.errorMessage === "string") {
  sanitized.errorMessage = patch.errorMessage.slice(0, 4096);
}
if (typeof patch.errorStack === "string") {
  sanitized.errorStack = patch.errorStack.slice(0, 65535);
}
if (typeof patch.errorCause === "string") {
  sanitized.errorCause = patch.errorCause.slice(0, 4096);
}
if (typeof patch.model === "string") {
  sanitized.model = patch.model.slice(0, 255);
}

Truncation limits should match your schema column definitions.


src/lib/proxy-status-tracker.ts, line 199 INNER JOIN excludes in-flight requests from soft-deleted providers

loadActiveRequests uses innerJoin(providers, ...) and then filters with isNull(providers.deletedAt) in the WHERE clause. If a provider is soft-deleted while requests are still in flight, those active requests immediately vanish from the proxy-status view — they continue consuming resources but become invisible to the monitoring dashboard.

Since the goal is to show currently active requests regardless of provider state, consider using a leftJoin:

const rows = await db
  .select({ ... })
  .from(messageRequest)
  .leftJoin(providers, eq(messageRequest.providerId, providers.id))
  .leftJoin(keys, and(eq(keys.key, messageRequest.key), isNull(keys.deletedAt)))
  .where(
    and(
      isNull(messageRequest.deletedAt),
      isNull(messageRequest.durationMs),
    )
  )
  ...

And handle providerName potentially being null (e.g. row.providerName ?? "deleted") in the result mapping.


src/repository/message.ts, line 157 Silent costUsd data loss for rejected_invalid result

When enqueueResult.kind === "rejected_invalid", the code falls through to the await writeMessageRequestUpdateToDb(id, { costUsd: formattedCost }) call at line 156. But rejected_invalid means sanitizeCostUsdString(formattedCost) returned undefined inside the buffer (e.g. the formatted cost string is >= 1_000_000 or has an unexpected format). The subsequent sync write calls sanitizeMessageRequestUpdatePatch again, which will produce the same empty result and silently return early — the cost update is lost with no warning.

Since the data was definitively classified as invalid (not a transient issue), consider logging a warning here rather than silently falling through:

if (enqueueResult.kind === "rejected_invalid") {
  logger.warn("[MessageRepository] costUsd update rejected as invalid, skipping", {
    requestId: id,
    costUsd: formattedCost,
  });
  return;
}

tests/unit/repository/message-write-buffer.test.ts, line 30 toSqlText is missing the casing parameter present in the sibling test file

The corresponding helper in tests/unit/repository/message-orphaned-requests.test.ts passes casing: new CasingCache() to toQuery. Without it, toQuery may silently omit case-conversion for column names in future drizzle versions, causing the SQL assertions in this file (e.g. expect(built.sql).toContain("duration_ms")) to match differently-cased identifiers and produce false positives or false negatives.

import { CasingCache } from "drizzle-orm/casing";

function toSqlText(query: { toQuery: (config: any) => { sql: string; params: unknown[] } }) {
  return query.toQuery({
    casing: new CasingCache(),
    escapeName: (name: string) => `"${name}"`,
    escapeParam: (index: number) => `$${index}`,
    escapeString: (value: string) => `'${value}'`,
    paramStartIndex: { value: 1 },
  });
}

greptile-apps avatar Mar 02 '26 23:03 greptile-apps