Skip to content

fix(billing): make group rate/RPM sync transactional - #8659

Merged
Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
lishuangqiang:fix/group-rate-sync-transaction
Nov 16, 2026
Merged

Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
lishuangqiang:fix/group-rate-sync-transaction

Conversation

@lishuangqiang

@lishuangqiang lishuangqiang commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

问题

SyncGroupRateMultipliers / SyncGroupRPMOverrides 用三条独立的 autocommit 语句完成“全量同步”:

  1. 把不在本次 entries 里的行 UPDATE ... SET <column> = NULL;
  2. DELETE 整行全 NULL 的记录;
  3. INSERT ... ON CONFLICT DO UPDATE 写入本次 entries。

没有事务。第 3 步失败时,前两步已经提交且无法回滚,数据库停留在“部分清空”的状态。

触发场景

  • 管理员打开弹窗后,另一个管理员删除了其中一个用户 → INSERT 触发外键 user_id REFERENCES users(id) 失败;
  • payload 里有重复 user_id → ON CONFLICT DO UPDATE command cannot affect row a second time;
  • 第 3 步遇到任意瞬时 DB 错误。

结果:接口返回 500,但不在 entries 里的用户配置已经被清空/删除;管理员看不到“其他配置被清空”的提示。

修复

  • 把三步放进同一个事务,任何一步失败整体回滚;
  • 写入前按 user_id 去重(保留最后一次出现的值),避免重复 ID 让 ON CONFLICT 直接失败;
  • 两个同步函数都改。

测试

用 sqlmock 验证事务边界:

  • TestSyncGroupRateMultipliersCommitsInOneTransaction / TestSyncGroupRPMOverridesCommitsInOneTransaction:三步 + Commit;
  • ...RollsBackOnInsertFailure:第 3 步失败时执行 Rollback,前两步不会生效;
  • TestDedupeGroupRateMultiplierEntriesKeepsLastValue / TestDedupeGroupRPMOverrideEntriesKeepsLastValue:重复 user_id 保留最后一次。

本地验证:

  • go test -tags=unit ./internal/repository/ 通过
  • 新测试 -race 通过
  • go build ./... 通过

Closes #8660

SyncGroupRateMultipliers and SyncGroupRPMOverrides ran three destructive
statements in autocommit mode: clear rows missing from the payload,
delete all-NULL rows, then upsert the payload. If the upsert failed
(deleted user FK, duplicate user_id, transient DB error), the clear and
delete had already committed, silently wiping the group's overrides.

Wrap each sync in one transaction and dedupe entries by user_id before
writing so ON CONFLICT cannot hit the same row twice. Any failure now
rolls the whole sync back.

Add sqlmock tests covering commit, rollback and dedupe.
@lishuangqiang

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@Wei-Shaw
Wei-Shaw merged commit 0c641e5 into Wei-Shaw:main Nov 16, 2026
9 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 16, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 分组专属倍率/RPM 同步无事务,写入失败会清空整组配置

2 participants