Skip to content

支持按已鉴权账号灰度写入压缩续聊历史 - #319

Merged
1034674309 merged 6 commits into
mainfrom
codex/compact-history-account-canary
Nov 19, 2026
Merged

1034674309 merged 6 commits into
mainfrom
codex/compact-history-account-canary

Conversation

@1034674309

Copy link
Copy Markdown
Collaborator

变更

统一 Responses 的续聊压缩写入现在可以按已鉴权账号灰度。使用 XHUB_COMPACT_HISTORY=canary 和逗号分隔的 XHUB_COMPACT_HISTORY_USER_IDS,控制台会话和个人 API Key 都按真实用户 ID 匹配。名单缺失或为空时继续写旧格式,1 保留已有全量模式。切回 0 后,后续请求写旧格式,已生成的压缩历史仍可续接。

先让所有网关使用支持两种格式的二进制,再配置试点账号。读路径、DDL、计费、权限、保留期与历史迁移均沿用当前实现。更新了中英文存储运维文档。

验证

  • 主分支 e78b75f5 上的定向单元与真实 HTTP/PostgreSQL 回归 40 项通过,0 失败或跳过。覆盖名单内外、伪造请求身份、跨账号拒绝、关闭后的压缩父历史及 SSE 续接。
  • affinity、store、dataplane 和迁移命令相关 Go 测试 702 个测试及子测试通过,0 失败,2 个外部供应商用例因缺少联调配置跳过。
  • 中英文浏览器灰度 2/2 通过,核对控制台账号的 JSON/SSE 续聊及实际写入格式,临时数据库清理通过。
  • 本地专用 PostgreSQL 16 三轮 30 次增长历史对照。WAL 中值 4,102,704 B → 190,104 B,相关物理表增长含 TOAST 和索引 4,046,848 B → 294,912 B,末轮暖机后读取 P95 0.594 ms → 3.295 ms。固定合成用例的结果用于决定灰度观察项,线上供应商、高并发和生产容量仍需实测。

Refs #315, #266.

@xgrowthlab-codecov

xgrowthlab-codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Impacted file tree graph

@@           Coverage Diff           @@
##             main     #319   +/-   ##
=======================================
  Coverage   69.74%   69.74%           
=======================================
  Files        1405     1405           
  Lines       79703    79723   +20     
  Branches    12207    12207           
=======================================
+ Hits        55587    55605   +18     
- Misses      17682    17687    +5     
+ Partials     6434     6431    -3     
Flag Coverage Δ
backend 73.47% <100.00%> (+0.02%) ⬆️
frontend 66.00% <ø> (-0.02%) ⬇️

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

Files with missing lines Coverage Δ
internal/gateway/affinity/cache.go 95.60% <100.00%> (ø)
internal/gateway/affinity/durable.go 100.00% <100.00%> (ø)
internal/gateway/affinity/route.go 81.77% <100.00%> (+0.19%) ⬆️
internal/store/compact_history.go 70.12% <100.00%> (ø)

... and 4 files 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.

@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.

整体实现质量不错:写入格式的决策收敛到单个纯函数,RoutePlan.CompactHistory 从 PlanRoute 到 commitRoute 传播完整,读侧始终双格式兼容、manifest 未命中才回退 kv,回退方向在同事务内删除同键索引,身份来源是 auth.Principal.UserID(来自密钥/会话行,正文 user 字段无法影响),名单比较是 TrimSpace 后的精确相等而非前缀匹配。compact == false 的默认写路径与改动前一致,没有引入额外开销。

主要问题集中在测试的实际证明力:新增的 e2e 用例在仓库默认 CI 配置下根本走不到 canary 分支,灰度的核心语义(名单命中/未命中按账号分叉)在浏览器层未被验证;Go 侧也缺少 CompactHistory 传播到 cacheWriteHistory 的单测保护。其次是开关取值的精确匹配语义与文档未提示的两处运维陷阱。

优先级:P2 三条(e2e 灰度分支空转、e2e 改主键夹具、开关解析与文档语义)、P3 四条。

userID = fixed;

const [compact, legacy] = historyCounts();
const mode = process.env.XHUB_COMPACT_HISTORY;

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] e2e 用例的 canary 分支在默认 CI 下永不执行

scripts/e2e.sh:26 只导出 XHUB_COMPACT_HISTORY=${XHUB_COMPACT_HISTORY:-1},仓库内没有任何地方设置 XHUB_COMPACT_HISTORY_USER_IDS。因此默认运行时 mode === "1",expectedCompact 与 outsiderCompact 恒为 true,allowlist 计算、UPDATE users SET id 与 fixed 全部是死代码,灰度名单命中的分叉语义在浏览器层一次也不会被验证——compactHistoryAllowed 即使退化成无条件 return true,本用例依然通过。

另外期望值由测试进程自身的 env 推导,与网关读取的是同一份配置,因此也只能验证"写入格式随开关变化",无法区分"名单命中"与"全局 1"。

建议在 scripts/e2e.sh 提供显式分支(例如 E2E_COMPACT_CANARY=1 时导出 XHUB_COMPACT_HISTORY=canary 与包含 history-canary-en、history-canary-zh-cn 的名单),并让用例在开头断言该前置成立、否则 test.skip,这样灰度路径才真正进入 CI。

let userID = (await created.json()).user_id;
expect(userID).toMatch(/^[0-9a-f-]+$/);
try {
expect(runCanarySQL(`UPDATE users SET id='${fixed}' WHERE id='${userID}' AND lower(email)='${email}' RETURNING id;`)).toBe(fixed);

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] 用 UPDATE 改写 users 主键,依赖"尚无子行"这一偶然前提

internal/iam/schema.sql 中 api_keys.user_id(:143)、team_members.user_id(:118)、organization_members.user_id(:109)、personal_log_preferences.user_id(:265) 都 REFERENCES users(id) ON DELETE CASCADE,但没有 ON UPDATE CASCADE。当前能通过仅因为新建用户还没有产生任何子行;一旦夹具后续给它建密钥、加入团队或写入日志偏好,这条 UPDATE 会直接报外键错误。

若要固定 ID 来喂名单,更稳妥的做法是让名单成为可运行时调整的配置(可参考 NativeResponsesAllowed 的做法:internal/gateway/native_responses.go + internal/config/native_responses.go,走 general_settings 而非环境变量),或让创建接口支持指定用户 ID,而不是事后改主键。

Comment thread internal/gateway/affinity/durable.go Outdated
// 值 1 保留原有全量模式;canary 只接受明确列出的身份,名单缺失或为空时写旧格式。
// 只按可信用户 ID 比较,个人 Key 与会话均可命中,匿名、主密钥和缺少用户归属的密钥不能命中名单。
func compactHistoryAllowed(p *auth.Principal) bool {
switch os.Getenv("XHUB_COMPACT_HISTORY") {

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] 开关取值精确匹配不 trim,未知值静默关闭;名单仅在 canary 下读取

switch os.Getenv(...) 是精确匹配且不做 TrimSpace,而同函数第 42 行对名单项做了 TrimSpace——同一处配置里一个宽松一个严格。canary (尾部空格,从文档复制或 Compose 环境里很常见)、Canary、TRUE、yes 都会静默退回旧格式,既没有日志也没有启动错误,与仓库 docs/development/en/configuration.md 明示的"非法值阻止启动"风格不一致。

另外 case "1": return true 在读取名单之前就返回,所以运维同时设置 XHUB_COMPACT_HISTORY=1 与一份名单时,名单被静默忽略、所有调用方都写新格式,这与"只想灰度这几个人"的直觉相反。

建议对开关值同样 TrimSpace,并对未识别取值记录一次告警(或启动即失败);同时把"1 表示全量、名单被忽略"写进文档。顺带一提:compact 与同包 compaction.go 中供应商 compaction 条目的"压缩"是两个概念,compactHistoryAllowed / CompactHistory 在 internal/gateway/affinity 内与既有命名高度相似,建议改为 compactStorageAllowed / CompactStorage 之类以区分。


New tables `conversation_history_blocks` and `conversation_history_manifests` are created on startup. Both formats are readable. New writes use the old format by default; set `XHUB_COMPACT_HISTORY=1` in the process environment and restart to enable compact writes. Disabling it affects future writes only. A rollback must still use a binary capable of reading compact records. Block and index writes are transactional; corrupted or missing blocks fail continuation, and a failed history write cannot publish a successful Responses terminal event.

For a canary, set `XHUB_COMPACT_HISTORY=canary` and put the verified XHub user IDs in the comma-separated `XHUB_COMPACT_HISTORY_USER_IDS` variable. Console sessions and personal API keys match the authenticated user ID. A missing or empty list leaves new writes in the old format. Upgrade every instance to a binary that reads both formats before the canary. Check JSON and SSE continuation, database write volume, and read latency for a canary account and a control account before expanding. To roll back future writes, set `XHUB_COMPACT_HISTORY=0` and restart. Existing compact histories remain readable. The canary needs no migration or deletion of existing history.

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] canary 段落漏掉两条运维陷阱:名单须各实例一致、缩小名单会永久留下不可回收的块

新增段落的信息与实现基本一致,但缺两点:

  1. 名单是逐实例的环境变量,文档未要求各实例取值一致。 若滚动重启期间实例取值不同,同一响应键会在 compact 与 legacy 之间反复交替,每轮都多一次 manifest delete/insert 与一份 kv 副本,读路径又会优先命中 manifest 而绕过刚写入的旧副本。建议写明"所有实例必须使用同一份名单"。
  2. conversation_history_blocks 没有任何回收路径(仓库内 DELETE FROM conversation_history_blocks 只出现在测试里),而本 PR 让"把某个账号移出名单"成为灰度收敛的常规动作。移出后该账号所有响应键的 manifest 被删除,其内容块全部变为不可达数据并永久留存。建议在 canary 段落点明这一交互,或提供按 scope 清理的运维入口。

中英文两版需要同步。

} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("XHUB_COMPACT_HISTORY", tc.enabled)
t.Setenv("XHUB_COMPACT_HISTORY_USER_IDS", "")

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] stringPtr/Unsetenv 三层机制换不来额外覆盖,真正缺的是负向用例

compactHistoryAllowed 用 os.Getenv,无法区分"未设置"与"设置为空串"(都是 ""),而 strings.SplitSeq("", ",") 只产出一个空串、此前又已排除 UserID == "",所以 missing-list 与 explicit-empty 覆盖的是同一条分支。*string + stringPtr + 裸 os.Unsetenv 这套机制不增加任何覆盖,却多了一个按仓库注释规范必须写注释的辅助函数(:45)。建议用 ids string 一个字段表示,删掉 ids == nil 分支与 stringPtr。

真正值得补的是负向用例:"true"、"yes"、"TRUE"、"canary "(尾空格)都应返回 false;以及 p.UserID 前后带空白时不匹配(当前只修剪名单项、不修剪用户 ID,这个不对称没有任何测试或注释覆盖)。

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return store.WriteHistory(ctx, key, scope, value)
return store.WriteHistory(ctx, key, scope, value, compact)

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] 缺少 CompactHistory 传播到存储层的单测

internal/gateway/affinity/durable_test.go 的 memoryConversation 只实现了 ConversationStore,没有 HistoryStore 替身,因此这条 compact 透传没有任何单测保护。建议加一个记录 compact 参数的假存储,覆盖三点:

  • /v1/responses + "1" 或名单命中 → true;
  • chat / messages / bypass:* 入口 → false(守住 route.go:62-64 的 if endpoint == "responses";否则将来把判断改成读正文 user 字段也不会有测试报警);
  • CommitMessagesHistory 桥接路径实际写入时的取值。

}
mu.Lock()
defer mu.Unlock()
if !success || len(requests) != 4 {

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] 回归测试:断言合并导致失败信息误导,且持锁做数据库 I/O

if !success || len(requests) != 4 的失败信息写的是"回退后未用 SSE 成功续接",但真正的原因也可能是"跨账号续接没有在出站前拒绝,导致上游多收一次请求"(此时 requests 长度为 5)。建议拆成两个断言并分别给出信息,其中计数那条应明确表达"跨账号请求不得触达上游"。

另外 :101-102 的 mu.Lock(); defer mu.Unlock() 之后还在 counts(2, 2) 里查库,锁范围过大;按本仓库既有写法(如 responses_native_continuation_test.go),短暂加锁后把 requests 拷贝出来、立即解锁,再用副本断言更合适。

最后,:13 注释声称覆盖"JSON、SSE",但 SSE 只覆盖了"关闭开关后按旧格式写入"这一次;灰度用户在 canary 阶段按新格式写入的流式路径没有覆盖到。建议补一次 canary 阶段的 streaming 续接并核对行数增量。

@1034674309
1034674309 merged commit 511b6e2 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