Skip to content

fix: 修复视频任务不同分组可能导致补回额度计算错误 - #2030

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
xyfacai:refactor/openai-video
Oct 13, 2025
Merged

fix: 修复视频任务不同分组可能导致补回额度计算错误#2030
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
xyfacai:refactor/openai-video

Conversation

@xyfacai

@xyfacai xyfacai commented Oct 13, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Tasks now support an optional group attribute, enabling group-based rate limits and billing when provided or resolvable.
    • Default behavior remains unchanged when no group is available.
  • Performance

    • Reduced overhead by resolving user details only when necessary, improving request efficiency in grouped scenarios.

@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The Task model gained a Group field populated from relayInfo.UsingGroup. The video task update logic now determines the group from task.Group or, if absent, fetches the user to derive it. User lookup and group ratio calculations occur only when a non-empty group is available; billing paths use the resolved group.

Changes

Cohort / File(s) Summary
Task model update
model/task.go
Added public field Group string with JSON/gorm tags; InitTask assigns Group from relayInfo.UsingGroup.
Video task controller flow
controller/task_video.go
Modified updateVideoSingleTask control flow: derive group from task.Group first; fetch user only if needed; gate ratio and billing calculations on non-empty group; preserved final ratio and billing pathways using resolved group.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant VC as VideoController
  participant U as UserService
  participant B as Billing/Throttle

  C->>VC: updateVideoSingleTask(task)
  alt task.Group present
    VC->>VC: use task.Group
  else task.Group empty
    VC->>U: fetch user
    U-->>VC: user(group)
    VC->>VC: derive group from user
  end

  alt group is non-empty
    VC->>B: compute model/group ratio
    B-->>VC: finalGroupRatio
    VC->>B: perform billing calc
    B-->>VC: billing result
  else group is empty
    VC->>VC: skip ratio/billing by group
  end

  VC-->>C: return updated task/result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through fields of structs and flow,
A Group now tucked where tasks will go.
If none is found, I sniff the user,
Then bill with ratios, no confuser.
Ears up, I route each little byte—
Carrots counted, tokens right. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly describes the core fix addressing incorrect quota compensation when video tasks span different groups, directly aligning with the changes made to defer group lookup and adjust billing logic based on group assignment.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a4238d and dad0a7c.

📒 Files selected for processing (2)
  • controller/task_video.go (1 hunks)
  • model/task.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
controller/task_video.go (2)
model/user.go (1)
  • GetUserById (288-300)
setting/ratio_setting/group_ratio.go (2)
  • GetGroupRatio (65-75)
  • GetGroupGroupRatio (77-90)
🔇 Additional comments (5)
model/task.go (2)

49-49: LGTM! Group field properly added for billing consistency.

The new Group field will store the group context at task creation time, ensuring accurate quota calculations even if the user's group changes later. The field has appropriate JSON and GORM tags.


103-103: LGTM! Group correctly initialized from relay context.

Populating the group from relayInfo.UsingGroup ensures the task captures the group that was active when the request was made, which is essential for consistent billing calculations.

controller/task_video.go (3)

143-149: Verify error handling when user lookup fails.

The code silently ignores errors from model.GetUserById(). If the user lookup fails (e.g., user deleted), the group remains empty and billing adjustments are skipped without logging. This could lead to incorrect quota state.

Consider adding logging when the user fetch fails:

 group := task.Group
 if group == "" {
   user, err := model.GetUserById(task.UserId, false)
-  if err == nil {
+  if err != nil {
+    logger.LogError(ctx, fmt.Sprintf("Failed to get user %d for task %s billing adjustment: %s", task.UserId, task.TaskID, err.Error()))
+  } else {
     group = user.Group
   }
 }

150-216: Verify behavior when group resolution fails.

If both task.Group and user.Group are empty (or user lookup fails), the entire billing adjustment logic is skipped silently. This means tasks with token-based billing won't have their quotas adjusted, potentially leaving users overcharged or undercharged.

Consider adding an else branch to log this scenario:

 if group != "" {
   groupRatio := ratio_setting.GetGroupRatio(group)
   userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(group, group)
   
   // ... rest of billing logic ...
+} else {
+  logger.LogWarn(ctx, fmt.Sprintf("Task %s cannot perform billing adjustment: group not available (task.Group='%s', user lookup may have failed)", task.TaskID, task.Group))
 }

143-216: Good fix for group-based billing consistency.

The solution correctly stores the group at task creation time and uses it during billing adjustments. The fallback to user's current group handles legacy tasks gracefully. This ensures quota calculations use the group ratio that was in effect when the task was created, preventing miscalculations when users switch groups.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Calcium-Ion
Calcium-Ion merged commit 7311c18 into QuantumNous:main Oct 13, 2025
1 check passed
Xiaoshuaiawd referenced this pull request in Xiaoshuaiawd/new-api Oct 13, 2025
* main: (42 commits)
  fix: remove redundant error handling for empty Gemini API response
  fix(convert): 修复 OpenAI 转 Claude 流时 thinking 块的格式问题
  fix: improve error handling for email sending failures
  feat: add support for Sora channel type and OpenAI video endpoint
  feat: jimeng images base64 limit (#2032)
  fix: 修复视频任务不同分组可能导致补回额度计算错误 (#2030)
  feat: jimeng use openai sdk input_reference i2v
  refactor: Openai video model 移动到 dto
  fix: update error messages for unsupported parameter names in Google extra body
  fix: 修复工作流重复创建release的问题
  feat: Add pre-status protection for IncreaseUserQuota
  fix: empty version
  feat: support free model setting
  fix: version
  ignore ghcr
  fix: mask sensitive information in error messages and refine task retrieval query
  feat: add vidu use openai sdk
  fix: kling create video via openai sdk
  refactor: add openaiVideo and method
  feat: add jimeng use openai sdk
  ...

# Conflicts:
#	Dockerfile
#	model/log.go
#	relay/channel/openai/relay-openai.go
#	relay/compatible_handler.go
jiutubaba pushed a commit to jiutubaba/fx-api that referenced this pull request May 17, 2026
…ulk-edit-scope-and-compact

feat: support filtered account bulk edit and align compact OpenAI bulk fields
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.

2 participants