Files
OmniRoute/tests/unit/combo/execute-target-gates.test.ts
Bob.Hou c75e293a47 fix(api): thread X-OmniRoute-Fallback-Attempts through combo chat (#12339) (#13038)
Right call not to reuse the combo loop's `fallbackCount`: it only increments after a leg fails or is skipped, so the second target would still report 0 at dispatch. Stamping the ordered index (or round-robin offset) at the gate is the only place the number is actually known. This PR also carries the batch's file-size rebaseline, since it merges first and the ceiling has to cover every intermediate state.

---

Validated in one consolidated worktree cut from `release/v3.8.51`, boarded with the other 19 PRs of this batch. Two in-batch conflicts, both additive and resolved by keeping each side: the `ENVIRONMENT.md` table (#13035 + #13011) and the `chatHelpers.ts` import block (#12975 on the tip + #13017).

- `typecheck:core` clean; `check:dashboard-typecheck` OK (206 pre-existing, within baseline); `check:changelog-integrity` OK; `check:docs-counts` migrations ✓
- complexity 2816 / baseline 3218 and cognitive-complexity 1271 / baseline 1437 — both under baseline
- 531 of 532 focused assertions green across the batch's 46 test files
- `check-file-size` rebaselined for the batch's real growth (annotation `_rebaseline_2026_09_11_mergebatch_v3851_houminxi`, landed on #13038), attributed per PR

The single red is **not this batch**: `tests/unit/combo/quota-weighted-strategy.test.ts` → "A/B isolation: 7 hard-empty + 2 at 0.5% + 1 at 40%, floor=1" asserts an order between two connections of identical weight and flakes on the pure tip too — 2 failures in 4 runs at `origin/release/v3.8.51` with nothing from this batch applied.

⚠️ base-red inherited: #12732 — `Docs Gates`, `Merge integrity`, `No new ESLint warnings`, `Unit Tests fast-path` and `Fast Quality Gates` reproduce on the pure tip (provider count 356 vs the 358 the modules define, SKILL.md drift, and `open-sse/utils/stream.ts` at 3115 > frozen 3098, untouched here).

Thanks @HouMinXi — the live evidence on these (X500 logs, `storage.sqlite` state, real `/v1/models` probes, the 36-minute outage write-up) is what let a 20-PR batch be reviewed as a unit.
2026-09-11 19:27:33 -03:00

225 lines
7.3 KiB
TypeScript

/**
* Characterization for executeTarget pre-dispatch gates
* (open-sse/services/combo/executeTargetGates.ts).
*/
import test from "node:test";
import assert from "node:assert/strict";
import { getCircuitBreaker, STATE } from "../../../src/shared/utils/circuitBreaker.ts";
import type {
AttemptLoopDeps,
AttemptLoopState,
GateDecision,
} from "../../../open-sse/services/combo/attemptLoopTypes.ts";
import type { ResolvedComboTarget } from "../../../open-sse/services/combo/types.ts";
test("attemptLoopTypes exports GateDecision discriminant", async () => {
const mod = await import("../../../open-sse/services/combo/attemptLoopTypes.ts");
assert.equal(typeof mod, "object");
});
function emptyState(overrides: Partial<AttemptLoopState> = {}): AttemptLoopState {
return {
orderedTargets: [],
fallbackCount: 0,
recordedAttempts: 0,
comboErrors: [],
lastError: null,
lastStatus: null,
earliestRetryAfter: null,
comboExpired: false,
exhaustedProviders: new Set(),
exhaustedConnections: new Set(),
transientRateLimitedProviders: new Set(),
abortControllers: new Map([[0, new AbortController()]]),
dispatchedTargets: new Set(),
targetFailureTrust: new Map(),
comboAttemptOrder: [],
skippedForCircuitOpen: false,
earliestCircuitOpenRetryMs: 0,
globalAttempts: 0,
observedFailure: false,
allObservedFailuresQuota: true,
observeFailure() {},
...overrides,
};
}
function baseDeps(overrides: Partial<AttemptLoopDeps> = {}): AttemptLoopDeps {
const handleSingleModelWithTimeout = async () => {
throw new Error("handleSingleModel must not be called from gates");
};
return {
strategy: "priority",
combo: { name: "t", models: [] },
config: {},
log: { info() {}, warn() {}, debug() {}, error() {} },
settings: null,
resilienceSettings: {
providerCooldown: { enabled: false },
} as AttemptLoopDeps["resilienceSettings"],
sticky: { targets: [], messageHash: null, stuck: false },
effectiveSessionId: null,
preScreenMap: new Map(),
quotaCutoffResetWindowConfig: {} as AttemptLoopDeps["quotaCutoffResetWindowConfig"],
maxRetries: 0,
traceInvocationId: "inv-test",
clientRequestedStream: false,
handleSingleModelWithTimeout,
body: { messages: [{ role: "user", content: "hi" }] },
startTime: Date.now(),
releaseStickyPinOnFailure() {},
clearStaleLKGP() {},
...overrides,
};
}
function modelTarget(overrides: Partial<ResolvedComboTarget> = {}): ResolvedComboTarget {
return {
kind: "model",
stepId: "s1",
executionKey: "ek-1",
modelStr: "openai/gpt-4o",
provider: "openai",
providerId: null,
connectionId: "c1",
weight: 1,
label: null,
...overrides,
};
}
test("breaker OPEN skips and does not call handleSingleModel", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const provider = `openai-gates-test-${Date.now()}`;
const cb = getCircuitBreaker(provider, { failureThreshold: 1, resetTimeout: 60_000 });
cb._onFailure("transient");
assert.equal(cb.getStatus().state, STATE.OPEN);
const target = modelTarget({ provider, modelStr: `${provider}/gpt-4o-mini` });
const state = emptyState({ orderedTargets: [target] });
const decision: GateDecision = await evaluateExecuteTargetGates({
index: 0,
state,
deps: baseDeps(),
});
assert.equal(decision.kind, "skip");
assert.equal(state.skippedForCircuitOpen, true);
});
test("exhausted connection skip uses getExhaustedTargetSkipReason", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const target = modelTarget({ connectionId: "conn-1", provider: "openai" });
const state = emptyState({
orderedTargets: [target],
exhaustedConnections: new Set(["openai:conn-1"]),
});
const decision = await evaluateExecuteTargetGates({ index: 0, state, deps: baseDeps() });
assert.equal(decision.kind, "skip");
if (decision.kind === "skip") {
assert.equal(decision.result, null);
}
});
test("quota cutoff skipped for strategy auto", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const target = modelTarget();
const state = emptyState({ orderedTargets: [target] });
const decision = await evaluateExecuteTargetGates({
index: 0,
state,
deps: baseDeps({ strategy: "auto" }),
});
assert.equal(decision.kind, "proceed");
});
test("protected priority non-quota skip returns 503 response not null", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const target = modelTarget({
connectionId: "c1",
fallbackOnlyOnQuotaExhaustion: true,
});
const state = emptyState({
orderedTargets: [target],
exhaustedConnections: new Set(["openai:c1"]),
});
const decision = await evaluateExecuteTargetGates({
index: 0,
state,
deps: baseDeps({ strategy: "priority" }),
});
assert.equal(decision.kind, "skip");
if (decision.kind === "skip") {
assert.equal(decision.result?.ok, false);
assert.equal(decision.result?.response?.status, 503);
}
});
test("proceed stamps fallbackAttempts from the ordered-target index", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const first = modelTarget({ executionKey: "ek-0", stepId: "s0" });
const second = modelTarget({ executionKey: "ek-1", stepId: "s1" });
const state = emptyState({
orderedTargets: [first, second],
abortControllers: new Map([
[0, new AbortController()],
[1, new AbortController()],
]),
});
const firstDecision = await evaluateExecuteTargetGates({
index: 0,
state,
deps: baseDeps(),
});
const secondDecision = await evaluateExecuteTargetGates({
index: 1,
state,
deps: baseDeps(),
});
assert.equal(firstDecision.kind, "proceed");
assert.equal(secondDecision.kind, "proceed");
if (firstDecision.kind === "proceed") {
assert.equal(
(firstDecision.targetForAttempt as ResolvedComboTarget & { fallbackAttempts?: number })
.fallbackAttempts,
0
);
}
if (secondDecision.kind === "proceed") {
assert.equal(
(secondDecision.targetForAttempt as ResolvedComboTarget & { fallbackAttempts?: number })
.fallbackAttempts,
1
);
}
});
test("injection: dropping fallbackAttempts from targetForAttempt goes red", async () => {
const { evaluateExecuteTargetGates } =
await import("../../../open-sse/services/combo/executeTargetGates.ts");
const first = modelTarget({ executionKey: "ek-0", stepId: "s0" });
const second = modelTarget({ executionKey: "ek-1", stepId: "s1" });
const state = emptyState({
orderedTargets: [first, second],
abortControllers: new Map([
[0, new AbortController()],
[1, new AbortController()],
]),
});
const decision = await evaluateExecuteTargetGates({
index: 1,
state,
deps: baseDeps(),
});
assert.equal(decision.kind, "proceed");
if (decision.kind === "proceed") {
assert.equal(
Object.prototype.hasOwnProperty.call(decision.targetForAttempt, "fallbackAttempts"),
true
);
}
});