Skip to content

fix: 当totalWeight小于等于0时随机选择渠道 - #2126

Merged
seefs001 merged 2 commits into
mainfrom
fix-randomWeight-panic
Oct 29, 2025
Merged

fix: 当totalWeight小于等于0时随机选择渠道#2126
seefs001 merged 2 commits into
mainfrom
fix-randomWeight-panic

Conversation

@creamlike1024

@creamlike1024 creamlike1024 commented Oct 29, 2025

Copy link
Copy Markdown
Collaborator

fix #2125

Summary by CodeRabbit

  • Bug Fixes
    • Strengthened channel selection reliability by adding validation safeguards for weight calculations during smoothing operations. These protective measures prevent errors from invalid weight values, ensuring the algorithm operates consistently when selecting among available channels based on weighted criteria.

@coderabbitai

coderabbitai Bot commented Oct 29, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Replace the previous zero-weight guard with a deterministic fallback: if computed totalWeight ≤ 0 and there are target channels, treat each channel as weight 100 and run weighted random selection; if no channels exist, return a "no available channels" error. (43 words)

Changes

Cohort / File(s) Summary
Channel selection fallback
model/channel_cache.go
When computed totalWeight ≤ 0, if target channels exist set totalWeight = len(targetChannels) * 100 and perform weighted selection by treating each channel as weight 100 (decrementing a threshold by 100 per channel). If no channels, return an error "no available channels".

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ChannelCache
    participant RNG as rand.Intn

    Caller->>ChannelCache: request SelectChannel(targetChannels)
    ChannelCache->>ChannelCache: compute totalWeight (after smoothing)
    alt totalWeight > 0
        ChannelCache->>RNG: n = rand.Intn(totalWeight)
        ChannelCache->>ChannelCache: iterate channels, subtract weights until n < 0
        ChannelCache->>Caller: return selected channel
    else totalWeight <= 0
        alt targetChannels not empty
            ChannelCache->>ChannelCache: totalWeight = len(targetChannels) * 100
            ChannelCache->>RNG: n = rand.Intn(totalWeight)
            ChannelCache->>ChannelCache: iterate channels, subtract 100 per channel until n < 0
            ChannelCache->>Caller: return selected channel
        else no channels
            ChannelCache->>Caller: return error "no available channels"
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect model/channel_cache.go selection loop for off-by-one and threshold decrement correctness.
  • Verify randomness distribution with 100-per-channel fallback matches intended behavior.
  • Confirm error path uses the correct error type/message and is handled by callers.

Poem

I’m a rabbit in the cache, hopping through the lot,
When weights fall to zero, I find a simple plot.
Each channel gets a hundred hops, I spin the wheel anew,
If none are here to choose from, I shout, "No channels — adieu!" 🐇🎲

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The pull request title (translated from Chinese: "fix: When totalWeight is less than or equal to 0, set it to 1 and select the first channel") describes a fix where totalWeight is set to 1 and the first channel is selected. However, the actual implementation sets totalWeight to len(targetChannels) * 100 and performs a weighted random selection by decrementing 100 for each channel, rather than simply selecting the first channel. This is a material difference in behavior that makes the title misleading and inaccurate relative to what the code actually does. The title should be updated to accurately reflect the actual implementation. A more accurate title would be something like "fix: Add fallback with weighted random selection when totalWeight <= 0" or "fix: Handle zero totalWeight with equal-weight channel distribution" to convey that the fix uses a 100-weight-per-channel fallback with random selection rather than simply selecting the first channel.
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 (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-randomWeight-panic

📜 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 cba21eb and 90f1daf.

📒 Files selected for processing (1)
  • model/channel_cache.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • model/channel_cache.go

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f419a3 and cba21eb.

📒 Files selected for processing (1)
  • model/channel_cache.go (1 hunks)

Comment thread model/channel_cache.go Outdated
@seefs001
seefs001 merged commit 8297723 into main Oct 29, 2025
1 check passed
@creamlike1024 creamlike1024 changed the title fix: 当totalWeight小于等于0时设置为1选择第一个渠道 fix: 当totalWeight小于等于0时随机选择渠道 Oct 29, 2025
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
…-panic

fix: 当totalWeight小于等于0时设置为1选择第一个渠道
@Calcium-Ion
Calcium-Ion deleted the fix-randomWeight-panic branch April 1, 2026 16:54
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.

newapi start failed with panic

2 participants