Repository navigation
fix(setting): stop config hot-reload from racing with hot-path readers - #6673
guopengnaivoc wants to merge 3 commits into
Conversation
Config hot-reload mutates already-published shared objects in place via reflection while relay hot paths read them with no shared synchronisation. This is not an admin-action window: SyncOptions runs as a permanent background goroutine and rewrites every registered config once per SYNC_FREQUENCY (default 60s) regardless of whether anything changed. The write side is not unlocked - updateOptionMap holds OptionMapRWMutex across handleConfigUpdate - but readers do not take that lock, so the lock is simply not shared with them. Measured on 0ab0202 (go1.26.5 darwin/arm64): a loop that only updates billing_mode while goroutines call GetBillingMode crashes the process with "fatal error: concurrent map read and map write" at tiered_billing.go:39 in 2 of 2 runs. Readers of the sensitive-word list observe a length of 0 while it is being rebuilt. go test -race reports 12 distinct races. After this change: 0 races, no crash across 3 runs of 25s, and no partial list observed. Fixes the six modules whose read path is on a hot path or guards a security control: - billing_setting: fields become *types.RWMap, so the existing ConfigManager pointer branch routes writes through RWMap.UnmarshalJSON (write lock) and reads through Get (read lock). group_ratio_setting already worked this way; this reuses that proven pattern rather than adding a new mechanism. - fetch_setting: GetFetchSetting returns an immutable snapshot published via atomic.Pointer. The SSRF allow/deny lists go through the slice branch, which refills the backing array in place. Snapshotting leaves all six SSRF call sites untouched, which matters for security-critical code. - sensitive.go / auto_group.go / chat.go: build the list locally and publish it in one store instead of clearing then refilling. Invalid JSON now leaves the previous config intact instead of blanking it. - monitor_setting: GetMonitorSetting no longer writes to shared state. Env overrides and test-mode normalisation move to the post-update hook, so the env-wins-over-DB contract still holds after every periodic sync. Adds config.PostUpdater, an optional hook invoked after fields are written. It is additive and does not change the publish model, so the broader ConfigManager rework remains separately schedulable. chat.go additionally switches from encoding/json to the common wrappers, as required by AGENTS.md. The two existing monitor_setting tests asserted that the getter applies env overrides at read time, which is the behaviour being removed. They are rewritten to assert the durable contract - env overrides win over database config - by driving a real config update first, which is closer to the actual failure mode. Refs: docs/bugfix/002-config-hotpath-race-bug.md Co-Authored-By: Claude Opus 5 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
WalkthroughConfiguration settings now publish atomic snapshots. Post-update hooks refresh derived settings after hot changes. Readers use accessors instead of mutable globals, with tests covering snapshot isolation and update behavior. ChangesConcurrent configuration updates
Estimated code review effort: 4 (Complex) | ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
setting/billing_setting/tiered_billing.go (1)
21-59: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winKeep
RWMapfields initialized fornullconfiguration values.
updateConfigFromMapsets pointer fields to nil when the value is"null". A persistedbilling_mode=nullorbilling_expr=nullremoves the initializedRWMap, and everytypes.RWMapaccessor dereferences the nil receiver. Rejectnullfor these fields or replace it with an emptyRWMap. Add a regression test for both fields.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@setting/billing_setting/tiered_billing.go` around lines 21 - 59, Preserve non-nil RWMap values when billing_mode or billing_expr configuration is null by rejecting null or replacing it with a newly initialized empty RWMap during updateConfigFromMap processing. Ensure GetBillingMode, GetBillingExpr, GetBillingModeCopy, and GetBillingExprCopy remain safe after null configuration, and add regression coverage for both fields.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@setting/operation_setting/monitor_setting.go`:
- Around line 31-64: Make monitor configuration reads safe by separating the
mutable update target from the published snapshot. Update the flow around
refreshMonitorSetting and MonitorSetting.AfterConfigUpdate to apply overrides
first, then atomically publish a complete MonitorSetting value; change
GetMonitorSetting to load and return the published snapshot rather than
&monitorSetting. Ensure every configuration update publishes after all mutations
so readers never observe partial state.
---
Outside diff comments:
In `@setting/billing_setting/tiered_billing.go`:
- Around line 21-59: Preserve non-nil RWMap values when billing_mode or
billing_expr configuration is null by rejecting null or replacing it with a
newly initialized empty RWMap during updateConfigFromMap processing. Ensure
GetBillingMode, GetBillingExpr, GetBillingModeCopy, and GetBillingExprCopy
remain safe after null configuration, and add regression coverage for both
fields.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9a226354-a849-4412-934b-56397fc3578c
📒 Files selected for processing (13)
controller/misc.goservice/sensitive.gosetting/auto_group.gosetting/billing_setting/tiered_billing.gosetting/billing_setting/tiered_billing_test.gosetting/chat.gosetting/config/config.gosetting/operation_setting/monitor_setting.gosetting/operation_setting/monitor_setting_test.gosetting/sensitive.gosetting/snapshot_publish_test.gosetting/system_setting/fetch_setting.gosetting/system_setting/fetch_setting_test.go
Addresses two review findings, both verified independently before changing anything. 1. billing_setting panicked on a "null" configuration value - a regression introduced by this branch. Changing the fields from map[string]string to *types.RWMap moved them from the map branch of updateConfigFromMap to the pointer branch, which sets the field to nil for the literal "null". Every RWMap method dereferences the receiver, so GetBillingMode then panicked. The map branch had no such problem: reading a nil map in Go yields the zero value. Measured: on the baseline, billing_mode=null leaves GetBillingMode returning "ratio"; on this branch before the fix it was a nil pointer dereference. That accessor runs on every relay request, so the blast radius is larger than the race being fixed. group_ratio_setting has used *RWMap with an explicit nil guard for a while (group_ratio.go:55-58); this branch adopted the type without the guard. The fix reads defensively without writing - usableBillingMap falls back to a shared read-only empty map - rather than rebuilding the map inside the getter the way group_ratio_setting does, since that would turn a read path back into a writer of shared state. AfterConfigUpdate restores the field so a nil is not re-serialised as "null" and latched. 2. GetMonitorSetting still handed readers &monitorSetting, the hot-reload write target. ChannelTestMode is a string, so its double-word write can be observed torn by the scheduled-task goroutines that read it. Now published as an atomic.Pointer snapshot, matching fetch_setting in this same change. The struct is all scalars, so assignment is a complete copy. Call sites unchanged. Regression tests cover both: a null value must not panic and must fall back to ratio while leaving the fields restored, and a held monitor snapshot must not be rewritten by a later update. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Fixed in db16e6c. Confirmed as a regression this branch introduced: on the baseline 🤖 Addressed by Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@setting/billing_setting/tiered_billing.go`:
- Around line 57-88: Synchronize replacement of the BillingMode and BillingExpr
pointers across AfterConfigUpdate and all billing accessors. Prefer atomically
publishing an immutable BillingSetting snapshot, or introduce one shared lock
covering the complete mutation and every pointer read in GetBillingMode,
GetBillingExpr, GetBillingModeCopy, and GetBillingExprCopy; also add a
concurrent null-update/accessor regression test.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fa1ae886-af90-49f7-bf81-6001f1fe348f
📒 Files selected for processing (4)
setting/billing_setting/tiered_billing.gosetting/billing_setting/tiered_billing_test.gosetting/operation_setting/monitor_setting.gosetting/operation_setting/monitor_setting_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- setting/operation_setting/monitor_setting.go
Third review finding on QuantumNous#6673, verified before changing anything: with the fields typed as *types.RWMap, RWMap guards the map contents but not replacement of the pointer field itself. updateConfigFromMap replaces that pointer for the literal "null" (the reflect.Ptr branch), and AfterConfigUpdate wrote it back, so the pointer reads in the four accessors raced with those writes. Reproduced: a loop alternating "null" and a real value against concurrent readers reports 4 data races at tiered_billing.go:73. Reaching for RWMap was the wrong call and is what created this. Reverting the fields to plain maps and publishing an immutable snapshot via atomic.Pointer is both simpler and more complete: - readers never touch the write target, so pointer replacement cannot be observed at all; - a nil map reads fine, so the "null" crash class disappears rather than being guarded against; - the serialised form in the database is unchanged, since the field types are back to what they were; - the hot path becomes a plain read of an immutable map with no lock, which is cheaper than the RWMap read lock it replaces. It also makes billing_setting, fetch_setting and monitor_setting use one consistent pattern in this branch instead of two. Same reproduction after the change: 0 races. Co-Authored-By: Claude Opus 5 <[email protected]>
|
说实话人工智能已经超越了人类 |
|
你不相信吗 |
|
你不理解,不代表不对 |
51fdfc5 to
2b6f1df
Compare
Use complete logical-channel transaction snapshots so central persistence rollback cannot be followed by an incremental undo that panics or removes existing data. Reject audit cursors when any portion of the original retained interval expires. Synchronize test writers after a second manager persists migration defaults, without weakening pending external-edit protection. Regression coverage includes first/existing logical creation, deletion and update failures, partial/full cursor eviction, and repeated single-writer mutations. Follow-up to soulteary/yunqi PR #105 review. Refs: QuantumNous/new-api #8076 QuantumNous/new-api#8076 Refs: QuantumNous/new-api #8034 QuantumNous/new-api#8034 Refs: QuantumNous/new-api #6673 QuantumNous/new-api#6673
Commit configuration and bounded management audit atomically, retain explicit actor/operation identity through HTTP and domain transactions, and preserve separate system attribution for discovery. Regression tests, cross-review and full Verify CI passed, including retention/rollback fixes, model governance integration and isolated Redis readiness. Refs: QuantumNous/new-api#8076 QuantumNous/new-api#8076 Refs: QuantumNous/new-api#8034 QuantumNous/new-api#8034 Refs: QuantumNous/new-api#6673 QuantumNous/new-api#6673 Refs: QuantumNous/new-api#7953 QuantumNous/new-api#7953 Refs: QuantumNous/new-api#7951 QuantumNous/new-api#7951
docs: finalize community improvement batches and validation Document eight implemented capabilities, review fixes, exact commits, CI evidence and upstream correspondence. Preserve identity, Redis and evaluation boundaries, and provide the model governance lifecycle/API guide. All functional PRs were reviewed and merged after successful regression tests and Verify CI. The running checkout and services were not changed. Refs: QuantumNous/new-api issue #1730 QuantumNous/new-api#1730 Refs: QuantumNous/new-api issue #2841 QuantumNous/new-api#2841 Refs: QuantumNous/new-api issue #3240 QuantumNous/new-api#3240 Refs: QuantumNous/new-api PR #3345 QuantumNous/new-api#3345 Refs: QuantumNous/new-api issue #4328 QuantumNous/new-api#4328 Refs: QuantumNous/new-api PR #4329 QuantumNous/new-api#4329 Refs: QuantumNous/new-api PR #4492 QuantumNous/new-api#4492 Refs: QuantumNous/new-api PR #5431 QuantumNous/new-api#5431 Refs: QuantumNous/new-api PR #5791 QuantumNous/new-api#5791 Refs: QuantumNous/new-api PR #6264 QuantumNous/new-api#6264 Refs: QuantumNous/new-api PR #6583 QuantumNous/new-api#6583 Refs: QuantumNous/new-api PR #6620 QuantumNous/new-api#6620 Refs: QuantumNous/new-api PR #6673 QuantumNous/new-api#6673 Refs: QuantumNous/new-api issue #6972 QuantumNous/new-api#6972 Refs: QuantumNous/new-api PR #7028 QuantumNous/new-api#7028 Refs: QuantumNous/new-api issue #7951 QuantumNous/new-api#7951 Refs: QuantumNous/new-api issue #7952 QuantumNous/new-api#7952 Refs: QuantumNous/new-api PR #7953 QuantumNous/new-api#7953 Refs: QuantumNous/new-api PR #7955 QuantumNous/new-api#7955 Refs: QuantumNous/new-api issue #8034 QuantumNous/new-api#8034 Refs: QuantumNous/new-api PR #8076 QuantumNous/new-api#8076 Refs: QuantumNous/new-api issue #8123 QuantumNous/new-api#8123 Refs: QuantumNous/new-api PR #8124 QuantumNous/new-api#8124 Refs: QuantumNous/new-api issue #8232 QuantumNous/new-api#8232 Refs: QuantumNous/new-api PR #8233 QuantumNous/new-api#8233 Refs: QuantumNous/new-api issue #8295 QuantumNous/new-api#8295 Refs: QuantumNous/new-api PR #8296 QuantumNous/new-api#8296 Refs: QuantumNous/new-api PR #8350 QuantumNous/new-api#8350 Refs: QuantumNous/new-api PR #8357 QuantumNous/new-api#8357 Refs: QuantumNous/new-api PR #8363 QuantumNous/new-api#8363 Refs: #99 #99 Refs: #100 #100 Refs: #101 #101 Refs: #102 #102 Refs: #103 #103 Refs: #104 #104 Refs: #105 #105 Refs: #106 #106 Refs: #107 #107 Refs: #108 #108 Refs: #109 #109 Documentation Verify CI passed: https://github.com/soulteary/yunqi/actions/runs/45003986698
📝 变更描述 / Description
配置热更新会用反射原地改写已经发布给业务代码的共享对象,而中继热路径同时在读这些对象,两者之间没有共享的锁。
关键在于这不是「管理员改配置时的瞬时窗口」:
SyncOptions是常驻后台 goroutine,每SYNC_FREQUENCY秒(默认 60)把所有 option 重新过一遍updateOptionMap→handleConfigUpdate,与是否有人修改配置无关。所以这是每个实例持续存在的状态。需要说明的是,写入侧并非完全无锁 ——
updateOptionMap持有common.OptionMapRWMutex并覆盖handleConfigUpdate的整个执行。问题是读者不持这把锁,即「锁没有和读者共享」。实测结果(
0ab02020,go1.26.5 darwin/arm64)一个只更新
billing_mode的循环 + 并发调用GetBillingMode:2/2 轮必现崩溃。 进程直接终止,无法 recover。
go test -race报告的竞争崩溃的成因是缺少 happens-before 边:
field.Set发布新 map 的存储没有 release 语义,在 arm64 这类弱内存序架构上可以先于填充该 map 的存储对其他核可见,读者因而可能拿到一个内部状态尚未稳定的 map。未在 amd64 上验证,x86 强内存序下复现难度应显著更高,但缺少同步这一事实与架构无关。改动内容
本 PR 修复读路径位于中继热路径或安全控制的 6 个模块:
billing_setting:字段改为*types.RWMap。updateConfigFromMap的指针分支会把写入路由到RWMap.UnmarshalJSON(写锁),读取走Get(读锁),写者与读者共享同一把锁。group_ratio_setting本来就是这么写的且已经是正确的,这里复用同一模式,不引入新机制,也不改动 ConfigManager。fetch_setting:GetFetchSetting()改为返回atomic.Pointer发布的不可变快照。SSRF 名单走的是切片分支,encoding/json解码切片会复用底层数组,属于在已发布对象上原地改写。改用快照后6 个 SSRF 调用点一行不用改 —— 对安全关键代码,这直接降低了引入新缺陷的概率。sensitive.go/auto_group.go/chat.go:由「先清空再逐个填充」改为「本地构建完成后一次性发布」。附带收益:非法 JSON 不再清空已生效的配置(原先先make再 unmarshal,解析失败就留下空列表)。monitor_setting:GetMonitorSetting()不再写入共享状态。原先它每次调用都套用 env 覆盖并做归一化,两个并发的读取就能互相写同一个结构体,与配置更新无关。env 覆盖与归一化移到更新后处理,因此「env 优先于数据库配置」在每轮周期同步后依然成立。新增
config.PostUpdater可选接口,供模块在字段写入后收尾(发布快照 / 归一化)。这是纯增量扩展,不改变 ConfigManager 的发布模型。chat.go顺带从encoding/json改为common封装,符合AGENTS.md的要求。范围说明
本 PR 只覆盖热路径和安全控制部分,不是该问题的完整修复。
反射普查 23 个注册模块:98 个导出字段中有 28 个
string(SetString是指针+长度的双字写入,读者可能读到「新指针 + 旧长度」而越界读),可撕裂或可竞争字段合计 48 个。gemini(GetGeminiSafetySetting已被 race detector 实测命中)、claude、global、payment_setting、qwen、channel_affinity_setting的读路径仍未同步。彻底的做法是改造 ConfigManager 的发布模型(解析到新对象 → 写锁内原子替换、
Get返回只读快照),一次性让全部模块变安全。那个改动影响面大,建议单独一个 PR。如果维护者希望合并处理,我可以继续跟进。🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
无。已搜索现有 Issue 与 PR,未找到相同问题的记录。如果希望先开 Issue 讨论再合并,请告知。
✅ 提交前检查项 / Checklist
📸 运行证明 / Proof of Work
修复前,崩溃复现(2/2 轮):
修复后,同一压测 3 轮 × 25 秒:
竞争检测:
常规检查:
go build ./...cd relaykit && GOWORK=off go build ./...go vet ./...gofmt -l(改动的 10 个文件)go test ./...go test -race ./setting/...service包在-race下有 3 处竞争(task_polling.go、logger.go、model/task.go),已用基线 worktree 对照确认修复前同样是 3 处且调用栈一致,属既有问题,与本 PR 无关。新增测试(确定性断言,未包含压测代码):
setting/snapshot_publish_test.go—— 更新是全有或全无;已取得的列表不被后续更新改写;解析失败保留原列表setting/system_setting/fetch_setting_test.go—— 快照与写入目标解耦、深拷贝底层数组setting/billing_setting/tiered_billing_test.go—— 序列化格式不变(字段类型改变后旧数据行仍可读)、移除的模型回退到 ratio、Copy 系列返回独立副本monitor_setting_test.go的两个既有测试原本断言 getter 在读取时套用 env 覆盖,而该行为正是本 PR 要消除的。它们编码的底层契约(env 优先于数据库配置)是真实且必须保留的,因此改为通过真实的配置更新路径验证同一契约 —— 先模拟数据库下发相反的值,再断言 env 仍然胜出。这比原测试更接近实际故障场景。Summary by CodeRabbit
Bug Fixes
Tests