Skip to content

分批预览和清理过期旧版日志正文 - #316

Merged
1034674309 merged 2 commits into
mainfrom
codex/282-legacy-log-retention
Nov 19, 2026
Merged

1034674309 merged 2 commits into
mainfrom
codex/282-legacy-log-retention

Conversation

@1034674309

Copy link
Copy Markdown
Collaborator

改动

新增独立的 log-body-retention 运维命令。按用量事件主键逐批检查 request_logs 中至少 30 天前的旧正文,默认在只读事务中统计。显式执行后清除请求、响应和代理请求副本,保留有界错误摘要。新版独立正文按各条自身的到期时间保留。

  • 单批最多检查 500 条用量事件。写入失败时整批回滚,原游标可重试。并发锁等待有上限。
  • 上游诊断保留状态、用量及其他字段。较大或不识别的诊断保留供单独核查,并汇总计数。
  • 日志详情沿用双语的「正文已到期」状态。保留真实费用、用量、用户权限和续聊历史。
  • 逻辑正文大小用于估算;磁盘实际归还取决于 PostgreSQL 的空间复用、WAL 和备份轮换。运维手册说明分批核对步骤。

只读试算

通过环境变量 XHUB_DATABASE_URL 提供只读连接,并将 RETENTION_CUTOFF 设为固定的 RFC 3339 时间。

go run ./cmd/log-body-retention --before="$RETENTION_CUTOFF" --limit=100

按每批 JSON 结果中的 next 续跑。实施现场的配置、命中范围、WAL 与可用磁盘需在执行前复核。

验证

  • Go -race 42 个测试和子测试通过,go vet 通过。
  • 真实 HTTP 和隔离 PostgreSQL regression 5 项通过,0 跳过,包含并发重试、期限边界、用量、错误摘要、续聊和越权。
  • 真实中英文浏览器用例 2/2。创建请求并将其中一条恢复为旧日志格式,经运维命令清理后确认页面展示到期、费用未变、近期正文仍可访问。隔离资源清理通过。
  • 网站 53 项测试、相关 ESLint、git diff --check 通过。第一次生产前端构建受到现有 Next.js 版本更新提示中断,重跑完成验收。

关联 #282。部署、生产清理和保留配置核对另行验收。

@xgrowthlab-codecov

xgrowthlab-codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.11765% with 42 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/log-body-retention/main.go 38.23% 20 Missing and 1 partial ⚠️
internal/gateway/requestlog/retention.go 79.41% 12 Missing and 9 partials ⚠️

Impacted file tree graph

@@           Coverage Diff            @@
##             main     #316    +/-   ##
========================================
  Coverage   69.72%   69.73%            
========================================
  Files        1403     1405     +2     
  Lines       79567    79703   +136     
  Branches    12207    12207            
========================================
+ Hits        55481    55577    +96     
- Misses      17665    17696    +31     
- Partials     6421     6430     +9     
Flag Coverage Δ
backend 73.44% <69.11%> (-0.01%) ⬇️
frontend 65.99% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/log-body-retention/main.go 38.23% <38.23%> (ø)
internal/gateway/requestlog/retention.go 79.41% <79.41%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@1034674309
1034674309 marked this pull request as ready for review November 19, 2026 12:02

@fennoai fennoai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

总体评价

批次边界、只读试算、FOR UPDATE 加 lock_timeout 的整批回滚,以及 DSN 和错误输出的处理整体都是正确的,SQL 全部使用绑定参数。需要关注的主要有两点:

  • 未处理的诊断在行被标记 expired 后无法再定位,但其中可能仍有私有数据;
  • 诊断 error 的规范化会丢失信息,而且重复执行时结果不稳定。

详见行内评论。

其他建议(无法放在行内)

  • 文档中英文不一致:zh 第 3 行多了“管理员曾开启正文记录时”这一前提;zh 第 17 行说明字节量“不能当作文件系统回收量”,en 版缺少这句提醒;docs/user-guide.zh-CN.md 只写了“请求与响应正文”,实际还包括代理请求和旧 error 列。
  • 残留数据范围:清理只改写诊断中顶层的 error。旧数据里的 headers/trailers、read_error 等字段可能保留未脱敏的内容。建议在手册中列为已知残留,或者在清理时一并调用 diagnosticHeaders 处理。
  • 安全下限只在 CLI 中校验:ProcessLegacyLogBatch 是导出函数,但 30 天下限只在 main.go 里检查。建议在函数注释中写明这个前置条件,或者把 now 传进去,在库内校验。

for _, row := range updates {
change, err := tx.ExecContext(ctx, `UPDATE request_logs
SET request_body = '', response_body = '', proxy_request = '', error = $2,
body_capture_status = CASE WHEN $5 THEN 'expired' ELSE body_capture_status END,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 未处理的诊断在标记 expired 后就无法再找到

如果一行既有旧正文,upstream_response 又超过 64 KiB 或无法解析(例如回归测试里的 ids[2]),这里只把它计入一次 UnchangedDiagnostics,但同时把 body_capture_status 写成 'expired'。之后所有扫描都按 body_capture_status = ''(第 55 行)过滤,这行不会再被检查或计数,命令输出里也没有任何行标识。

结果是:最可能残留供应商原始正文的大型或旧格式诊断,在页面上显示为“已到期清理”,实际数据却还在。文档里“计入 unchanged_diagnostics 留待单独核查”的承诺,只在第一次 --execute 时成立。

建议三选一:诊断未处理时不标记 expired(或改用单独的状态);在输出中给出这些行的 usage_events.id;或者在运维手册中提供可复用的定位 SQL(例如 body_capture_status='expired' AND octet_length(upstream_response) > 65536)。

if !exists || string(source) == "null" {
return "", false, true
}
summary := FailureSummary(string(source))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 诊断中 error 为字符串时,原始信息会被丢掉

以 {"status_code":502,"error":"upstream timeout"} 为例,FailureSummary("\"upstream timeout\"") 解析出的是 JSON 字符串而不是对象,因此返回 "upstream error details unavailable"。随后这段代码把它包装成 {"error":{"message":"upstream error details unavailable"}},原本可用于排障的文本就永久丢失了。error 为数字、布尔值,或是不含任何白名单键的对象时,结果也一样。这类行能命中 strpos(upstream_response, '"error":'),所以确实会被改写。

建议:error 不是对象时,先解码成字符串,再交给 shortErrorText 处理(它本身会做脱敏和截断)。

}
summary = string(encoded)
}
if summary == string(source) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] 规范化结果不稳定,重复执行会反复改写

当摘要超过 16 KiB 时,FailureSummary 会回退为 {"truncated":true,"error":{…}}。但 truncated 不在顶层白名单里,下一轮会变成 {"error":{…}},和已存的值不同,于是 replace 又为 true。如果 error 不是 map,回退值 {"truncated":true} 还会再变成 unavailable 并被包装一层。

对仅含诊断的行(状态保持 ''),文档建议的“从零再跑一轮”会重复把它们计入 eligible 并改写,截断标记也会丢失。建议把 truncated 视为已规范化的形态,并补一条超过 16 KiB 的稳定性测试。

ELSE 'upstream error details exceed the summary limit' END AS error_summary_source,
CASE WHEN octet_length(upstream_response) <= 65536 THEN upstream_response ELSE '' END AS diagnostic,
octet_length(upstream_response) > 65536 AS diagnostic_too_large,
(request_body <> '' OR response_body <> '' OR proxy_request <> '' OR error <> '') AS has_legacy_body

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] 只有旧 error 的行也会被标记为 expired

has_legacy_body 包含 error <> '',所以从未保存过请求或响应正文、只有网关错误的旧记录,也会被写成 'expired'。页面因此显示“正文已到期清理”,但这条请求其实从未记录过正文。同时它被计入 eligible,对 legacy_body_bytes 的贡献却是 0。

建议只在三个正文列中有非空值时才标记 expired;只有 error 的行只重新生成摘要。如果保留现有行为,也请在文档的“哪些字段会变”一节说明。

// 先由主键限定检查范围,再按请求时间查正文。即使旧正文稀疏,每批也不扫描整张日志或账单表。
// 锁繁忙时回滚整批而不跳过行,避免游标前移导致未清理记录被遗漏。
query := `WITH page AS MATERIALIZED (
SELECT id, request_id, ts FROM usage_events WHERE id > $1 ORDER BY id LIMIT $2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] 游标会遍历整张 usage_events,包括截止时间之后的行

page CTE 没有时间条件,p.ts <= $3 只在 LATERAL 里生效。截止时间之后的新行同样占用每批的 500 条名额,done 要一直走到表的实时末尾才会为 true。而每批都是一次独立的 go run 进程,大表需要成千上万次启动,文档建议的第二轮又要全部重来一遍。

建议在 ts 明显超过截止时间后提前结束(id 和 ts 大体同步递增),或者提供在一个连接内连续执行多批的选项(如 --max-batches / --sleep),并在文档中改用编译好的二进制。

}
cancelCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if blocked, err := requestlog.ProcessLegacyLogBatch(cancelCtx, db, cutoff, 0, 10, true); err == nil || blocked.Next != 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] blocked.Next != 0 这个断言永远不会失败

ProcessLegacyLogBatch 出错时总是返回 LegacyRetentionBatch{},所以 Next 必然是 0,“游标未前移”这一点实际上没有被验证。

建议改为检查:失败后 ids[0] 等锁前的行仍然保留 private-input;错误是锁超时(SQLSTATE 55P03),而不是其他原因。

return json.Marshal(batch)
}

// main 把标准输入环境和命令行参数交给 run;失败以非零退出码退出,便于维护脚本暂停后续批次。

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] 注释与实现不符

main 并不读取标准输入,它传给 run 的是 os.Args[1:]、XHUB_DATABASE_URL 和 time.Now()。建议改为“把命令行参数、XHUB_DATABASE_URL 和当前时间交给 run”。

@1034674309
1034674309 merged commit f1a102b into main Nov 19, 2026
15 checks passed
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