Skip to content

Improve channel affinity reliability and Claude cache recovery - #4223

Open
nixyme wants to merge 1 commit into
QuantumNous:mainfrom
nixyme:codex/channel-affinity-reliability
Open

nixyme wants to merge 1 commit into
QuantumNous:mainfrom
nixyme:codex/channel-affinity-reliability

Conversation

@nixyme

@nixyme nixyme commented Apr 13, 2026 •

Copy link
Copy Markdown

Summary

  • auto-clear stale affinity bindings when the preferred channel is disabled or missing
  • log distributor-stage channel disable decisions with channel context for faster debugging
  • let Claude CLI affinity flows retry instead of hard-failing on affinity errors
  • add a dedicated Claude Code cache-clear shortcut in channel affinity settings

Why

This fixes a high-impact connectivity issue where Claude Code and other affinity-bound traffic could get pinned to disabled historical channels and return opaque 403 errors. The new behavior degrades gracefully, preserves routing continuity, and adds enough observability to identify the bad channel quickly when something does go wrong.

Testing

  • go test ./setting/operation_setting ./service ./middleware
  • bun run build

Notes

  • excluded unrelated local workspace changes from this PR on purpose

Summary by CodeRabbit

  • New Features

    • Added UI option to clear Claude Code cache in channel affinity settings.
    • Enhanced channel affinity management with ability to clear cache entries.
  • Improvements

    • Improved channel handling for disabled channels with better logging and error tracking.
    • Claude CLI trace rule now retries on failure by default.
  • Tests

    • Added test coverage for cache clearing functionality.
    • Added verification for Claude CLI trace retry behavior.

@coderabbitai

coderabbitai Bot commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes enhance channel distribution middleware with structured logging and affinity management capabilities. A new channel affinity clearing function enables cache invalidation when preferred channels become unavailable or disabled. Configuration updates adjust retry behavior for Claude CLI trace rules, accompanied by corresponding tests and UI enhancements for cache management.

Changes

Cohort / File(s) Summary
Middleware Enhancements
middleware/distributor.go
Added structured logging helpers (logDistributorChannelDecision, logDistributorAffinityFallback) and modified control flow to detect disabled channels with early abort. Enhanced affinity handling to detect unavailable preferred channels, clear affinity cache via new service function, emit fallback logs, and enrich context with admin info when ErrorLogEnabled.
Service Logic
service/channel_affinity.go
Added ClearCurrentChannelAffinity(c *gin.Context) bool function to safely delete channel-affinity cache entries, reset skip-retry flag, and return deletion status.
Service Tests
service/channel_affinity_template_test.go
Added TestClearCurrentChannelAffinity test verifying cache deletion, flag reset, and retry behavior changes after affinity clearing.
Configuration & Testing
setting/operation_setting/channel_affinity_setting.go, channel_affinity_setting_test.go
Updated Claude CLI trace rule default to disable skip-retry-on-failure behavior (SkipRetryOnFailure: false); added corresponding test TestClaudeCliTraceDoesNotSkipRetryOnFailure to validate the setting.
UI Enhancement
web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx
Added memoized lookup for Claude CLI trace rule, cache count display, and new UI section ("Claude Code 快捷运维") with cache-clear button and state management.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 When channels hop away or stumble and fall,
The affinity clears, we log through it all!
New helpers shine bright in the distributor's land,
And Claude's cache, now cleared, springs up with a hand.
Configuration fresh, UI enhanced with cheer—
A rabbit's proud moment: improvements are here! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 accurately reflects the main changes across the PR: it addresses channel affinity reliability improvements (clearing stale bindings, logging decisions) and Claude cache recovery (new cache-clear shortcut). The title is concise, specific, and clearly conveys the primary intent.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@middleware/distributor.go`:
- Around line 456-474: service.AppendChannelAffinityAdminInfo mutates adminInfo
but the mutated map is never recorded; include the enriched adminInfo in the
fallback path so the rule/key context is preserved—after calling
service.AppendChannelAffinityAdminInfo(c, adminInfo) pass the mutated adminInfo
into the logger.LogWarn call (e.g., add admin_info=%v to the formatted message)
so the enriched map is logged, or alternatively call the existing
persistence/attach function that records adminInfo for the request before
emitting the warning; reference AppendChannelAffinityAdminInfo, adminInfo and
logger.LogWarn.

In `@service/channel_affinity.go`:
- Around line 238-255: ClearCurrentChannelAffinity currently leaves
ginKeyChannelAffinitySkipRetry unchanged when cache.DeleteMany fails, allowing
ShouldSkipRetryAfterChannelAffinityFailure to see an old SkipRetry=true; ensure
the retry gate is always reset by setting c.Set(ginKeyChannelAffinitySkipRetry,
false) regardless of delete outcome (either move that c.Set before calling
getChannelAffinityCache/DeleteMany or use a defer to set it immediately in
ClearCurrentChannelAffinity), keep error logging of
getChannelAffinityCache().DeleteMany and still return false on error but do not
leave the retry flag intact.

In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx`:
- Around line 287-299: claudeCliRule and claudeCliCacheCount currently match and
index cache by the mutable display name; change claudeCliRule to locate the
Claude rule by a stable identifier (e.g., rule.id or rule.rule_type) instead of
rule.name (update the useMemo that defines claudeCliRule), and then compute
claudeCliCacheCount by looking up cacheStats using that stable id (e.g.,
cacheStats.by_rule_id[stableId]) with a fallback to the name if needed; update
the useMemo dependencies (claudeCliRule, cacheStats) accordingly so the cache
count no longer drops when admins rename the rule.
🪄 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: 2440eebc-180f-43bf-9673-04b6b1d3fda2

📥 Commits

Reviewing files that changed from the base of the PR and between 8c8661d and 8540f1e.

📒 Files selected for processing (6)
  • middleware/distributor.go
  • service/channel_affinity.go
  • service/channel_affinity_template_test.go
  • setting/operation_setting/channel_affinity_setting.go
  • setting/operation_setting/channel_affinity_setting_test.go
  • web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx

Comment thread middleware/distributor.go
Comment on lines +456 to +474
adminInfo := map[string]interface{}{
"cache_cleared": cacheCleared,
}
service.AppendChannelAffinityAdminInfo(c, adminInfo)

logger.LogWarn(
c.Request.Context(),
fmt.Sprintf(
"event=fallback_triggered status=affinity_channel_unavailable decision_reason=%s model=%s channel_id=%d channel_name=%q channel_status=%d using_group=%s request_path=%s cache_cleared=%t",
decisionReason,
modelName,
channelID,
channelName,
channelStatus,
usingGroup,
c.Request.URL.Path,
cacheCleared,
),
)

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.

⚠️ Potential issue | 🟡 Minor

The enriched affinity context is dropped on this warning path.

service.AppendChannelAffinityAdminInfo mutates adminInfo, but nothing logs or stores that map afterward. The fallback warning therefore still loses the rule/key context this call was meant to attach.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/distributor.go` around lines 456 - 474,
service.AppendChannelAffinityAdminInfo mutates adminInfo but the mutated map is
never recorded; include the enriched adminInfo in the fallback path so the
rule/key context is preserved—after calling
service.AppendChannelAffinityAdminInfo(c, adminInfo) pass the mutated adminInfo
into the logger.LogWarn call (e.g., add admin_info=%v to the formatted message)
so the enriched map is logged, or alternatively call the existing
persistence/attach function that records adminInfo for the request before
emitting the warning; reference AppendChannelAffinityAdminInfo, adminInfo and
logger.LogWarn.

Comment on lines +238 to +255
func ClearCurrentChannelAffinity(c *gin.Context) bool {
if c == nil {
return false
}
cacheKey, _, ok := getChannelAffinityContext(c)
if !ok || strings.TrimSpace(cacheKey) == "" {
return false
}

cache := getChannelAffinityCache()
if _, err := cache.DeleteMany([]string{cacheKey}); err != nil {
common.SysError(fmt.Sprintf("channel affinity cache delete failed: key=%s, err=%v", cacheKey, err))
return false
}

c.Set(ginKeyChannelAffinitySkipRetry, false)
return true
}

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.

⚠️ Potential issue | 🟠 Major

Always reset the current-request retry gate, even when cache eviction fails.

middleware.Distribute keeps routing after this helper returns false. On the error path here, ginKeyChannelAffinitySkipRetry stays untouched, so ShouldSkipRetryAfterChannelAffinityFailure() can still read the old rule’s SkipRetry=true and suppress retries for the fallback channel.

Proposed fix
 func ClearCurrentChannelAffinity(c *gin.Context) bool {
 	if c == nil {
 		return false
 	}
+	c.Set(ginKeyChannelAffinitySkipRetry, false)
 	cacheKey, _, ok := getChannelAffinityContext(c)
 	if !ok || strings.TrimSpace(cacheKey) == "" {
 		return false
 	}
 
 	cache := getChannelAffinityCache()
 	if _, err := cache.DeleteMany([]string{cacheKey}); err != nil {
 		common.SysError(fmt.Sprintf("channel affinity cache delete failed: key=%s, err=%v", cacheKey, err))
 		return false
 	}
-
-	c.Set(ginKeyChannelAffinitySkipRetry, false)
 	return true
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@service/channel_affinity.go` around lines 238 - 255,
ClearCurrentChannelAffinity currently leaves ginKeyChannelAffinitySkipRetry
unchanged when cache.DeleteMany fails, allowing
ShouldSkipRetryAfterChannelAffinityFailure to see an old SkipRetry=true; ensure
the retry gate is always reset by setting c.Set(ginKeyChannelAffinitySkipRetry,
false) regardless of delete outcome (either move that c.Set before calling
getChannelAffinityCache/DeleteMany or use a defer to set it immediately in
ClearCurrentChannelAffinity), keep error logging of
getChannelAffinityCache().DeleteMany and still return false on error but do not
leave the retry flag intact.

Comment on lines +287 to +299
const claudeCliRule = useMemo(
() =>
(rules || []).find(
(rule) => (rule?.name || '').trim().toLowerCase() === 'claude cli trace',
) || null,
[rules],
);

const claudeCliCacheCount = useMemo(() => {
const name = (claudeCliRule?.name || '').trim();
if (!name) return 0;
return Number(cacheStats?.by_rule_name?.[name] || 0);
}, [cacheStats, claudeCliRule]);

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.

⚠️ Potential issue | 🟠 Major

The Claude shortcut is tied to a mutable display name.

claudeCliRule only resolves when rule.name === 'claude cli trace', but this screen lets admins rename rules. After a rename, the count drops to 0 and the “清空 Claude Code 缓存” shortcut stops working even though the Claude rule still exists.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 287
- 299, claudeCliRule and claudeCliCacheCount currently match and index cache by
the mutable display name; change claudeCliRule to locate the Claude rule by a
stable identifier (e.g., rule.id or rule.rule_type) instead of rule.name (update
the useMemo that defines claudeCliRule), and then compute claudeCliCacheCount by
looking up cacheStats using that stable id (e.g.,
cacheStats.by_rule_id[stableId]) with a fallback to the name if needed; update
the useMemo dependencies (claudeCliRule, cacheStats) accordingly so the cache
count no longer drops when admins rename the rule.

This branch has not been deployed

No deployments
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.

1 participant