333 lines
23 KiB
TypeScript
333 lines
23 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { test } from "node:test"
|
|
import { routeAiProfileSchema, type RouteObservation } from "@mmapp/contracts/mcp-routing"
|
|
import { rankRoutingCandidates, decideRoutingSwitch, selectFailoverReserveProbes, type ControllerState, type PathHealth } from "./routing-model.js"
|
|
|
|
const now = Date.parse("2026-10-17T10:00:00Z"), at = new Date(now).toISOString()
|
|
const profile = routeAiProfileSchema.parse({ name: "Test", serverId: 1, community: "65000:10", family: "ipv4", candidates: [
|
|
{ id: "a", jumpHostId: 2, exitNodeId: 3, wanInterface: "wan-a", downstreamInterface: "exit-a", gateway: "10.0.0.1", gatewayRef: { resource: "ipv4_route", id: "*a" } },
|
|
{ id: "b", jumpHostId: 4, exitNodeId: 3, wanInterface: "wan-b", downstreamInterface: "exit-b", gateway: "10.0.0.2", gatewayRef: { resource: "ipv4_route", id: "*b" } },
|
|
] })
|
|
function sample(id: string, src: number, dst: number, iface: string, values: Partial<RouteObservation> = {}): RouteObservation {
|
|
return { id, srcServerId: src, dstServerId: dst, srcInterface: iface, dstInterface: "peer", family: "ipv4", table: "main", contextVerified: true, pingMs: 10, lossPct: 1, dlMbps: 100, ulMbps: 50, pingAt: at, bandwidthAt: at, ...values }
|
|
}
|
|
const a = [sample("a1", 1, 2, "wan-a"), sample("a2", 2, 3, "exit-a", { dlMbps: 80, ulMbps: 40 })]
|
|
|
|
test("durable charge count limits a controller with empty legacy history without synthetic timestamps", () => {
|
|
const active = { ...profile, confirmationSamples: 1, cooldownSec: 0, switchThreshold: 0, hysteresis: 0 }
|
|
const ranking = rankRoutingCandidates(active, [...a.map(row => ({ ...row, pingMs: 100 })), sample("b1", 1, 4, "wan-b", { pingMs: 1 }), sample("b2", 4, 3, "exit-b", { pingMs: 1 })], now)
|
|
const allowed = decideRoutingSwitch(active, {}, ranking, "a", now, [], 0)
|
|
assert.equal(allowed.switchTo, "b")
|
|
const stopped = decideRoutingSwitch(active, {}, ranking, "a", now, [], active.maxSwitchesPerHour)
|
|
assert.equal(stopped.switchTo, null); assert.equal(stopped.state.pausedReason, "Лимит переключений")
|
|
assert.deepEqual(stopped.state.switches, [])
|
|
assert.throws(() => decideRoutingSwitch(active, { switches: [at] }, ranking, "a", now, [], 0))
|
|
})
|
|
|
|
test("new unknown attempts block older successful data independently for each metric", () => {
|
|
const later = new Date(now + 1).toISOString()
|
|
const unknown = sample("unknown", 1, 2, "wan-a", { contextVerified: false, pingAt: later, bandwidthAt: null, pingMs: null, lossPct: null })
|
|
let ranked = rankRoutingCandidates(profile, [...a, unknown], now + 1).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, null); assert.equal(ranked.eligible, false); assert.equal(ranked.dlMbps, 80)
|
|
const unknownBandwidth = { ...unknown, pingAt: null, bandwidthAt: later }
|
|
ranked = rankRoutingCandidates(profile, [...a, unknownBandwidth], now + 1).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, 20); assert.equal(ranked.dlMbps, null); assert.equal(ranked.eligible, false)
|
|
const pingOnly = routeAiProfileSchema.parse({ ...profile, weights: { ping: 100, speed: 0, loss: 0 } })
|
|
assert.equal(rankRoutingCandidates(pingOnly, [...a, unknownBandwidth], now + 1).find(row => row.candidate.id === "a")!.eligible, true)
|
|
const tampered = { ...unknown, sourceVerified: false, recordedAt: later, pingAt: null, bandwidthAt: null }
|
|
ranked = rankRoutingCandidates(profile, [...a, tampered], now + 1).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, null); assert.equal(ranked.dlMbps, null)
|
|
ranked = rankRoutingCandidates(profile, [...a, { ...tampered, pingAt: new Date(now - 1).toISOString() }], now + 1).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, null, "Invalid latest publication cannot fall back by editing metric timestamps")
|
|
})
|
|
test("failover requires three distinct failures and a freshly verified eligible standby", () => {
|
|
const ranking = rankRoutingCandidates(profile, [...a, sample("b1", 1, 4, "wan-b"), sample("b2", 4, 3, "exit-b")], now)
|
|
let state: ControllerState = {}
|
|
const health = (id: string, time = now, status: PathHealth["status"] = "failed"): PathHealth[] => {
|
|
const observedAt = new Date(time).toISOString()
|
|
return [{ id, candidateId: "a", status, observedAt }, { id: "reserve", candidateId: "b", status: "passed", observedAt }]
|
|
}
|
|
for (let i = 0; i < 5; i++) { const next = decideRoutingSwitch(profile, state, ranking, "a", now, health("one")); state = next.state; assert.equal(next.switchTo, null) }
|
|
assert.equal(state.failureCount, 1)
|
|
const secondAt = now + 60000, thirdAt = now + 120000
|
|
const second = decideRoutingSwitch(profile, state, ranking, "a", secondAt, health("two", secondAt)); assert.equal(second.switchTo, null)
|
|
assert.equal(decideRoutingSwitch(profile, second.state, ranking, "a", thirdAt, health("three", thirdAt)).switchTo, "b")
|
|
const unknown = decideRoutingSwitch(profile, second.state, ranking, "a", thirdAt, health("three", thirdAt, "unknown"))
|
|
assert.equal(unknown.switchTo, null)
|
|
assert.equal(unknown.state.failureObservedAt, undefined)
|
|
assert.equal(decideRoutingSwitch(profile, { ...second.state, switches: [at, at, at] }, ranking, "a", thirdAt, health("three", thirdAt)).switchTo, null)
|
|
assert.equal(decideRoutingSwitch(profile, second.state, ranking, "a", thirdAt + 100000, health("three", thirdAt)).switchTo, null)
|
|
})
|
|
test("failover starts a fresh series after downtime or legacy state and ignores reordered failures", () => {
|
|
const ranking = rankRoutingCandidates(profile, [...a, sample("b1", 1, 4, "wan-b"), sample("b2", 4, 3, "exit-b")], now)
|
|
const last = now + 60000
|
|
const persisted: ControllerState = JSON.parse(JSON.stringify({ failureCount: 2, failureKey: "two",
|
|
failureObservedAt: new Date(last).toISOString(), failingCandidateId: "a" }))
|
|
const check = (state: ControllerState, id: string, time: number, clock = time) => {
|
|
const observedAt = new Date(time).toISOString()
|
|
return decideRoutingSwitch(profile, state, ranking, "a", clock,
|
|
[{ id, candidateId: "a", status: "failed", observedAt }, { id: "reserve", candidateId: "b", status: "passed", observedAt }])
|
|
}
|
|
for (const result of [check(persisted, "two", last + 60000), check(persisted, "older", last - 1000, last),
|
|
check(persisted, "clock-rollback", last - 1000), check(persisted, "equal-time", last)]) {
|
|
assert.equal(result.switchTo, null)
|
|
assert.equal(result.state.failureCount, 2)
|
|
assert.equal(result.state.failureObservedAt, persisted.failureObservedAt)
|
|
}
|
|
for (const [state, time] of [[persisted, now + 4 * 3600000], [{ ...persisted, failureObservedAt: undefined }, last + 60000]] as const) {
|
|
const result = check(state, "next", time)
|
|
assert.equal(result.switchTo, null)
|
|
assert.equal(result.state.failureCount, 1)
|
|
assert.equal(result.state.failureObservedAt, new Date(time).toISOString())
|
|
}
|
|
})
|
|
test("bounded failover probing keeps the highest eligible reserve and eventually visits every other eligible probe", () => {
|
|
const controlProbe = { targetInterface: "exit-a", expectedHops: [{ serverId: 3, interface: "exit-a" }] }
|
|
const configured = routeAiProfileSchema.parse({ ...profile, excludedCandidateIds: ["05"],
|
|
candidates: Array.from({ length: 100 }, (_, index) => ({ ...profile.candidates[0], id: String(index).padStart(2, "0"),
|
|
controlProbe: index === 4 ? undefined : controlProbe })) })
|
|
const ranking = rankRoutingCandidates(configured, a, now)
|
|
const expected = ranking.filter(row => row.eligible && row.candidate.controlProbe && !["00", "01"].includes(row.candidate.id)).map(row => row.candidate.id)
|
|
let cursor: string | undefined
|
|
for (const alternate of expected) {
|
|
const probes = selectFailoverReserveProbes(ranking, "00", cursor)
|
|
assert.deepEqual(probes.candidateIds, ["01", alternate])
|
|
assert.equal(probes.cursor, alternate)
|
|
cursor = probes.cursor
|
|
}
|
|
assert.deepEqual(selectFailoverReserveProbes(ranking, "00", cursor).candidateIds, ["01", "02"])
|
|
assert.deepEqual(selectFailoverReserveProbes(ranking, "00", "05").candidateIds, ["01", "02"])
|
|
const pinned = rankRoutingCandidates({ ...configured, pinnedCandidateId: "09" }, a, now)
|
|
assert.deepEqual(selectFailoverReserveProbes(pinned, "00"), { candidateIds: ["09"], cursor: undefined })
|
|
assert.deepEqual(selectFailoverReserveProbes(pinned, "09"), { candidateIds: [], cursor: undefined })
|
|
})
|
|
test("routing combines RTT, independent losses and bottleneck speed, never claims an observed path", () => {
|
|
const ranked = rankRoutingCandidates(profile, a, now).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, 20); assert.ok(Math.abs(ranked.lossPct! - 1.99) < 0.00001)
|
|
assert.equal(ranked.dlMbps, 80); assert.equal(ranked.ulMbps, 40); assert.equal(ranked.observedPath, false)
|
|
})
|
|
test("fresh ping preserves an independent bandwidth sample for the exact same link", () => {
|
|
const ranked = rankRoutingCandidates(profile, [...a, sample("new-ping", 1, 2, "wan-a", { pingMs: 2, pingAt: new Date(now + 1).toISOString(), bandwidthAt: null, dlMbps: null, ulMbps: null })], now + 1).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.pingMs, 12); assert.equal(ranked.dlMbps, 80)
|
|
assert.ok(ranked.observationIds.includes("a1")); assert.ok(ranked.observationIds.includes("new-ping"))
|
|
})
|
|
test("reverse measurements swap download/upload relative to the analyzed source", () => {
|
|
const reverse = sample("reverse", 2, 1, "peer", { dstInterface: "wan-a", dlMbps: 30, ulMbps: 90 })
|
|
const ranked = rankRoutingCandidates(profile, [reverse, a[1]], now).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.dlMbps, 80); assert.equal(ranked.ulMbps, 30)
|
|
})
|
|
test("unknown, stale, wrong VRF/family/interface and unverified samples do not rank", () => {
|
|
for (const values of [{ contextVerified: false }, { table: "other" }, { family: "ipv6" as const }, { srcInterface: "another" }, { pingAt: new Date(now - 301000).toISOString() }, { bandwidthAt: null }, { lossPct: null }]) {
|
|
const ranked = rankRoutingCandidates(profile, [{ ...a[0], ...values }, a[1]], now).find(row => row.candidate.id === "a")!
|
|
assert.equal(ranked.eligible, false); assert.equal(ranked.score, null)
|
|
}
|
|
})
|
|
test("exclusions, pin and SLA prohibit an otherwise measurable candidate", () => {
|
|
for (const patch of [{ excludedCandidateIds: ["a"] }, { pinnedCandidateId: "b" }, { maxPingMs: 15 }, { minBandwidthMbps: 50 }]) {
|
|
assert.equal(rankRoutingCandidates({ ...profile, ...patch }, a, now).find(row => row.candidate.id === "a")!.eligible, false)
|
|
}
|
|
})
|
|
test("controller does not count polling the same sample as consecutive confirmation", () => {
|
|
const observations = [...a.map(row => ({ ...row, pingMs: 100 })), sample("b1", 1, 4, "wan-b", { pingMs: 1 }), sample("b2", 4, 3, "exit-b", { pingMs: 1 })]
|
|
const ranks = rankRoutingCandidates(profile, observations, now)
|
|
let state: ControllerState = {}
|
|
for (let index = 0; index < 10; index++) { const next = decideRoutingSwitch(profile, state, ranks, "a", now); state = next.state; assert.equal(next.switchTo, null) }
|
|
assert.equal(state.consecutive, 1)
|
|
for (let index = 0; index < 2; index++) {
|
|
observations[2].id += "new"; const next = decideRoutingSwitch(profile, state, rankRoutingCandidates(profile, observations, now), "a", now); state = next.state
|
|
assert.equal(next.switchTo, index === 1 ? "b" : null)
|
|
}
|
|
assert.equal(decideRoutingSwitch(profile, { ...state, lastSwitchAt: at }, ranks, "a", now).switchTo, null)
|
|
assert.equal(decideRoutingSwitch(profile, { ...state, switches: [at, at, at] }, ranks, "a", now).switchTo, null)
|
|
assert.equal(decideRoutingSwitch(profile, state, ranks, null, now).switchTo, null)
|
|
})
|
|
|
|
test("controller counts only samples used for ranking or SLA and resets an old mixed streak", () => {
|
|
const slow = a.map(row => ({ ...row, pingMs: 100, bandwidthAt: null, dlMbps: null, ulMbps: null }))
|
|
const base = [...slow, sample("b1", 1, 4, "wan-b", { pingMs: 1, bandwidthAt: null, dlMbps: null, ulMbps: null }),
|
|
sample("b2", 4, 3, "exit-b", { pingMs: 1, bandwidthAt: null, dlMbps: null, ulMbps: null })]
|
|
const bandwidth = base.map(row => ({ ...row, id: `bw-${row.id}`, pingAt: null, pingMs: null, lossPct: null,
|
|
bandwidthAt: at, dlMbps: 100, ulMbps: 100 }))
|
|
const pingOnly = routeAiProfileSchema.parse({ ...profile, weights: { ping: 100, speed: 0, loss: 0 } })
|
|
const decide = (configured: typeof profile, state: ControllerState, observations: RouteObservation[]) => {
|
|
const ranks = rankRoutingCandidates(configured, observations, now + 20)
|
|
const confirmation = new Map(ranks.map(row => [row.candidate.id, row.confirmation]))
|
|
return decideRoutingSwitch(configured, state, ranks, "a", now + 20, [], undefined, confirmation)
|
|
}
|
|
let state: ControllerState = { pendingCandidateId: "b", consecutive: 2, observationKey: "old-mixed-key" }
|
|
for (let i = 0; i < 3; i++) {
|
|
const observations = [...base, ...bandwidth, { ...bandwidth[2], id: `bw-new-${i}`, bandwidthAt: new Date(now + i + 1).toISOString() }]
|
|
const result = decide(pingOnly, state, observations)
|
|
assert.equal(result.switchTo, null)
|
|
assert.equal(result.state.consecutive, 1)
|
|
state = result.state
|
|
}
|
|
assert.equal(state.observationKey, "ping:a1:a2:b1:b2")
|
|
const fresh = (i: number) => [...base, ...bandwidth, { ...base[2], id: `ping-new-${i}`, pingAt: new Date(now + i + 1).toISOString() }]
|
|
const second = decide(pingOnly, state, fresh(1))
|
|
assert.equal(second.state.consecutive, 2)
|
|
assert.equal(decide(pingOnly, second.state, fresh(1)).state.consecutive, 2)
|
|
assert.equal(decide(pingOnly, second.state, fresh(2)).switchTo, "b")
|
|
|
|
const withBandwidthSla = routeAiProfileSchema.parse({ ...pingOnly, minBandwidthMbps: 10 })
|
|
const initial = decide(withBandwidthSla, {}, [...base, ...bandwidth])
|
|
const updated = decide(withBandwidthSla, initial.state, [...base, ...bandwidth, {
|
|
...bandwidth[2], id: "new-sla-sample", bandwidthAt: new Date(now + 1).toISOString(),
|
|
}])
|
|
assert.equal(initial.state.observationKey, "a1:a2:b1:b2:bw-a1:bw-a2:bw-b1:bw-b2")
|
|
assert.equal(updated.state.consecutive, 2)
|
|
|
|
const bandwidthOnly = routeAiProfileSchema.parse({ ...profile, weights: { ping: 0, speed: 100, loss: 0 } })
|
|
const unequalBandwidth = bandwidth.map((row, i) => ({ ...row, dlMbps: i < 2 ? 20 : 800, ulMbps: i < 2 ? 20 : 800 }))
|
|
const speedInitial = decide(bandwidthOnly, {}, [...base, ...unequalBandwidth])
|
|
const speedWithNewPing = decide(bandwidthOnly, speedInitial.state, [...base, ...unequalBandwidth, fresh(1).at(-1)!])
|
|
assert.equal(speedInitial.state.observationKey, "bandwidth:bw-a1:bw-a2:bw-b1:bw-b2")
|
|
assert.equal(speedWithNewPing.state.consecutive, 1)
|
|
assert.equal(speedWithNewPing.switchTo, null)
|
|
})
|
|
|
|
test("an unknown current path breaks the confirmation streak without making the last sample reusable", () => {
|
|
const configured = routeAiProfileSchema.parse({ ...profile, pingFreshnessSec: 10, weights: { ping: 100, speed: 0, loss: 0 } })
|
|
const observations = [...a.map(row => ({ ...row, pingMs: 100 })), sample("b1", 1, 4, "wan-b", { pingMs: 1 }), sample("b2", 4, 3, "exit-b", { pingMs: 1 })]
|
|
const decide = (state: ControllerState, rows: RouteObservation[], time: number) => {
|
|
const ranks = rankRoutingCandidates(configured, rows, time)
|
|
const confirmation = new Map(ranks.map(row => [row.candidate.id, row.confirmation]))
|
|
return decideRoutingSwitch(configured, state, ranks, "a", time, [], undefined, confirmation)
|
|
}
|
|
const initial = decide({}, observations, now)
|
|
const newer = observations.map(row => ({ ...row, id: row.id + "-next", pingAt: new Date(now + 1000).toISOString() }))
|
|
const second = decide(initial.state, newer, now + 1000)
|
|
assert.equal(second.state.consecutive, 2)
|
|
const unavailable = decide(second.state, newer.slice(2), now + 1000)
|
|
assert.equal(decide(unavailable.state, newer, now + 1000).state.consecutive, 0)
|
|
const outageAt = now + 12_000
|
|
const reserve = newer.slice(2).map(row => ({ ...row, id: row.id + "-outage", pingAt: new Date(outageAt).toISOString() }))
|
|
const outage = decide(second.state, [...newer, ...reserve], outageAt)
|
|
assert.equal(outage.state.consecutive, 0)
|
|
assert.equal(outage.state.pendingCandidateId, undefined)
|
|
assert.equal(outage.state.observationKey, second.state.observationKey)
|
|
assert.equal(outage.switchTo, null)
|
|
const restored = newer.map(row => ({ ...row, id: row.id + "-restored", pingAt: new Date(outageAt + 1000).toISOString() }))
|
|
const firstAfterOutage = decide(outage.state, restored, outageAt + 1000)
|
|
assert.equal(firstAfterOutage.state.consecutive, 1)
|
|
assert.equal(firstAfterOutage.switchTo, null)
|
|
})
|
|
|
|
test("missed ticks cannot carry expired or unbounded confirmations into a new comparison", () => {
|
|
const configured = routeAiProfileSchema.parse({ ...profile, pingFreshnessSec: 10, weights: { ping: 100, speed: 0, loss: 0 } })
|
|
const rankAt = (time: number) => {
|
|
const pingAt = new Date(time).toISOString()
|
|
return rankRoutingCandidates(configured, [
|
|
...a.map(row => ({ ...row, pingMs: 100 })),
|
|
sample("b1", 1, 4, "wan-b", { pingMs: 1 }), sample("b2", 4, 3, "exit-b", { pingMs: 1 }),
|
|
].map(row => ({ ...row, pingAt, id: `${row.id}-${time}` })), time)
|
|
}
|
|
const first = decideRoutingSwitch(configured, {}, rankAt(now), "a", now)
|
|
const secondAt = now + 1_000
|
|
const second = decideRoutingSwitch(configured, first.state, rankAt(secondAt), "a", secondAt)
|
|
assert.equal(second.state.consecutive, 2)
|
|
const boundary = secondAt + 10_000
|
|
const persisted: ControllerState = JSON.parse(JSON.stringify(second.state))
|
|
assert.equal(decideRoutingSwitch(configured, persisted, rankAt(boundary), "a", boundary).switchTo, "b")
|
|
|
|
for (const window of [persisted.confirmationWindow, undefined, { evaluatedAtMs: secondAt, validUntilMs: Infinity }]) {
|
|
const resumedAt = boundary + 1
|
|
const resumed = decideRoutingSwitch(configured, { ...persisted, confirmationWindow: window }, rankAt(resumedAt), "a", resumedAt)
|
|
assert.equal(resumed.switchTo, null)
|
|
assert.equal(resumed.state.consecutive, 1)
|
|
}
|
|
const noBound = decideRoutingSwitch(configured, { ...persisted, confirmationWindow: undefined }, rankAt(secondAt), "a", secondAt)
|
|
assert.equal(noBound.state.consecutive, 0)
|
|
assert.equal(noBound.state.observationKey, persisted.observationKey)
|
|
const rolledBack = decideRoutingSwitch(configured, persisted, rankAt(now), "a", now)
|
|
assert.equal(rolledBack.state.consecutive, 1)
|
|
assert.equal(rolledBack.switchTo, null)
|
|
})
|
|
|
|
test("a decision delayed beyond the oldest relevant leg cannot use an earlier eligible ranking", () => {
|
|
const configured = routeAiProfileSchema.parse({ ...profile, pingFreshnessSec: 60, bandwidthFreshnessSec: 60, confirmationSamples: 1 })
|
|
const ranks = rankRoutingCandidates(configured, [
|
|
...a.map(row => ({ ...row, pingMs: 100 })), sample("b1", 1, 4, "wan-b", { pingMs: 1 }),
|
|
sample("b2", 4, 3, "exit-b", { pingMs: 1, bandwidthAt: new Date(now - 59_000).toISOString() }),
|
|
], now)
|
|
assert.equal(ranks.every(row => row.eligible), true)
|
|
const confirmation = new Map(ranks.map(row => [row.candidate.id, row.confirmation]))
|
|
const publicRanks = ranks.map(({ confirmation: _private, ...row }) => row)
|
|
assert.equal(decideRoutingSwitch(configured, {}, publicRanks, "a", now + 1_000, [], undefined, confirmation).switchTo, "b")
|
|
assert.equal(decideRoutingSwitch(configured, {}, publicRanks, "a", now + 1_001, [], undefined, confirmation).switchTo, null)
|
|
assert.equal(decideRoutingSwitch(configured, {}, publicRanks, "a", now, [], undefined, new Map()).switchTo, null)
|
|
|
|
const beforeThirdFailure = { failureCount: 2, failureKey: "previous", failureObservedAt: at, failingCandidateId: "a" }
|
|
const failedOverAt = (time: number) => {
|
|
const observedAt = new Date(time).toISOString()
|
|
return decideRoutingSwitch(configured, beforeThirdFailure, publicRanks, "a", time, [
|
|
{ id: "third", candidateId: "a", status: "failed", observedAt },
|
|
{ id: "reserve", candidateId: "b", status: "passed", observedAt },
|
|
], undefined, confirmation)
|
|
}
|
|
assert.equal(failedOverAt(now + 1_000).switchTo, "b")
|
|
assert.equal(failedOverAt(now + 1_001).switchTo, null)
|
|
assert.equal(failedOverAt(now + 1_001).state.failureCount, 3)
|
|
})
|
|
|
|
test("hysteresis retains pending confirmation without counting sub-threshold observations or releasing cooldown", () => {
|
|
const ranked = rankRoutingCandidates(profile, [...a, sample("b1", 1, 4, "wan-b"), sample("b2", 4, 3, "exit-b")], now)
|
|
const compare = (state: ControllerState, gain: number, observation: string, time = now) => {
|
|
const ranks = ["b", "a"].map(id => ({ ...ranked.find(row => row.candidate.id === id)!,
|
|
score: id === "a" ? 50 : 50 + gain, observationIds: [id + observation] }))
|
|
return decideRoutingSwitch(profile, state, ranks, "a", time)
|
|
}
|
|
|
|
const initial = compare({}, 15, "1").state
|
|
assert.equal(initial.consecutive, 1)
|
|
for (const [gain, observation] of [[6, "2"], [5, "3"]] as const) {
|
|
const result = compare(initial, gain, observation)
|
|
assert.equal(result.switchTo, null)
|
|
assert.deepEqual(result.state, initial)
|
|
}
|
|
const reset = compare(initial, 4, "4")
|
|
assert.equal(reset.state.pendingCandidateId, undefined)
|
|
assert.equal(reset.state.consecutive, 0)
|
|
|
|
const second = compare(initial, 15, "5")
|
|
assert.equal(second.switchTo, null)
|
|
const afterCooldown = now + 100_000
|
|
const lastSwitchAt = new Date(afterCooldown - profile.cooldownSec * 1000).toISOString()
|
|
const third = compare({ ...second.state, lastSwitchAt }, 15, "6")
|
|
assert.equal(third.state.consecutive, 3)
|
|
assert.equal(third.switchTo, null)
|
|
|
|
assert.equal(compare(third.state, 6, "7", afterCooldown).switchTo, null)
|
|
assert.equal(compare(third.state, 15, "8", afterCooldown).switchTo, "b")
|
|
})
|
|
|
|
test("a different pending candidate cannot borrow confirmations from a shared observation key", () => {
|
|
const ranks = rankRoutingCandidates(profile, [...a, sample("b1", 1, 4, "wan-b"), sample("b2", 4, 3, "exit-b")], now)
|
|
.map(row => ({ ...row, score: row.candidate.id === "a" ? 50 : 75 }))
|
|
.sort((left, right) => right.score - left.score)
|
|
const observationKey = ranks.flatMap(row => row.observationIds).sort().join(":")
|
|
const persisted: ControllerState = { pendingCandidateId: "previous-candidate", consecutive: 3, observationKey }
|
|
const selected = decideRoutingSwitch(profile, persisted, ranks, "a", now)
|
|
assert.equal(selected.switchTo, null)
|
|
assert.equal(selected.state.pendingCandidateId, "b")
|
|
assert.equal(selected.state.consecutive, 0)
|
|
assert.equal(selected.state.observationKey, observationKey)
|
|
|
|
const replay = decideRoutingSwitch(profile, selected.state, ranks, "a", now)
|
|
assert.equal(replay.switchTo, null)
|
|
assert.equal(replay.state.consecutive, 0)
|
|
|
|
const freshRanks = [{ ...ranks[0], observationIds: ["new-b-1", "new-b-2"] }, ranks[1]]
|
|
const fresh = decideRoutingSwitch(profile, replay.state, freshRanks, "a", now)
|
|
assert.equal(fresh.state.consecutive, 1)
|
|
assert.equal(fresh.switchTo, null)
|
|
|
|
const belowFloor = [{ ...freshRanks[0], score: 54 }, freshRanks[1]]
|
|
const reset = decideRoutingSwitch(profile, fresh.state, belowFloor, "a", now)
|
|
assert.equal(reset.state.pendingCandidateId, undefined)
|
|
assert.equal(reset.state.consecutive, 0)
|
|
const replayAfterReset = decideRoutingSwitch(profile, reset.state, freshRanks, "a", now)
|
|
assert.equal(replayAfterReset.switchTo, null)
|
|
assert.equal(replayAfterReset.state.consecutive, 0)
|
|
})
|