fix: reverse used quota on async task refunds (#4211)#6091
Conversation
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughRefund and negative recalculation flows now decrease user and channel ChangesQuota refund accounting
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant TaskBilling
participant QuotaModels
participant Database
TaskBilling->>QuotaModels: decrease user and channel used_quota
QuotaModels->>Database: apply clamped decrement
Database-->>QuotaModels: updated usage totals
Possibly related PRs
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 |
Keep QuantumNous#4211 scoped to used-quota reversal only. Channel group column widening belongs in QuantumNous#6017.
|
Addressed CodeRabbit out-of-scope warning:
Commit: fb4de27 |
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 `@model/channel.go`:
- Line 40: Revert the `channels.Group` GORM width change in the `Channel` model
so this PR preserves the existing `varchar(1024)` schema; defer narrowing it to
a separate ticket or dedicated migration.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
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 `@model/channel.go`:
- Line 40: Revert the `channels.Group` GORM width change in the `Channel` model
so this PR preserves the existing `varchar(1024)` schema; defer narrowing it to
a separate ticket or dedicated migration.
🪄 Autofix (Beta)
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
Run ID: 9c83000e-5ac7-42ac-a740-b4f2efe7aa49
📒 Files selected for processing (1)
model/channel.go
🛑 Comments failed to post (1)
model/channel.go (1)
40-40: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Inspect the new/updated channel used-quota helpers and the Group field history ast-grep outline model/channel.go --items all sed -n '855,895p' model/channel.go # Verify current base definition of the Group column tag rg -nP 'Group\s+string\s+`json:"group"' model/channel.goRepository: QuantumNous/new-api
Length of output: 7437
🏁 Script executed:
#!/bin/bash set -euo pipefail # Inspect the current schema/model references for channel group length and any migrations around it. rg -n "varchar\\(1024\\)|varchar\\(64\\)|Group.*default:'default'|group length|channel group" .Repository: QuantumNous/new-api
Length of output: 2867
🏁 Script executed:
#!/bin/bash set -euo pipefail # Show the exact diff for model/channel.go and any mentions of the group-size change in the repo. git diff -- model/channel.go printf '\n---\n' rg -n "codex/fix-6017-channel-group-length|`#6017`|group length|varchar\\(1024\\)" .Repository: QuantumNous/new-api
Length of output: 386
🌐 Web query:
GORM AutoMigrate shrink varchar column existing data truncate alter column size behavior💡 Result:
When using GORM's AutoMigrate, the library is designed to automatically detect and apply changes to database columns, including size, if they differ from your struct definition [1][2]. Specifically, if you shrink the size of a varchar column in your struct (e.g., changing
size:255tosize:100), GORM will issue anALTER TABLEstatement (typically usingMODIFY COLUMNorCHANGE COLUMNdepending on the database driver) to update the column definition [3]. Regarding the behavior of existing data, it is critical to understand the following: 1. No Automatic Truncation: GORM itself does not perform data truncation or validation logic to trim existing records that exceed the new, smaller size. It merely issues the DDL command to the database [4][3]. 2. Database-Level Enforcement: The actual behavior depends entirely on the underlying database engine (e.g., MySQL, PostgreSQL, SQLite). When you issue anALTER TABLEcommand to shrink a varchar column: - Some databases (like strict MySQL configurations) may reject the operation if existing data exceeds the new size, resulting in an error. - Others may allow it but behave unpredictably, potentially causing truncation or data corruption at the database storage level. 3. Reliability Limitations: While GORM attempts to be "smart" about migrations, the logic for detecting when a column needs to be altered can sometimes be inconsistent [3]. Users have reported that simply updating the struct tag does not always trigger the necessaryALTERstatement [5][6][7]. In some cases, explicitly defining other attributes or using a custom migration might be required if GORM fails to detect the change [8]. Recommendation: Because AutoMigrate is a convenience tool and not a replacement for robust database migration management, you should not rely on it to safely shrink columns containing production data. Before applying such a change, you should manually verify your existing data size, perform a backup, and consider using a dedicated migration tool (likegolang-migrateor GORM's ownMigratorinterface with manualExecutecalls) to perform the change safely, potentially involving a staging column or data cleanup to avoid errors during the schema update.Citations:
- 1: https://gorm.io/docs/migration.html
- 2: https://gorm.io/docs/v2_release_note.html
- 3: go-gorm/gorm#4915
- 4: https://github.com/go-gorm/gorm/blob/master/migrator/migrator.go
- 5: go-gorm/gorm#3645
- 6: https://github.com/go-gorm/gorm/pull/7380/files/a01ac51ca798978348a8eb4adb349c6a77d6a3a6
- 7: https://stackoverflow.com/questions/64520985/gorm-change-column-length
- 8: go-gorm/gorm#4940
🏁 Script executed:
#!/bin/bash set -euo pipefail # Check whether group values are validated/bounded elsewhere and whether any migration exists for this model field. rg -n "group.{0,40}(len|length|varchar|64|1024)|Group.*64|Group.*1024|Validate.*Group|NormalizeChannelGroupFilter|ApplyChannelGroupFilter" model common dto internal .Repository: QuantumNous/new-api
Length of output: 16153
Keep the
channels.Groupwidth change out of this PRmodel/channel.go:40
This narrowsGroupfromvarchar(1024)tovarchar(64), which can truncate existing rows during migration. Move it to the separate group-length ticket or add a dedicated migration/backfill.🤖 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 `@model/channel.go` at line 40, Revert the `channels.Group` GORM width change in the `Channel` model so this PR preserves the existing `varchar(1024)` schema; defer narrowing it to a separate ticket or dedicated migration.Source: Path instructions
|
@Calcium-Ion @t0ng7u 麻烦有空时 review 一下这个 PR。 范围:仅 #4211 — 异步任务退款时同步回退 user/channel used quota。 |
Important
📝 变更描述 / Description
异步任务失败退款和负差额结算现在会同步回退用户/渠道 used_quota。此前任务预扣会增加 used_quota,但退款只返还余额,导致“剩余额度 + 已用额度”虚增。新增 DecreaseUserUsedQuota / DecreaseChannelUsedQuota,并对负向调整做 0 下限保护。
This PR was AI-assisted and manually reviewed before submission.
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
✅ 提交前检查项 / Checklist
Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。📸 运行证明 / Proof of Work
Summary by CodeRabbit