Spaces:
Paused
Paused
Anurag commited on
Enhance task affinity settings for key rotation
Browse filesUpdated task affinity settings to improve handling of in-flight requests and prevent mid-task key switches. Increased default values for task affinity duration and maximum reuses to accommodate complex tasks.
- multi-provider-key-rotator.cjs +56 -13
multi-provider-key-rotator.cjs
CHANGED
|
@@ -83,6 +83,16 @@ const MAX_INFLIGHT_PER_KEY = Math.max(
|
|
| 83 |
const STICKY_IGNORE_INFLIGHT_SATURATION = !/^(0|false|no|off)$/i.test(
|
| 84 |
String(process.env.KEY_STICKY_IGNORE_INFLIGHT_SATURATION || 'true').trim(),
|
| 85 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
const COOLDOWN_JITTER_PCT = Math.min(
|
| 87 |
50,
|
| 88 |
Math.max(0, parseInt(process.env.KEY_BLACKLIST_JITTER_PCT || '', 10) || 15),
|
|
@@ -160,21 +170,30 @@ const STICKY_PROVIDER_SET = new Set(
|
|
| 160 |
);
|
| 161 |
const UNKNOWN_MODEL_SCOPE = '__unknown_model__';
|
| 162 |
|
| 163 |
-
// Task affinity keeps
|
| 164 |
-
//
|
| 165 |
-
//
|
| 166 |
-
// per-request round-robin would spend a different key
|
| 167 |
-
//
|
| 168 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
const RAW_TASK_AFFINITY_MS = parseInt(process.env.KEY_TASK_AFFINITY_MS || '', 10);
|
| 170 |
const TASK_AFFINITY_MS = Math.max(
|
| 171 |
0,
|
| 172 |
-
Number.isFinite(RAW_TASK_AFFINITY_MS) ? RAW_TASK_AFFINITY_MS :
|
| 173 |
);
|
| 174 |
const RAW_TASK_AFFINITY_MAX_REUSES = parseInt(process.env.KEY_TASK_AFFINITY_MAX_REUSES || '', 10);
|
| 175 |
const TASK_AFFINITY_MAX_REUSES = Math.max(
|
| 176 |
0,
|
| 177 |
-
Number.isFinite(RAW_TASK_AFFINITY_MAX_REUSES) ? RAW_TASK_AFFINITY_MAX_REUSES :
|
| 178 |
);
|
| 179 |
|
| 180 |
// Maximum ms to respect from a Retry-After header.
|
|
@@ -636,7 +655,17 @@ function rememberTaskAffinityKey(p, model, key) {
|
|
| 636 |
// second affinity system on top, otherwise diagnostics and expiry semantics
|
| 637 |
// become harder to reason about.
|
| 638 |
if (isStickyProvider(p)) return;
|
| 639 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 640 |
key,
|
| 641 |
expiresAt: Date.now() + TASK_AFFINITY_MS,
|
| 642 |
remainingReuses: TASK_AFFINITY_MAX_REUSES,
|
|
@@ -676,12 +705,25 @@ function pickAffinitizedKey(p, model) {
|
|
| 676 |
return null;
|
| 677 |
}
|
| 678 |
const inflight = p.inFlight.get(key) || 0;
|
| 679 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
entry.remainingReuses -= 1;
|
| 681 |
entry.expiresAt = Date.now() + TASK_AFFINITY_MS;
|
| 682 |
if (entry.remainingReuses <= 0) p.taskAffinity.delete(bucket);
|
| 683 |
-
|
| 684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
return { key, waitMs: 0 };
|
| 686 |
}
|
| 687 |
|
|
@@ -2639,7 +2681,7 @@ if (hasProviderKeys) {
|
|
| 2639 |
patchUndici(); // covers OpenClaw gateway's bundled undici AI calls
|
| 2640 |
startDiagnostics();
|
| 2641 |
|
| 2642 |
-
debug(`[key-rotator] loaded β cooldown base:${BASE_COOLDOWN_MS/1000}s max-strikes:${MAX_STRIKES} perm-suspend:${formatHours(PERM_SUSPEND_MS)}h (cap 16h) max-inflight-per-key:${MAX_INFLIGHT_PER_KEY} max-retry-after:${MAX_RETRY_AFTER_MS/1000}s max-key-wait:${MAX_KEY_WAIT_MS/1000}s diagnostics:${DIAGNOSTICS_ENABLED ? 'on' : 'off'} log-level:${LOG_LEVEL} verbose-picks:${VERBOSE_PICKS ? 'on' : 'off'} suspended-last-resort:${USE_SUSPENDED_KEY_AS_LAST_RESORT ? 'on' : 'off'} per-model-providers:${providerState.filter(p => p.perModelLimits).map(p => p.name).join(',') || 'none'} model-from-body:on model-sniff-max:${REQUEST_MODEL_SNIFF_MAX_BYTES} error-sniff-max:${ERROR_BODY_SNIFF_MAX_BYTES} error-body-wait:${ERROR_BODY_WAIT_MS}ms inflight-ttl:${INFLIGHT_TTL_MS}ms task-affinity:${TASK_AFFINITY_MS}ms/${TASK_AFFINITY_MAX_REUSES}reuses sticky-until-failure:${STICKY_UNTIL_FAILURE ? 'on' : 'off'} sticky-ignore-inflight-saturation:${STICKY_IGNORE_INFLIGHT_SATURATION ? 'on' : 'off'} sticky-scope:${String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto'} sticky-providers:${[...STICKY_PROVIDER_SET].join(',') || 'none'} llm-fallback-providers:${LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET].join(',') : 'all'}`);
|
| 2643 |
emitEvent('rotator_loaded', null, null, {
|
| 2644 |
providers: providerState.filter(p => p.keys.length).map(p => ({ name: p.name, total: p.keys.length })),
|
| 2645 |
logLevel: LOG_LEVEL,
|
|
@@ -2649,6 +2691,7 @@ if (hasProviderKeys) {
|
|
| 2649 |
errorBodySniffMaxBytes: ERROR_BODY_SNIFF_MAX_BYTES,
|
| 2650 |
taskAffinityMs: TASK_AFFINITY_MS,
|
| 2651 |
taskAffinityMaxReuses: TASK_AFFINITY_MAX_REUSES,
|
|
|
|
| 2652 |
stickyUntilFailure: STICKY_UNTIL_FAILURE,
|
| 2653 |
stickyIgnoreInflightSaturation: STICKY_IGNORE_INFLIGHT_SATURATION,
|
| 2654 |
stickyScope: String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto',
|
|
|
|
| 83 |
const STICKY_IGNORE_INFLIGHT_SATURATION = !/^(0|false|no|off)$/i.test(
|
| 84 |
String(process.env.KEY_STICKY_IGNORE_INFLIGHT_SATURATION || 'true').trim(),
|
| 85 |
);
|
| 86 |
+
// Task-affinity keys: same reasoning as sticky β in-flight leases are local
|
| 87 |
+
// bookkeeping only. When the affinity key reaches MAX_INFLIGHT_PER_KEY,
|
| 88 |
+
// re-using it (with a warning) keeps the whole task on one key. The
|
| 89 |
+
// alternative β dropping affinity and letting round-robin pick a new key β
|
| 90 |
+
// causes exactly the mid-task API-key switch the user observes.
|
| 91 |
+
// FIX: default changed to true so non-sticky providers (Anthropic, OpenAI, etc.)
|
| 92 |
+
// are protected from mid-task rotation just like Gemini sticky keys.
|
| 93 |
+
const TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION = !/^(0|false|no|off)$/i.test(
|
| 94 |
+
String(process.env.KEY_AFFINITY_IGNORE_INFLIGHT_SATURATION || 'true').trim(),
|
| 95 |
+
);
|
| 96 |
const COOLDOWN_JITTER_PCT = Math.min(
|
| 97 |
50,
|
| 98 |
Math.max(0, parseInt(process.env.KEY_BLACKLIST_JITTER_PCT || '', 10) || 15),
|
|
|
|
| 170 |
);
|
| 171 |
const UNKNOWN_MODEL_SCOPE = '__unknown_model__';
|
| 172 |
|
| 173 |
+
// Task affinity keeps sequential non-sticky provider calls on the same key for
|
| 174 |
+
// an entire task window. OpenClaw/HuggingClaw splits one user task into many
|
| 175 |
+
// upstream requests (planning β tool calls β result synthesis β follow-ups);
|
| 176 |
+
// pure per-request round-robin would spend a different key on every chunk and
|
| 177 |
+
// cause visible mid-task provider switches.
|
| 178 |
+
//
|
| 179 |
+
// FIX: defaults raised from 30 s / 3 reuses to 300 s / 50 reuses.
|
| 180 |
+
// - 30 s was too short: complex tasks (deep research, multi-tool chains) easily
|
| 181 |
+
// exceed it, causing a key switch at the 31st second.
|
| 182 |
+
// - 3 reuses was too low: a single OpenClaw task can involve 5-20+ upstream
|
| 183 |
+
// calls (think β tool β observe β think β tool β synthesize β¦). After the
|
| 184 |
+
// 3rd call the rotator picked a fresh key mid-task.
|
| 185 |
+
// Round-robin load-balancing still resumes when a *new* task starts (affinity
|
| 186 |
+
// expires or key fails), so fairness across keys is preserved over time.
|
| 187 |
+
// Sticky providers (Gemini) use their stronger until-failure pin and are unaffected.
|
| 188 |
const RAW_TASK_AFFINITY_MS = parseInt(process.env.KEY_TASK_AFFINITY_MS || '', 10);
|
| 189 |
const TASK_AFFINITY_MS = Math.max(
|
| 190 |
0,
|
| 191 |
+
Number.isFinite(RAW_TASK_AFFINITY_MS) ? RAW_TASK_AFFINITY_MS : 300_000, // 5 min β covers full task burst
|
| 192 |
);
|
| 193 |
const RAW_TASK_AFFINITY_MAX_REUSES = parseInt(process.env.KEY_TASK_AFFINITY_MAX_REUSES || '', 10);
|
| 194 |
const TASK_AFFINITY_MAX_REUSES = Math.max(
|
| 195 |
0,
|
| 196 |
+
Number.isFinite(RAW_TASK_AFFINITY_MAX_REUSES) ? RAW_TASK_AFFINITY_MAX_REUSES : 50, // 50 calls β covers any task
|
| 197 |
);
|
| 198 |
|
| 199 |
// Maximum ms to respect from a Retry-After header.
|
|
|
|
| 655 |
// second affinity system on top, otherwise diagnostics and expiry semantics
|
| 656 |
// become harder to reason about.
|
| 657 |
if (isStickyProvider(p)) return;
|
| 658 |
+
const bucket = stickyBucketForProvider(p, model);
|
| 659 |
+
// FIX: do NOT reset a still-valid affinity slot for the same key.
|
| 660 |
+
// rememberTaskAffinityKey is called from nextKey's round-robin path every time
|
| 661 |
+
// ANY key is picked (including the saturated-reuse fallback). Overwriting a
|
| 662 |
+
// live entry here would silently refill remainingReuses and extend expiresAt,
|
| 663 |
+
// hiding the mid-task switch that TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION is
|
| 664 |
+
// meant to guard against. Only create/replace when the bucket is empty,
|
| 665 |
+
// pointing at a different key, or the existing entry has expired/exhausted.
|
| 666 |
+
const existing = p.taskAffinity.get(bucket);
|
| 667 |
+
if (existing && existing.key === key && Date.now() < existing.expiresAt && (existing.remainingReuses || 0) > 0) return;
|
| 668 |
+
p.taskAffinity.set(bucket, {
|
| 669 |
key,
|
| 670 |
expiresAt: Date.now() + TASK_AFFINITY_MS,
|
| 671 |
remainingReuses: TASK_AFFINITY_MAX_REUSES,
|
|
|
|
| 705 |
return null;
|
| 706 |
}
|
| 707 |
const inflight = p.inFlight.get(key) || 0;
|
| 708 |
+
const saturated = inflight >= MAX_INFLIGHT_PER_KEY;
|
| 709 |
+
// FIX: when the affinity key is saturated, do NOT return null.
|
| 710 |
+
// Returning null here drops affinity and sends the caller back to round-robin,
|
| 711 |
+
// which picks a DIFFERENT key mid-task β the exact bug reported.
|
| 712 |
+
// In-flight counts are local safety leases (they expire via INFLIGHT_TTL_MS),
|
| 713 |
+
// not real provider verdicts; a saturated key is almost certainly still healthy.
|
| 714 |
+
// Mirror sticky-provider behaviour: stay pinned and warn, rotate only on a
|
| 715 |
+
// real provider failure (auth / rate / transient from handleStatus).
|
| 716 |
+
if (saturated && !TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION) return null;
|
| 717 |
entry.remainingReuses -= 1;
|
| 718 |
entry.expiresAt = Date.now() + TASK_AFFINITY_MS;
|
| 719 |
if (entry.remainingReuses <= 0) p.taskAffinity.delete(bucket);
|
| 720 |
+
if (saturated) {
|
| 721 |
+
warn(`[key-rotator] ${p.name}: task-affinity key saturated but staying pinned on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY} remaining-reuses=${Math.max(0, entry.remainingReuses || 0)} (affinity protects mid-task key switch)`);
|
| 722 |
+
emitEvent('task_affinity_saturated_reuse', p, key, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, ttlMs: TASK_AFFINITY_MS, remainingReuses: Math.max(0, entry.remainingReuses || 0), sticky: false, reason: 'affinity_until_real_failure' });
|
| 723 |
+
} else {
|
| 724 |
+
verbosePickLog(`[key-rotator] ${p.name}: task-affinity picked ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY} remaining-reuses=${Math.max(0, entry.remainingReuses)}`);
|
| 725 |
+
emitEvent('task_affinity_pick', p, key, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, ttlMs: TASK_AFFINITY_MS, remainingReuses: Math.max(0, entry.remainingReuses), sticky: false });
|
| 726 |
+
}
|
| 727 |
return { key, waitMs: 0 };
|
| 728 |
}
|
| 729 |
|
|
|
|
| 2681 |
patchUndici(); // covers OpenClaw gateway's bundled undici AI calls
|
| 2682 |
startDiagnostics();
|
| 2683 |
|
| 2684 |
+
debug(`[key-rotator] loaded β cooldown base:${BASE_COOLDOWN_MS/1000}s max-strikes:${MAX_STRIKES} perm-suspend:${formatHours(PERM_SUSPEND_MS)}h (cap 16h) max-inflight-per-key:${MAX_INFLIGHT_PER_KEY} max-retry-after:${MAX_RETRY_AFTER_MS/1000}s max-key-wait:${MAX_KEY_WAIT_MS/1000}s diagnostics:${DIAGNOSTICS_ENABLED ? 'on' : 'off'} log-level:${LOG_LEVEL} verbose-picks:${VERBOSE_PICKS ? 'on' : 'off'} suspended-last-resort:${USE_SUSPENDED_KEY_AS_LAST_RESORT ? 'on' : 'off'} per-model-providers:${providerState.filter(p => p.perModelLimits).map(p => p.name).join(',') || 'none'} model-from-body:on model-sniff-max:${REQUEST_MODEL_SNIFF_MAX_BYTES} error-sniff-max:${ERROR_BODY_SNIFF_MAX_BYTES} error-body-wait:${ERROR_BODY_WAIT_MS}ms inflight-ttl:${INFLIGHT_TTL_MS}ms task-affinity:${TASK_AFFINITY_MS}ms/${TASK_AFFINITY_MAX_REUSES}reuses task-affinity-ignore-inflight:${TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION ? 'on' : 'off'} sticky-until-failure:${STICKY_UNTIL_FAILURE ? 'on' : 'off'} sticky-ignore-inflight-saturation:${STICKY_IGNORE_INFLIGHT_SATURATION ? 'on' : 'off'} sticky-scope:${String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto'} sticky-providers:${[...STICKY_PROVIDER_SET].join(',') || 'none'} llm-fallback-providers:${LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET].join(',') : 'all'}`);
|
| 2685 |
emitEvent('rotator_loaded', null, null, {
|
| 2686 |
providers: providerState.filter(p => p.keys.length).map(p => ({ name: p.name, total: p.keys.length })),
|
| 2687 |
logLevel: LOG_LEVEL,
|
|
|
|
| 2691 |
errorBodySniffMaxBytes: ERROR_BODY_SNIFF_MAX_BYTES,
|
| 2692 |
taskAffinityMs: TASK_AFFINITY_MS,
|
| 2693 |
taskAffinityMaxReuses: TASK_AFFINITY_MAX_REUSES,
|
| 2694 |
+
taskAffinityIgnoreInflightSaturation: TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION,
|
| 2695 |
stickyUntilFailure: STICKY_UNTIL_FAILURE,
|
| 2696 |
stickyIgnoreInflightSaturation: STICKY_IGNORE_INFLIGHT_SATURATION,
|
| 2697 |
stickyScope: String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto',
|