Skip to content

fix(logs): bound PgLogWriter backpressure, single-tx flush, LiveLogCache trim, and routing patch queue - #2458

Open
dofastted wants to merge 4 commits into
devfrom
fix/r3-log-rw-backpressure
Open

dofastted wants to merge 4 commits into
devfrom
fix/r3-log-rw-backpressure

Conversation

@dofastted

@dofastted dofastted commented Dec 1, 2026 •

Copy link
Copy Markdown
Owner

变更摘要

  • 改前:
    • LiveLogCache 维护零生产引用的 live:sess:active ZSET 与无上限 _localActiveSessions Map(L1),每次 startRequest 全量 O(N) 扫描 _localInflight(L2),finishRequest 把最大 64KB 的 jev_state 整份写入 Redis recent 桥接(L6),listLiveAndRecent 每次轮询无合并直查 Redis 且执行 ZREMRANGEBYSCORE 写操作(L9)。
    • PgLogWriter 超过 maxPending 时对每条日志无上限直连 pool.connect() 触发连接池雪崩(L3/PG10),单通道把 usage_logs/request_attempts/request_log_debug 拆成 3 次取连接 + 3 个事务(L10/PG10),debug 体积裁剪最多 64 轮全表 SUM+COUNT 扫(L5/PG10),runRetentionCleanupAsync 遗漏 request_attempts 周期清理且 routing-runtime 在 PG 启动时主线程同步全表 DELETE(PG2),保留零引用 enqueue()/enqueueDebug()(L12)。
    • RequestLogStore 对 Gemini 工具续写合并先全量 flush() 再走同步读改写(L4),_windowStatsPgAsync 使用 8 个标量 PERCENTILE_CONT 且跳过租户 owner_user_id(PG7),'ops-window' SWR 缓存键未包含 mutedErrorClasses(P2),含死分支 isHighConcurrency(L12),JSONL 镜像每条同步 mkdirSync+appendFileSync(L13)。
    • routing-runtime.mjs 的 persistRoutingPatch 无并发串行队列且在落盘前原地修改共享 ctx.routingConfig(P4)。
  • 改后:
    • src/lib/cache/live-log-cache.mjs:删除 getActiveSessionKeys/_localActiveSessions/SESS_ACTIVE_ZSET/sessionActiveTtlSec(保留 getActiveSessionCounts 与 _localSessionConc);_pruneLocalInflight 遇首条 started >= cutoff 立即 break(O(expired));formatRecentEntry 按列表白名单剔除 jev_state/advisor_usage/image_usage;listLiveAndRecent 按 (fetchCap, includeRecent, ageLimit) 增加 1s single-flight 结果复用并节流 ZREMRANGEBYSCORE。
    • src/lib/db/pg/pg-log-writer.mjs:移除无上限 _directInFlight/_dispatchDirectWrite,改为软上限入队 + 紧急批量 flush(并发严格 <= concurrency,保留 overflowDirect 计数兼容 bench-20k);新增 mergeToolContinuationInQueue 原地合并队列中父记录;单通道复用 1 个 client + 1 个事务写 usage_logs + request_attempts(保留 SET LOCAL synchronous_commit = off 与 attempts 排序防死锁),request_log_debug 包裹在 SAVEPOINT sp_debug 隔离失败;runRetentionCleanupAsync 改用单次窗口函数 SUM(OCTET_LENGTH(record_json)) OVER (ORDER BY ts DESC, request_id DESC) 定位截止 ts 后按 ctid 分批删,并在同把 advisory lock 内新增第 5 步 request_attempts ctid 分批清理;删除零引用 enqueue()/enqueueDebug()(保留 USAGE_LOG_COLUMNS/usageLogToRow 签名)。
    • src/lib/admin/request-log.mjs:Gemini 续写合并优先调 pgWriter.mergeToolContinuationInQueue 零 DB IO,仅父记录已离队时走原 flush+DB merge 路径;_windowStatsPgAsync 合并为 2 个 PERCENTILE_CONT(ARRAY[0.5, 0.9, 0.95, 0.99]) 并下推 owner_user_id;'ops-window' 缓存键纳入 muted: this.mutedErrorClasses;移除死分支 isHighConcurrency;JSONL 镜像目录只建一次且改为异步串行追加;SQLite cleanup() 同步清理过期 request_attempts。
    • src/lib/admin/routing-runtime.mjs:PG 模式下 initPoolRuntime 跳过启动期同步 attemptsRepo.cleanup();persistRoutingPatch 增加 FIFO 单飞串行队列,在隔离克隆体上预归一化并落盘成功后再原子发布 ctx.routingConfig 与监控配置。
  • 未改 / 延后:usage-logs-repo.mjs、usage-logs-view.mjs、panel-routes.mjs(归其他轨道);scripts/bench-20k/verify-closed-loop.mjs(保留 overflowDirect 计数契约无需改动)。

验收记录(Run)

  • 环境与基线:Windows + WSL2 Debian Node v24.13.0,基于 origin/dev 7870fa8d52c7dcc4f2af6701a45f23f6a6a37248 在独立工作树 X:\vm2api-wt-r3-log-rw(分支 fix/r3-log-rw-backpressure)施工。
  • 已跑命令与结果:
    • npx biome check src/lib/cache/live-log-cache.mjs src/lib/db/pg/pg-log-writer.mjs src/lib/admin/request-log.mjs src/lib/admin/routing-runtime.mjs test/unit/live-log-cache.test.mjs test/unit/pg-log-writer.test.mjs test/unit/log-realtime-merge.test.mjs test/unit/request-log.test.mjs test/unit/routing-runtime-load.test.mjs: PASS (9 files, 0 errors, 0 warnings)
    • find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check: PASS (0 syntax errors)
    • KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci: PASS (13/13 isolated test files, exit 0)
    • node --test test/unit/live-log-cache.test.mjs test/unit/pg-log-writer.test.mjs test/unit/log-realtime-merge.test.mjs test/unit/request-log.test.mjs test/unit/gemini-request-log.test.mjs test/unit/routing-runtime-load.test.mjs test/unit/settings-routing-audit.test.mjs test/unit/routing-redaction-budget.test.mjs test/unit/usage-logs-view.test.mjs test/unit/request-logs-export.test.mjs test/unit/write-behind.test.mjs test/unit/panel-redis-opt.test.mjs: PASS (189 pass, 0 fail, 1 skip without PG_URL)
    • WSL 临时 Docker postgres:18-alpine (127.0.0.1:55439, 跑完已清理) VM2API_TEST_PG_URL=... node --test test/unit/pg-log-writer.test.mjs test/unit/pg-integration.test.mjs test/unit/pg-repos-parity.test.mjs: PASS (22/22 pass, 0 fail, 0 skip)

回退与手破验证(Broken by hand)

  • 临时关闭 PgLogWriter._executeChannelTx 中 request_log_debug 的 useSavepoint: true -> PgLogWriter uses 1 client + 1 transaction per channel and isolates debug failure via SAVEPOINT FAIL(AssertionError: missing SAVEPOINT sp_debug / RELEASE SAVEPOINT sp_debug in single-tx sequence)-> 恢复后 PASS。
  • 临时把 LiveLogCache._pruneLocalInflight 的 if (started >= cutoff) break 退回全量扫描 -> LiveLogCache L1/L2/L6/L9: omits sess:active, early-breaks inflight prune, strips jev_state, and single-flights/throttles reads FAIL(AssertionError: _pruneLocalInflight must break on first started >= cutoff instead of scanning full Map)-> 恢复后 PASS。
  • 临时绕过 routing-runtime.mjs 中 persistRoutingPatch 的 persistQueue 串行队列 -> P4: persistRoutingPatch serializes concurrent patches in FIFO order and avoids mutating live routingConfig on failure FAIL(AssertionError: concurrent patch #2 must not interleave before patch #1 finishes)-> 恢复后 PASS。

真实使用(Real use)

  • 已在 WSL 本地一次性 postgres:18-alpine 容器上实跑 pg-log-writer(含真实 UNNEST 批量写、单事务 SAVEPOINT、窗口裁剪及 request_attempts ctid 清理)、pg-integration、pg-repos-parity 全通过(22/22 PASS,0 skip);未连生产机 ph24(沙箱禁区规则禁止)。

未运行项(Not run)

  • 全仓 556 个单测与 E2E / Web 前端套件(本提交零改动 web/、Go、Rust 模块);生产机 ph24 线上实测(按安全红线禁止连接);bench-20k 20K 实压测(未改动 verify-closed-loop.mjs 契约,单测中 waits for drain 用例因 WSL 代理环境回环请求未配置 NO_PROXY 与本改动无关)。

Note

Medium Risk
Touches hot-path log backpressure (drops possible under PG stall), routing config atomicity, and tenant-scoped stats SQL—important for ops correctness but bounded by extensive unit/PG integration tests.

Overview
This PR hardens logging, live dashboards, and routing config updates under high load and multi-tenant stats.

PgLogWriter drops unbounded overflow direct writes in favor of a strict maxPending cap (shed debug rows first, reject excess), batches usage_logs + request_attempts + request_log_debug in one client/transaction with SAVEPOINT isolation for debug failures, and adds mergeToolContinuationInQueue so Gemini tool continuations can update buffered parent rows without flush/DB I/O. Retention now ctid-cleans request_attempts and trims oversized debug storage via a single window cutoff instead of repeated full-table scans.

RequestLogStore prefers in-queue continuation merge, pushes owner_user_id into PG window stats (2 array PERCENTILE_CONT calls), keys ops-window SWR by muted error classes, replaces sync JSONL with a bounded async queue (flushJsonl / close on shutdown), and adds SQLite request_attempts cleanup parity.

LiveLogCache removes dead live:sess:active tracking, whitelists/truncates recent-bridge payloads (keeps bounded jev_state), adds ~1s single-flight list read cache (VM2API_LIVE_LIST_CACHE_TTL_MS), and speeds inflight pruning when timestamps stay monotonic.

persistRoutingPatch now runs on a FIFO queue, builds a draft clone, writes disk, then atomically publishes live config and monitor hooks only after success. PG skips blocking request_attempts cleanup at pool init.

Server shutdown calls requestLog.close() after write-behind flush and before cache teardown.

Reviewed by Cursor Bugbot for commit a9739d4. Configure here.

…che trim, and routing patch queue

## 变更摘要
- 改前:
  - `LiveLogCache` 维护零生产引用的 `live:sess:active` ZSET 与无上限 `_localActiveSessions` Map(L1),每次 `startRequest` 全量 `O(N)` 扫描 `_localInflight`(L2),`finishRequest` 把最大 64KB 的 `jev_state` 整份写入 Redis recent 桥接(L6),`listLiveAndRecent` 每次轮询无合并直查 Redis 且执行 `ZREMRANGEBYSCORE` 写操作(L9)。
  - `PgLogWriter` 超过 `maxPending` 时对每条日志无上限直连 `pool.connect()` 触发连接池雪崩(L3/PG10),单通道把 `usage_logs`/`request_attempts`/`request_log_debug` 拆成 3 次取连接 + 3 个事务(L10/PG10),debug 体积裁剪最多 64 轮全表 `SUM+COUNT` 扫(L5/PG10),`runRetentionCleanupAsync` 遗漏 `request_attempts` 周期清理且 `routing-runtime` 在 PG 启动时主线程同步全表 `DELETE`(PG2),保留零引用 `enqueue()`/`enqueueDebug()`(L12)。
  - `RequestLogStore` 对 Gemini 工具续写合并先全量 `flush()` 再走同步读改写(L4),`_windowStatsPgAsync` 使用 8 个标量 `PERCENTILE_CONT` 且跳过租户 `owner_user_id`(PG7),`'ops-window'` SWR 缓存键未包含 `mutedErrorClasses`(P2),含死分支 `isHighConcurrency`(L12),JSONL 镜像每条同步 `mkdirSync`+`appendFileSync`(L13)。
  - `routing-runtime.mjs` 的 `persistRoutingPatch` 无并发串行队列且在落盘前原地修改共享 `ctx.routingConfig`(P4)。
- 改后:
  - `src/lib/cache/live-log-cache.mjs`:删除 `getActiveSessionKeys`/`_localActiveSessions`/`SESS_ACTIVE_ZSET`/`sessionActiveTtlSec`(保留 `getActiveSessionCounts` 与 `_localSessionConc`);`_pruneLocalInflight` 遇首条 `started >= cutoff` 立即 `break`(`O(expired)`);`formatRecentEntry` 按列表白名单剔除 `jev_state`/`advisor_usage`/`image_usage`;`listLiveAndRecent` 按 `(fetchCap, includeRecent, ageLimit)` 增加 1s single-flight 结果复用并节流 `ZREMRANGEBYSCORE`。
  - `src/lib/db/pg/pg-log-writer.mjs`:移除无上限 `_directInFlight`/`_dispatchDirectWrite`,改为软上限入队 + 紧急批量 flush(并发严格 `<= concurrency`,保留 `overflowDirect` 计数兼容 `bench-20k`);新增 `mergeToolContinuationInQueue` 原地合并队列中父记录;单通道复用 1 个 `client` + 1 个事务写 `usage_logs` + `request_attempts`(保留 `SET LOCAL synchronous_commit = off` 与 attempts 排序防死锁),`request_log_debug` 包裹在 `SAVEPOINT sp_debug` 隔离失败;`runRetentionCleanupAsync` 改用单次窗口函数 `SUM(OCTET_LENGTH(record_json)) OVER (ORDER BY ts DESC, request_id DESC)` 定位截止 `ts` 后按 `ctid` 分批删,并在同把 advisory lock 内新增第 5 步 `request_attempts` `ctid` 分批清理;删除零引用 `enqueue()`/`enqueueDebug()`(保留 `USAGE_LOG_COLUMNS`/`usageLogToRow` 签名)。
  - `src/lib/admin/request-log.mjs`:Gemini 续写合并优先调 `pgWriter.mergeToolContinuationInQueue` 零 DB IO,仅父记录已离队时走原 flush+DB merge 路径;`_windowStatsPgAsync` 合并为 2 个 `PERCENTILE_CONT(ARRAY[0.5, 0.9, 0.95, 0.99])` 并下推 `owner_user_id`;`'ops-window'` 缓存键纳入 `muted: this.mutedErrorClasses`;移除死分支 `isHighConcurrency`;JSONL 镜像目录只建一次且改为异步串行追加;SQLite `cleanup()` 同步清理过期 `request_attempts`。
  - `src/lib/admin/routing-runtime.mjs`:PG 模式下 `initPoolRuntime` 跳过启动期同步 `attemptsRepo.cleanup()`;`persistRoutingPatch` 增加 FIFO 单飞串行队列,在隔离克隆体上预归一化并落盘成功后再原子发布 `ctx.routingConfig` 与监控配置。
- 未改 / 延后:`usage-logs-repo.mjs`、`usage-logs-view.mjs`、`panel-routes.mjs`(归其他轨道);`scripts/bench-20k/verify-closed-loop.mjs`(保留 `overflowDirect` 计数契约无需改动)。

## 验收记录(Run)
- 环境与基线:Windows + WSL2 Debian Node v24.13.0,基于 `origin/dev` `7870fa8d52c7dcc4f2af6701a45f23f6a6a37248` 在独立工作树 `X:\vm2api-wt-r3-log-rw`(分支 `fix/r3-log-rw-backpressure`)施工。
- 已跑命令与结果:
  - `npx biome check src/lib/cache/live-log-cache.mjs src/lib/db/pg/pg-log-writer.mjs src/lib/admin/request-log.mjs src/lib/admin/routing-runtime.mjs test/unit/live-log-cache.test.mjs test/unit/pg-log-writer.test.mjs test/unit/log-realtime-merge.test.mjs test/unit/request-log.test.mjs test/unit/routing-runtime-load.test.mjs`: PASS (9 files, 0 errors, 0 warnings)
  - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS (0 syntax errors)
  - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci`: PASS (13/13 isolated test files, exit 0)
  - `node --test test/unit/live-log-cache.test.mjs test/unit/pg-log-writer.test.mjs test/unit/log-realtime-merge.test.mjs test/unit/request-log.test.mjs test/unit/gemini-request-log.test.mjs test/unit/routing-runtime-load.test.mjs test/unit/settings-routing-audit.test.mjs test/unit/routing-redaction-budget.test.mjs test/unit/usage-logs-view.test.mjs test/unit/request-logs-export.test.mjs test/unit/write-behind.test.mjs test/unit/panel-redis-opt.test.mjs`: PASS (189 pass, 0 fail, 1 skip without PG_URL)
  - WSL 临时 Docker `postgres:18-alpine` (`127.0.0.1:55439`, 跑完已清理) `VM2API_TEST_PG_URL=... node --test test/unit/pg-log-writer.test.mjs test/unit/pg-integration.test.mjs test/unit/pg-repos-parity.test.mjs`: PASS (22/22 pass, 0 fail, 0 skip)

## 回退与手破验证(Broken by hand)
- 临时关闭 `PgLogWriter._executeChannelTx` 中 `request_log_debug` 的 `useSavepoint: true` -> `PgLogWriter uses 1 client + 1 transaction per channel and isolates debug failure via SAVEPOINT` FAIL(`AssertionError: missing SAVEPOINT sp_debug / RELEASE SAVEPOINT sp_debug in single-tx sequence`)-> 恢复后 PASS。
- 临时把 `LiveLogCache._pruneLocalInflight` 的 `if (started >= cutoff) break` 退回全量扫描 -> `LiveLogCache L1/L2/L6/L9: omits sess:active, early-breaks inflight prune, strips jev_state, and single-flights/throttles reads` FAIL(`AssertionError: _pruneLocalInflight must break on first started >= cutoff instead of scanning full Map`)-> 恢复后 PASS。
- 临时绕过 `routing-runtime.mjs` 中 `persistRoutingPatch` 的 `persistQueue` 串行队列 -> `P4: persistRoutingPatch serializes concurrent patches in FIFO order and avoids mutating live routingConfig on failure` FAIL(`AssertionError: concurrent patch #2 must not interleave before patch #1 finishes`)-> 恢复后 PASS。

## 真实使用(Real use)
- 已在 WSL 本地一次性 `postgres:18-alpine` 容器上实跑 `pg-log-writer`(含真实 `UNNEST` 批量写、单事务 `SAVEPOINT`、窗口裁剪及 `request_attempts` `ctid` 清理)、`pg-integration`、`pg-repos-parity` 全通过(22/22 PASS,0 skip);未连生产机 `ph24`(沙箱禁区规则禁止)。

## 未运行项(Not run)
- 全仓 556 个单测与 E2E / Web 前端套件(本提交零改动 `web/`、Go、Rust 模块);生产机 `ph24` 线上实测(按安全红线禁止连接);`bench-20k` 20K 实压测(未改动 `verify-closed-loop.mjs` 契约,单测中 `waits for drain` 用例因 WSL 代理环境回环请求未配置 `NO_PROXY` 与本改动无关)。
@cursor

cursor Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 831a05e2-760e-4a52-8da5-f2ebce56e774)

@dofastted

Copy link
Copy Markdown
Owner Author

评审结果(Codex 只读评审合并最新 dev 后的树,head 70aa5907c;Node 内存模型与真实函数复现,PG 结论标注为静态推断)

结论:需修,暂不合并。 已转为草稿(gh pr ready 2458 即可恢复)。本 PR 没有新增 / 修改迁移,也没改迁移运行器,没有新增测试文件。

Major

  1. PG 停滞时内存队列无上限(真实函数复现):pg-log-writer.mjs:778 超过 maxPending 后仍无条件 push,只限制了连接并发,没有等待生产者、拒绝入口或有界溢出。输入 maxPending=3、batchSize=2、concurrency=2,让连接获取停滞,提交 10,000 条真实日志记录,25ms 后 pending=9996、activeChannels=2、overflowDirect=9997;解除停滞后全部排空,但持续停滞会耗尽内存。pg-log-writer.test.mjs:701 还把原来的 pending <= maxPending 断言删了,只检查连接并发,六条记录最终排空,不能证明持续慢库下的背压。
  2. debug 容量裁剪误删同时间戳记录(SQL 静态推断,未实测):pg-log-writer.mjs:1473 按 (ts DESC, request_id DESC) 累加却只返回 MAX(ts),:1484 随后删除全部 ts <= cutoff。a/b/c 三条同 ts、各 100 字节、预算 200 字节:窗口应保留两条,删除条件却覆盖三条,真实清理入口配 SQL 行为模型得到“删除 3 条、剩余 0 条”。应保留完整排序边界。pg-log-writer.test.mjs:1170 的真实 PG 用例没传 maxBytes(默认 0),根本不执行窗口裁剪,所以正文里“验证了窗口裁剪”没有被这个用例支撑。
  3. JSONL 镜像退出时不排空(启用 KIN_REQUEST_LOG_JSONL=1 时,真实 shutdown coordinator + 受控内存文件系统复现):request-log.mjs:1435 改成 Promise 串行链且不等待(:1408),server.mjs:2124 teardown 等 PG writer、write-behind、缓存,却不等镜像链;最后一批请求完成后收到 SIGTERM,退出回调发生时写入数为 0。链也没有长度上限。

Minor / 其它

  • live-cache 提前退出清理依赖 Map 插入顺序 = started_at 顺序(live-log-cache.mjs:362):先 startRequest('fresh', now) 再提交 started_at=now-600000 的请求,dev 返回 inflight=1、过期 session=0,PR 返回 inflight=2、过期 session=1;正常入口通常顺序调用,墙钟回拨或乱序才暴露。
  • recent 白名单移除了仍被详情读取的 jev_state(usage-logs-view.mjs:374 仍读它):带 jev_state、尚未落 PG 的完成记录会失去它。
  • 新增 1 秒列表缓存引入约 1 秒跨实例可见性延迟(live-log-cache.mjs:954,A 完成并 flush 后 B 仍返回 in_flight=true,真实等待 1050ms 后变 false);生产入口没有把它接成部署开关(cache/index.mjs:58)。
  • PG 断连后逐行回退失败仍只增加 dropped、不重入队(既有策略);跨实例续写缺口(request-log.mjs:1245 只看本实例队列)仍在;路由补丁 FIFO 只是每个 factory 内的队列(routing-runtime.mjs:575),不提供跨进程锁或版本比较,生产 setRoutingConfig 替换分支没有测试覆盖(server.mjs:485)。

已核对没问题的:debug savepoint 隔离(usage、attempt、debug 同批 debug 抛错时保留前两者;ok1/bad/ok2 回滚后保留 ok1/ok2,内存事务模型);同实例续写队列合并(duration 120+85=205ms);租户 PG 统计下推用户 / key / VM owner 条件,新增 SQL 没有 IFNULL / 独立 ? IS NULL;生产默认值(256 条 / 200ms / 20,000 pending / 并发 2)没被改,改变的是 pending 阈值的含义(队列外直写 → 继续积压)。

测试缺口:缺同 ts 不同 request_id 的反例、持续停消费但持续入队、父记录在另一实例、JSONL 未落盘即退出、路由队列第一项失败后第二项成功。两个原始定向测试在评审树里因缺 pg / ioredis 加载失败,没有计为通过。没能验证:真实 PG18 的 SQL、锁、断连、提交不确定性,真实 Redis,生产路由补丁与完整 SIGTERM 链路。

@dofastted
dofastted marked this pull request as draft December 1, 2026 14:19
…jsonl drain, and live-cache

## 变更摘要
- 改前:
  - `PgLogWriter._enqueueItem` 超过 `maxPending` 后仍无条件 `push`,PG 持续停滞时内存队列无上限增长(Major 1)。
  - `runRetentionCleanupAsync` 的 debug 容量裁剪 `DEBUG_SIZE_CUTOFF_SQL` 只取 `MAX(ts)` 并按 `WHERE ts <= $1` 删除,同时间戳多条记录会被整批误删(Major 2)。
  - `RequestLogStore._appendJsonl` 改异步 Promise 链后既无队列上限,也无排空接口且 `server.mjs` graceful shutdown 未等待其落盘(Major 3)。
  - `LiveLogCache._pruneLocalInflight` 遇首条未过期即 `break` 假设插入序恒等于 `started_at` 序,乱序或墙钟回拨时漏清过期记录及 session 并发(Minor 1)。
  - `LiveLogCache.formatRecentEntry` 移除了 `usage-logs-view.mjs` 详情仍读取的 `jev_state`(Minor 2);1s 列表缓存未在 `cache/index.mjs` 接出部署开关(Minor 3)。
- 改后:
  - `src/lib/db/pg/pg-log-writer.mjs`:触及 `maxPending` 时先同步派发空闲并发通道吸收突刺;通道全满且队列满时优先淘汰 `_debugQueue` 低优记录,仍满则拒绝入队并节流告警,保证任意时刻 `pending() <= maxPending` 且 `activeChannels <= concurrency`。debug 容量裁剪改用 `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` 取复合边界 `(cutoff_ts, cutoff_request_id)`,按 `ts < $1 OR (ts = $1 AND request_id <= $2)` 精确 `ctid` 分批删除。
  - `src/lib/admin/request-log.mjs` & `src/server.mjs`:JSONL 镜像改为有界批量队列(默认 `jsonlMaxPending=10000`,超限计 `_jsonlDropped`)+ 单循环 `_drainJsonlQueue`,新增 `flushJsonl()` / `close()` 并在 `server.mjs` gracefulShutdown teardown(`flushWrites()` 后)等待其排空。
  - `src/lib/cache/live-log-cache.mjs`、`src/lib/db/pg/config.mjs`、`src/lib/cache/index.mjs`:`_pruneLocalInflight` 增加 `_lastInflightStartedAt` / `_inflightOrderDirty` 监测,单调时保持 O(expired) 快速路径、乱序/回拨时自动退回全表清理并恢复;`formatRecentEntry` 保留非空 `jev_state`(上限 4096 字符防 64KB 膨胀,落 PG 后覆盖为完整行);`resolveCacheConfig` 新增 `VM2API_LIVE_LIST_CACHE_TTL_MS`(默认 1000,支持 0 关闭)并透传 `cache/index.mjs`。
  - 在 5 个已有单测文件补齐回归用例(零新增测试文件):PG 持续停滞硬上限背压、真 PG18 同 `ts` `a/b/c` 窗口裁剪、JSONL 关机排空与慢盘队列上限、父记录离队回退 DB 续写合并、live-cache 乱序清理/jevState/跨实例开关、路由队列首项失败后次项成功及 `setRoutingConfig` 替换分支。
- 未改 / 延后:跨实例续写延迟合并与 PG 逐行回退丢弃属既有策略边界;路由写单 leader 架构由 `server.mjs` standby/draining 拦截,本次不扩展跨进程锁。

## 验收记录(Run)
- 环境与基线:Windows + WSL2 Debian Node v24.13.0,基于 `origin/fix/r3-log-rw-backpressure` (`70aa5907c`) 在独立工作树 `X:\vm2api-wt-fix-pr2458` 追加提交。
- 已跑命令与结果:
  - `npx biome check src/lib/db/pg/pg-log-writer.mjs src/lib/admin/request-log.mjs src/server.mjs src/lib/cache/live-log-cache.mjs src/lib/db/pg/config.mjs src/lib/cache/index.mjs test/unit/pg-log-writer.test.mjs test/unit/request-log.test.mjs test/unit/live-log-cache.test.mjs test/unit/routing-runtime-load.test.mjs test/unit/log-realtime-merge.test.mjs`: PASS (11 files, 0 errors, 0 warnings)
  - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS (0 syntax errors)
  - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci`: PASS (13/13 isolated test files, exit 0)
  - `node --test test/unit/live-log-cache.test.mjs test/unit/pg-log-writer.test.mjs test/unit/log-realtime-merge.test.mjs test/unit/request-log.test.mjs test/unit/gemini-request-log.test.mjs test/unit/routing-runtime-load.test.mjs test/unit/settings-routing-audit.test.mjs test/unit/routing-redaction-budget.test.mjs test/unit/usage-logs-view.test.mjs`: PASS (202 pass, 0 fail, 1 skip without PG_URL)
  - WSL 临时 Docker `postgres:18-alpine` (`127.0.0.1:55446`, 跑完已 `docker rm -f`) + `redis:8-alpine` (`127.0.0.1:56393`, 跑完已 `docker rm -f`) `VM2API_TEST_PG_URL=... VM2API_TEST_REDIS_URL=... node --test test/unit/pg-log-writer.test.mjs test/unit/pg-integration.test.mjs test/unit/pg-repos-parity.test.mjs test/unit/pg-redis-cache-e2e.test.mjs test/unit/sqlite-to-pg-migration.test.mjs`: PASS (31/31 pass, 0 fail, 0 skip)

## 回退与手破验证(Broken by hand)
- 临时移除 `PgLogWriter._enqueueItem` 满队列拒绝 `return false` -> `PgLogWriter enforces hard maxPending bound under burst and sustained PG stall while shedding debug first` FAIL(`AssertionError [ERR_ASSERTION]: under sustained PG stall, pending (4) must stay <= maxPending (3)`)-> 恢复后 PASS。
- 临时移除 `RequestLogStore.close()` 中 `await this.flushJsonl()` -> `jsonl mirror writes legacy format asynchronously, creates directory once, drains on close, and bounds queue` FAIL(`AssertionError [ERR_ASSERTION]: store.close() must wait for pending JSONL writes before exit`)-> 恢复后 PASS。

## 真实使用(Real use)
- 已在 WSL 真实 `postgres:18-alpine` + `redis:8-alpine` 容器上实跑 `pg-log-writer`(含真实 PG18 同 `ts` `same_ts_a/b/c` `maxBytes=200` 窗口裁剪验证)、`pg-integration`、`pg-repos-parity`、`pg-redis-cache-e2e`、`sqlite-to-pg-migration` 全通过(31/31 PASS,0 skip);未连生产机 `ph24`(安全红线禁止)。

## 未运行项(Not run)
- 全仓 556 个单测与 `web/` 前端套件(本提交零改动 `web/`、Go、Rust 模块);生产机 `ph24` 线上实测(按安全红线禁止连接)。
@dofastted

Copy link
Copy Markdown
Owner Author

已根据评审意见在 fix/r3-log-rw-backpressure 上追加根因修复提交 4dc75413549d86efb23901f340b7af058b8ffb28(零改写历史、零新建测试文件),逐条处置如下:

  1. Major 1 — PG 停滞时 PgLogWriter 内存队列无上限:已修。src/lib/db/pg/pg-log-writer.mjs 触及 maxPending 时先同步派发空闲并发通道吸收突刺;若通道全满仍触顶,优先淘汰低优 _debugQueue,仍满则拒绝入队并节流告警,保证 pending() <= maxPending 与 activeChannels <= concurrency 恒成立。已恢复 pending <= maxPending 断言并补 500 条持续停滞 + 恢复回归测试。
  2. Major 2 — debug 容量裁剪误删同时间戳记录:已修。DEBUG_SIZE_CUTOFF_SQL 改用 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 取复合边界 (cutoff_ts, cutoff_request_id),删除条件改为 WHERE ts < $1 OR (ts = $1 AND request_id <= $2)。已在 mock 与真实 PostgreSQL 18 用例中均补齐同 ts(a/b/c 各 100B、预算 200B 精确删 a 留 b/c)实测。
  3. Major 3 — JSONL 镜像退出时不排空且链无上限:已修。src/lib/admin/request-log.mjs 改为有界批量队列(默认 jsonlMaxPending=10000)+ 单循环 drain,新增 flushJsonl() / close() 并在 src/server.mjs gracefulShutdown teardown(flushWrites() 之后)等待其落盘。已补慢盘队列上限与 close() 排空回归测试。
  4. Minor 1 — _pruneLocalInflight 乱序 / 墙钟回拨漏清:已修。src/lib/cache/live-log-cache.mjs 增加 _lastInflightStartedAt / _inflightOrderDirty,单调时保持 O(expired) 快速路径,遇乱序或回拨自动全扫并释放 _localSessionConc 后自动恢复。已补先 fresh 后 now-600000 回归用例。
  5. Minor 2 — recent 白名单移除 jev_state:已修。formatRecentEntry 保留非空 jev_state(上限 4096 字符防 64KB 膨胀,落 PG 后由 PG 完整行覆盖),继续剔除列表/详情未读的 advisor_usage/image_usage。已在 live-log-cache 与 log-realtime-merge 补齐未落 PG recent 记录保留 jevState 用例。
  6. Minor 3 — 1 秒列表缓存缺部署开关:已修。src/lib/db/pg/config.mjs resolveCacheConfig 新增 VM2API_LIVE_LIST_CACHE_TTL_MS(默认 1000,支持 0 关闭实现跨实例零延迟)并透传 src/lib/cache/index.mjs。已补 listCacheTtlMs=0 跨实例零延迟用例。
  7. 测试缺口与既有边界:已补 routing-runtime-load 队列首项失败后次项成功及生产 setRoutingConfig 替换分支用例、以及 request-log 父记录不在本实例队列回退 flush() + DB merge 用例;PG 逐行回退不重入队、跨实例续写延迟合并与单 leader 路由写入均属既有架构边界,本次保持不变。

验证汇总(HEAD 4dc75413549d86efb23901f340b7af058b8ffb28):Biome check 11 files PASS、node --check PASS、npm run test:ci 13/13 PASS、9 项关联单测 202/202 PASS、真实 Docker postgres:18-alpine + redis:8-alpine(pg-log-writer / pg-integration / pg-repos-parity / pg-redis-cache-e2e / sqlite-to-pg-migration)31/31 PASS(0 skip)、2 处真实手破验证均确认红转绿。

@dofastted

Copy link
Copy Markdown
Owner Author

复验通过(head 4dc75413549d86efb23901f340b7af058b8ffb28,与最新 origin/dev aa224e150 及 #2456 均 merge-tree 零冲突),准备转为 Ready(暂不合并)。

变更摘要

  • 改前:前轮评审指出 3 项 Major(Major 1 PG 停滞时 PgLogWriter 内存队列无硬上限、Major 2 debug 容量裁剪按 ts <= cutoff 误删同时间戳记录、Major 3 JSONL 镜像链无长度上限且退出时不排空)及 3 项 Minor(_pruneLocalInflight 乱序/墙钟回拨漏清、recent 白名单移除了详情仍读的 jev_state、1 秒列表缓存缺少部署开关)。
  • 改后:逐条核对提交 4dc754135 源码与测试,Major 1–3 与 Minor 1–3 全部根因闭环:PgLogWriter._enqueueItem 在 maxPending 触顶先同步派发空闲通道再优先淘汰 debug 并拒收超限行、DEBUG_SIZE_CUTOFF_SQL 与 CTID_DELETE_DEBUG_UP_TO_CUTOFF_SQL 改用 (ts, request_id) 复合边界、RequestLogStore 改有界队列并在 server.mjs gracefulShutdown 调用 requestLog.close() 排空、LiveLogCache 补 _inflightOrderDirty 全扫兜底与有界 jev_state(4096 字符,且核对 usage-logs-view.mjs 直接透传字符串不做 JSON.parse)及 VM2API_LIVE_LIST_CACHE_TTL_MS 开关。
  • 未改 / 延后:既有架构边界(PG 逐行回退失败不重入队、跨实例续写延迟合并、单 leader 路由写入)保持不变。

验收记录(Run)

  • 环境与基线:Windows + WSL2 Debian Node v24.13.0 + Docker (postgres:18-alpine, redis:8-alpine);独立验证工作树 X:/vm2api-wt-verify-2458,head 4dc75413549d86efb23901f340b7af058b8ffb28,git merge-tree --write-tree origin/dev origin/fix/r3-log-rw-backpressure(origin/dev aa224e150)退出码 0(零冲突)。
  • 已跑命令与结果:
    • find src scripts -name "*.mjs" -print0 | xargs -0 -n1 node --check: PASS (0 syntax errors)
    • npx biome check <12 changed .mjs files>: PASS (12 files, 0 errors)
    • KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-gemini-format-parity/bin/kin-scheduler VM2API_TEST_CONCURRENCY=4 npm run test:ci: PASS (13/13 files, 0 fail)
    • VM2API_TEST_CONCURRENCY=4 npm run test:unit -- live-log-cache log-realtime-merge pg-log-writer request-log routing-runtime-load: PASS (5/5 files: 7+13+18+68+25 = 131 passed, 0 fail, 1 live-PG skip in offline pass)
    • VM2API_TEST_PG_URL=...55436/vm2api VM2API_TEST_REDIS_URL=...56386/0 npm run test:unit -- pg-log-writer pg-integration pg-repos-parity pg-redis-cache-e2e sqlite-to-pg-migration: PASS (5/5 files: 19+1+2+4+5 = 31/31 tests, 0 fail, 0 skip)
    • GitHub Actions 远端检查:changes PASS、ci PASS

回退与手破验证(Broken by hand)

  • Major 1:临时禁用 src/lib/db/pg/pg-log-writer.mjs maxPending 超限淘汰/拒收分支 -> node --test test/unit/pg-log-writer.test.mjs 的 PgLogWriter enforces hard maxPending bound under burst and sustained PG stall while shedding debug first 真实 FAIL(AssertionError: under sustained PG stall, pending (4) must stay <= maxPending (3))-> 恢复后 PASS
  • Major 2:临时将 src/lib/db/pg/pg-log-writer.mjs CTID_DELETE_DEBUG_UP_TO_CUTOFF_SQL 回退为 WHERE ts <= $1 -> node --test test/unit/pg-log-writer.test.mjs 的 runRetentionCleanupAsync performs ctid batched archive+delete, monotonic pruned_through, debug age+size trim, and advisory lock 真实 FAIL -> 恢复后 18/18 PASS
  • Major 3:临时跳过 src/lib/admin/request-log.mjs RequestLogStore.close() 中的 await this.flushJsonl() -> node --test test/unit/request-log.test.mjs 的 jsonl mirror writes legacy format asynchronously, creates directory once, drains on close, and bounds queue 真实 FAIL(AssertionError: store.close() must wait for pending JSONL writes before exit)-> 恢复后 68/68 PASS
  • Minor 1:临时禁用 src/lib/cache/live-log-cache.mjs _inflightOrderDirty 全扫分支 -> node --test test/unit/live-log-cache.test.mjs 的 LiveLogCache L1/L2/L6/L9 真实 FAIL(AssertionError: out-of-order expired entry must be pruned, not stranded behind fresh)-> 恢复后 7/7 PASS

真实使用(Real use)

  • 在 WSL 临时 postgres:18-alpine(55436)+ redis:8-alpine(56386)容器上实测 pg-log-writer(含真 PG18 同 ts 复合边界容量裁剪与 UNNEST 写入)、pg-integration、pg-repos-parity、pg-redis-cache-e2e 与 sqlite-to-pg-migration,31/31 全绿无 skip,临时容器已 docker rm -f 销毁;未触碰线上 ph24。

未运行项(Not run)

  • 未运行全量 556 个后端单测、web/ 前端测试与构建(本 PR 未改 web/)、Go/Rust 构建及线上 ph24 实测。

@dofastted
dofastted marked this pull request as ready for review December 1, 2026 16:38
@dofastted

Copy link
Copy Markdown
Owner Author

复核结果(head 4dc754135;真 PG18 / Redis 8 一次性容器上复核,合入当时的 origin/dev c83c12b3b)

结论:我之前的 3 条 Major 都已修,但合入当前 dev(含 #2474 的 captcha solver)后出现一处语义冲突,暂不合并,已转为草稿。

已修:Major 1(PG 停滞时队列无界)→ 同一输入 10,000 条,现在 pending=3、活动连接 ≤2、dropped=9994,overflow_drop 告警节流为 1 次(代价是持续停滞时会丢日志而不是占满内存,请在发版说明里写明);Major 2(debug 裁剪误删同时间戳)→ 真 PG18 上 a/b/c 同 ts 各 100B 预算 200B,base 剩 0 条,PR 剩 b,c;150 组随机(大量相同时间戳)base 81 组与模型不符,PR 0 组;Major 3(JSONL 退出不排空)→ RequestLogStore.close() 已加且队列上限 10,000,server.mjs:2134 在 flushWrites() 之后、closeCacheRuntime() 之前调用。其余 Minor(live-cache 乱序、jev_state、1 秒列表缓存可配、路由队列 FIFO)也已处理。

阻断(已复现):文本无冲突,但 src/lib/admin/routing-runtime.mjs:705 的 routingConfig.oauth = {…}(#2474 新增的 captcha_solver 分支)落进了你重写后的 persistRoutingPatch,而 routingConfig 在同函数 747 行才声明 → ReferenceError: Cannot access 'routingConfig' before initialization,PUT /api/panel/routing 带 oauth.captcha_solver 返回 503 routing_persist_failed。routing-runtime-load(“persistRoutingPatch stores captcha solver secrets privately…”)与 settings-routing-audit(“panel routing GET/PUT redact captcha client_key…”)在 dev 上 24/24、9/9,合入后各红 1 个;它们不在 test:ci,所以 CI 看不到。正确改法是让该分支写 draft.oauth(并保证 captcha 密钥的私有存储走 draft),而不是写活对象,否则也违背本 PR “落盘成功前不改活配置”的目标。请合入最新 dev 后修,并对 routing-runtime-load、settings-routing-audit、routing-redaction-budget 整批跑一遍。

还要补:去掉 server.mjs 里的 requestLog.close() 调用后,所有相关测试仍全绿——这条退出排空的接线没有用例保护;PR 正文还写着 “formatRecentEntry 剔除 jev_state”,与现行为(保留并截断到 4096 字符)不符,请更新。没有验证到的:真实 server 的 SIGTERM 全链路。

@dofastted
dofastted marked this pull request as draft December 1, 2026 17:41
@dofastted

Copy link
Copy Markdown
Owner Author

1. 本次改动与原因(Head $sha)

已合入最新 origin/dev 并修复复核阻断项及补齐测试:

  • 阻断项(
    outing-runtime.mjs:705 TDZ ReferenceError)
    :test(oauth): follow the publicRoutingNotify→publicRoutingConfig rename in notify and panel-route-coverage tests (takes over #2463) #2474 新增的 �ody.oauth.captcha_solver 分支此前写入未声明的
    outingConfig.oauth,现改为写入 draft.oauth(mergeCaptchaSolverConfig(draft.oauth?.captcha_solver, body.oauth.captcha_solver)),彻底消除 Cannot access 'routingConfig' before initialization 并坚持“落盘成功前不改活配置”。
  • 补齐关停排空护栏测试:在 est/unit/request-log.test.mjs 新增用例断言 src/server.mjs 关停流程在 lushWrites() 之后、closeCacheRuntime() 之前调用
    equestLog?.close?.()。
  • 说明更正: ormatRecentEntry 现行为是保留 jev_state 并截断至 4096 字符(非剔除);PG 持续停滞场景下日志队列按 maxPending 丢弃新日志以防 OOM,后续发版说明中将注明。

2. 已执行验证与结果

px biome check src/lib/admin/routing-runtime.mjs test/unit/request-log.test.mjs — 0 fixes

ode --test test/unit/routing-redaction-budget.test.mjs test/unit/routing-runtime-load.test.mjs test/unit/settings-routing-audit.test.mjs test/unit/request-log.test.mjs — 105/105 PASS(0 fail)

  • KIN_SCHEDULER_BIN=/tmp/kin-sched-target/release/kin-scheduler npm run test:ci — 13/13 PASS

3. 破坏性验证(Broken-by-hand)

  • 合入 origin/dev 后修复前,
    outingConfig.oauth 触发 ReferenceError: Cannot access 'routingConfig' before initialization 导致
    outing-runtime-load 与 settings-routing-audit 失败;改为 draft.oauth 后全绿。

4. 未运行项

  • 未连生产机 ph24,未做真实 server 进程 SIGTERM 全链路压测。

5. 风险与回滚

  • 仅改 3 行 draft.oauth 与 1 条单测断言;单提交可回滚。

@dofastted
dofastted marked this pull request as ready for review December 1, 2026 17:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant