diff --git a/.prettierignore b/.prettierignore index 92641fe..2d45652 100644 --- a/.prettierignore +++ b/.prettierignore @@ -6,3 +6,5 @@ js lib types package-lock.json +# Vendored byte-for-byte from absmartly/abs; never reformat. +src/__tests__/fixtures/switchback diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..72471d1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## 1.14.0 (unreleased) + +Earlier release notes are on the [GitHub releases page](https://github.com/absmartly/javascript-sdk/releases); the [Migration Guide](README.md#migration-guide-113x--1140) lists the other changes in 1.14.0. + +### Added + +- Switchback experiments (R33, cluster-defined): an experiment with `randomizationType: "switchback"` is served by cluster and period through the existing `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()`, matching the collector and java-sdk. `ExperimentData` gains the optional `randomizationType`, `switchbackClusters`, `switchbackClusterValues`, `switchbackStartAt`, `switchbackPeriodMs`, `switchbackCarryoverDurationMs`, `switchbackBurnInDurationMs`, `switchbackBurnOutDurationMs`, `switchbackDesignType` and `switchbackEstimand` fields. There is no new method or option. See [Switchback Experiments](README.md#switchback-experiments). +- Known limitation: JavaScript cannot tell `3.0` from `3`, so a cluster attribute set to an integral float is keyed like the integer (`"3"`), where other SDKs give a float no cluster value. A cluster map with two or more linked unit types, one named like an array index (`"1"`), cannot keep its declared order in JavaScript, so it is served as an ineligible control (variant 0, no exposure). + +### Changed + +- Shared variable keys pick and expose one experiment, as the Java SDK does. Before, `variableValue()` exposed every experiment it checked that had the key, including ones the unit was not in (for example a strict audience mismatch or a switchback that gives way), which recorded users in experiments they never saw; and when the first experiment's selected variant lacked the key, a later experiment's value was served and exposed, so which experiment a unit was counted in depended on its arm, biasing the result. Now candidates are the experiments defining the key in any variant, by experiment id ascending; the winner is the first one the unit is in (assigned, overridden or rule-assigned), whatever its arm, and returns its variant's value (`null`, `false`, `0` and `""` included) or the caller default if that variant lacks the key. With no winner, a held-out candidate supplies its control value, otherwise the caller default. Only the winner is exposed (an out-of-range overridden, custom or full-on winner is exposed with that variant; a silent switchback winner, before its schedule starts or with an ineligible cluster, returns control and records nothing); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. A `variableValue()` read queues all its exposures before its `exposure` and `error` callbacks run, and a `treatment()` with holdouts queues its exposures before their `exposure` callbacks (an audience `error` raised by `treatment()` itself is still reported first), so a callback that calls `finalize()` or `publish()` sends every one of them; such a callback now sees them already pending. Callbacks a callback raises are replayed after the ones already held, in queue order; once a replay has run a bounded number of rounds or callbacks, each later call delivers its own callbacks as soon as all of its exposures are queued, so runaway logger feedback stays bounded in stack and memory and each call still sends its whole batch. A cached `variableValue()` or `peekVariableValue()` (four experiments sharing a key) is about 3x faster than the previous unreleased build (about 21–26 vs 65 ns, versus about 155 ns in 1.13.4) and no longer allocates; `treatment()` and `peek()` are unchanged within noise (shared-host measurements, approximate). A cached assignment or switchback slot whose arm a refresh removes returns the caller default (1.13.4 kept serving the removed arm's value) and gets the arm's values back if a later refresh restores it. Keys no experiment defines return the default, including names like `toString` or `__proto__`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Who moves: anyone with two or more running experiments sharing a variable key, and anyone counting exposures from `variableValue()` on an experiment the unit is not in (use `treatment()` to record those). +- Switchback experiments that are already running change assignment for this SDK: before, they were served as a sticky unit assignment on their `unitType` (or not at all), which did not follow the switchback schedule. Now each unit gets its cluster's scheduled variant for the current period unless an override, assignment rule, strict audience mismatch, full-on setting, a not-yet-started schedule (control, no exposure), a traffic miss or `customAssignment()` decides it first (see Switchback Experiments in the README for the exact order), and exposures are recorded once per period under the serving unit, while that period's assignment stays cached. Who moves: customers who run switchback experiments. The switchback support itself does not change unit experiments or context data without switchbacks; the separate shared-variable-key fix above can change their variable reads. diff --git a/README.md b/README.md index 2b47e7d..e9a586b 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,23 @@ const defaultButtonColor = "red"; const buttonColor = context.variableValue("button.color", defaultButtonColor); ``` +#### Shared variable keys + +When several experiments define the same variable key, the SDK checks them in +ascending experiment id and uses the first one the user is in (assigned, +overridden or assigned by a rule). Its variant's value is returned, or your +default if that variant does not define the key; later experiments are never +used instead. If the user is in none of them but one is held out by a holdout, +the first held-out experiment's control value is returned, or your default if +its control arm does not define the key (no other experiment is checked). Only +the winning experiment gets an exposure (plus any holdouts covering the +experiments checked); a held-out experiment that supplies its control value +records only its holdout's exposure. An experiment the user is not in, such as a +strict audience mismatch, gets none; call `treatment()` to record it. A +switchback that wins but is silent (before its schedule starts, or with an +ineligible cluster) returns its control value and records nothing, and later +experiments are still not used. `peekVariableValue()` never queues an exposure. + ### Peek at Treatment Variants Although generally not recommended, it is sometimes necessary to peek at a treatment without triggering an exposure. The A/B Smartly SDK provides a `peek()` method for that. @@ -252,6 +269,29 @@ context.overrides({ }); ``` +### Switchback Experiments + +A switchback experiment randomizes *clusters* over time instead of units. A cluster is a value of a context attribute, for example a store's region. Every unit in the same cluster sees the same variant during a period, and the variant changes on a fixed time grid. There is nothing new to call: `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()` serve switchback experiments, and the A/B Smartly collector sends their configuration with the context data. + +```javascript +context.units({ store_id: "store-1234" }); +// The experiment links the store_id unit type to the attribute path "region". +context.attribute("region", "lisbon"); + +const variant = context.treatment("exp_delivery_fee"); // the "lisbon" cluster's variant for this period +``` + +How a switchback is served (the contract the A/B Smartly collector serves; java-sdk implements the same): + +- **Cluster.** The experiment lists linked unit types, each with an attribute path, in a significant order. For each linked type the context has a unit of, in that order, the SDK reads the attribute at the path. The first unit that gives a value serves, and its value is the cluster key. If a later unit gives a different value, the cluster is ineligible. +- **Values.** A non-empty string is used as-is, and a whole number below `1e21` in magnitude as its decimal text (`17` and `"17"` are the same cluster). Numbers beyond `Number.MAX_SAFE_INTEGER` lose precision in JavaScript before the SDK sees them, so set large identifiers as strings. Fractions, booleans, objects, arrays, empty strings and `null` give no value. **JavaScript cannot tell `3.0` from `3`**, so a number written as `3.0` is the cluster `"3"`, like the integer; other SDKs give a float no value. Set cluster attributes as strings or integers. A cluster map whose unit type names look like array indexes (`"1"`, `"2"`) cannot keep its order in JavaScript, so with two or more linked types such an experiment is served as an ineligible control. +- **Paths.** `/` separates segments (`profile/region`, `items/0/region`), a quoted segment is a literal key (`'a/b'`), and an unquoted number indexes an array. An index must be non-negative and sit between two key segments (`items/0` and `items/0/1/region` are unreadable). A `.` anywhere makes the path unreadable: nest with `/`. The first segment names an attribute set with `attribute()`; the value read is the latest one set at or before the call. +- **No linked unit:** the experiment does not apply (variant 0, nothing recorded; a variable lookup returns its default), though an `override()` still applies and is recorded. **Ineligible cluster** (no value, units disagree, or a value outside the experiment's allowed values): variant 0 and no exposure, unless an `override()` is set, which still applies and is recorded under the first linked unit present. **Unreadable cluster map** (missing, empty or with an unreadable path): an ineligible control when the context has a unit of the experiment's `unitType`, otherwise the experiment does not apply. +- **Precedence** for an eligible cluster: `override()`, then assignment rules (a `split` rule randomizes over the serving unit), a strict audience mismatch (variant 0, recorded), full-on, then the schedule. Before the schedule starts, or when it cannot be served, the result is variant 0 with no exposure. Then traffic (on the serving unit; a miss is recorded as not eligible), `customAssignment()`, and the schedule draw over the cluster key. **Holdouts never apply to switchback experiments.** +- **Exposures.** One exposure per experiment and period while that period's assignment stays cached, under the serving unit's type, with the same fields as any other exposure. As for other experiments, an assignment that is resolved again within the period (after a refresh or an attribute change alters its outcome, or a clock moved back past the two retained periods) records another exposure. Its `exposedAt` is the time at which the call chose the period. While the period's assignment stays cached, the cluster is read once: a later `attribute()` in the same period does not move the unit to another cluster, and the next period reads the attributes afresh. A clock moved back past the two retained periods reads the cluster afresh too, and can select a different cluster. Attributes are published as usual; the collector reads the cluster from them. On a variable key shared with other experiments, a switchback follows the same rule as unit experiments (see [Shared variable keys](#shared-variable-keys)): only the winner is exposed, so a strict-mismatched switchback checked before the winner records nothing. + +The schedule follows the device clock (`Date.now()`), so a device whose clock is wrong is served another period's variant. + ## Advanced ### Context Attributes @@ -360,6 +400,15 @@ The data parameter depends on the type of event. Currently, the SDK logs the fol | `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | | `"finalize"` | `finalize()` method succeeds the first time | undefined | +`"exposure"` and `"error"` events raised by one `variableValue()` call (and the +`"exposure"` events of one `treatment()` call) are delivered after all of that +call's exposures are queued, in the order they were raised, so a logger that +calls `publish()` or `finalize()` sends every one of them. `"exposure"` and +`"error"` events a logger triggers itself are delivered after the ones already +waiting (other events, such as a `"goal"` from `track()`, are delivered +immediately); after a bounded number of rounds or callbacks, each later call delivers its own +events together, once all of that call's exposures are queued. + ### HTTP Request Timeout It is possible to set a timeout per individual HTTP request, overriding the global timeout set for all requests when instantiating the SDK object. @@ -554,6 +603,18 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **This changes assignment for running experiments.** In an experiment with Audience enforced (`audienceStrict`) and an `environment` or `application` condition, a unit whose context does not set that attribute itself currently gets variant 0, even when the configured name matches the condition and even when the experiment is full-on. After upgrading, such a unit is randomised normally (or gets the full-on variant) when the configured name matches. Those units are misassigned today; this release fixes them, but their exposures will change. An attribute your context sets itself still overrides the configured name, so its matching does not change. This protection is per attribute: if an audience uses both `application` and `environment` and the context sets only one of them, the configured name for the other can still change the result. An audience or rule on `app_version` no longer matches unless you set `app_version` yourself. +### Switchback experiments are served + +**Before:** this SDK ignored the switchback fields the collector sends. A switchback experiment was served as a sticky unit assignment on its `unitType` (or not at all without one), so its exposures did not follow the switchback schedule. + +**After:** switchback experiments are served by cluster and period, as described in [Switchback Experiments](#switchback-experiments). **This changes assignment for switchback experiments that are already running**: their units move from the sticky unit assignment to the cluster's schedule, and exposures are recorded once per period (while the period's assignment stays cached) under the serving unit. The switchback support itself does not change unit experiments or context data without switchbacks; see [Shared variable keys](#shared-variable-keys-pick-and-expose-one-experiment) below for the separate variable-read fix. + +### Shared variable keys pick and expose one experiment + +**Before:** when several experiments defined the same variable key, `variableValue()` exposed every experiment it checked, including ones the user was not in (for example a strict audience mismatch), and when the first experiment's variant lacked the key it served and exposed a later experiment's value instead. + +**After:** the first experiment by id that the user is in (assigned, overridden or rule-assigned) wins whatever its variant, as in the Java SDK; its variant's value is returned, or your default if that variant lacks the key. Only that experiment is exposed, unless it is a silent switchback (before its schedule starts, or with an ineligible cluster), which returns control and records nothing (see [Shared variable keys](#shared-variable-keys)). **This changes served values and exposures** for users whose winning experiment's variant lacks the key, and removes exposures that `variableValue()` used to record for experiments the user is not in; call `treatment()` if you need those recorded. + ## About A/B Smartly **A/B Smartly** is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics. diff --git a/src/__tests__/context-switchback-cluster.test.js b/src/__tests__/context-switchback-cluster.test.js new file mode 100644 index 0000000..1675464 --- /dev/null +++ b/src/__tests__/context-switchback-cluster.test.js @@ -0,0 +1,532 @@ +import Client from "../client"; +import SDK from "../sdk"; +import Context from "../context"; +import { hashUnit } from "../utils"; +import { VariantAssigner } from "../assigner"; +import { assignSwitchbackPeriod } from "../switchback"; +import { ContextPublisher } from "../publisher"; +import { ContextDataProvider } from "../provider"; + +jest.mock("../client"); +jest.mock("../sdk"); +jest.mock("../provider"); +jest.mock("../publisher"); + +// Port of java-sdk's ContextSwitchbackClusterRuleTest, itself a port of the Collector's +// ContextAPISwitchbackTest ClusterRule section (absmartly/abs 9bd2b5ca35), through the public Context +// API. Switchback "sbc" (id 900, "34/33/33", 1h) is linked to user_id (unit type id 2) at +// "profile/store" and to session_id (unit type id 1) at "session_store", declared in unit type id +// order, so session_id comes first although the user_id link was inserted first. +// +// A context holds one uid per unit type and keeps its units in an object, so the declared source +// order alone decides which unit serves. +const HOUR = 3600000; +const ANCHOR = 1767225600000; +const PERIOD = 5; +const NOW = ANCHOR + PERIOD * HOUR + 17 * 60000; +const SEED_HI = 0x1234; +const SEED_LO = 0x5678abcd; +const TRAFFIC_SEED_HI = 7; +const TRAFFIC_SEED_LO = 11; + +const SESSION = "session_id"; +const USER = "user_id"; + +const sdk = new SDK(); +const client = new Client(); +const publisher = new ContextPublisher(); +const provider = new ContextDataProvider(); + +sdk.getContextDataProvider.mockReturnValue(provider); +sdk.getContextPublisher.mockReturnValue(publisher); +sdk.getClient.mockReturnValue(client); +client.getApplication.mockReturnValue({ name: "website", version: 0 }); +client.getEnvironment.mockReturnValue("production"); + +let clock; +let experiment; +let links; + +function switchbackExperiment(experimentName, id, unitType, split) { + const parts = split.split("/"); + return { + id, + name: experimentName, + unitType, + iteration: 1, + seedHi: SEED_HI, + seedLo: SEED_LO, + split: parts.map((p) => Number(p) / 100), + trafficSeedHi: TRAFFIC_SEED_HI, + trafficSeedLo: TRAFFIC_SEED_LO, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "website" }], + variants: parts.map((p, i) => ({ name: String(i), config: `{"sbc.config":"test config ${i}"}` })), + audience: null, + audienceStrict: false, + customFieldValues: null, + randomizationType: "switchback", + switchbackStartAt: ANCHOR, + switchbackPeriodMs: HOUR, + switchbackDesignType: "balanced_block", + }; +} + +function unitExperiment(experimentName, id, unitType) { + const unit = switchbackExperiment(experimentName, id, unitType, "50/50"); + delete unit.randomizationType; + delete unit.switchbackStartAt; + delete unit.switchbackPeriodMs; + delete unit.switchbackDesignType; + unit.variants = [ + { name: "0", config: null }, + { name: "1", config: null }, + ]; + return unit; +} + +// switchbackClusters in declared (unit type id ascending) order: session_id (1) before user_id (2). +function refreshLinks() { + const clusters = {}; + for (const type of [SESSION, USER, "device_id"]) { + for (const [linkType, path] of links) { + if (linkType === type) clusters[linkType] = path; + } + } + experiment.switchbackClusters = links.length === 0 ? null : clusters; +} + +function unlinkAll() { + links = []; + refreshLinks(); +} + +function link(unitType, path) { + links.push([unitType, path]); + refreshLinks(); +} + +beforeEach(() => { + clock = NOW; + jest.spyOn(Date, "now").mockImplementation(() => clock); + publisher.publish.mockReset(); + publisher.publish.mockReturnValue(Promise.resolve()); + experiment = switchbackExperiment("sbc", 900, USER, "34/33/33"); + unlinkAll(); + link(USER, "profile/store"); + link(SESSION, "session_store"); +}); + +function scheduled(clusterKey) { + return assignSwitchbackPeriod(clusterKey, PERIOD, SEED_HI, SEED_LO, 3); +} + +let exposures; + +function createContext(attributes, experiments, units) { + exposures = []; + const eventLogger = (context, eventName, data) => { + if (eventName === "exposure") exposures.push(data); + }; + const context = new Context(sdk, { publishDelay: -1, refreshPeriod: 0, eventLogger }, { units }, { experiments }); + if (attributes != null) context.attributes(attributes); + return context; +} + +// The cached "sbc" resolution at the clock's current reading (Java's switchbackResolutionForTest). +function resolution(context) { + const periods = Object.values(context._switchbackEpochs?.sbc?.slots ?? {}); + const periodless = context._switchbackEpochs?.sbc?.periodless; + const slots = periodless !== undefined ? [periodless, ...periods] : periods; + expect(slots.length).toEqual(1); + return slots[0]; +} + +// The Collector's ExperimentAssignment for "sbc", or null when it lists none (not applicable). Every +// other experiment is resolved (and exposed) first, so the caches it fills are in place. +function sbcWith(attributes, experiments, units) { + const context = createContext(attributes, experiments, units); + for (const other of experiments) { + if (other.name !== "sbc") context.treatment(other.name); + } + const variant = context.treatment("sbc"); + const resolved = resolution(context); + const config = context.variableValue("sbc.config", null); + const sbcExposures = exposures.filter((e) => e.name === "sbc"); + // Keyed on the serving status, not on assigned: a strict audience mismatch is not assigned yet is + // still an assignment the Collector lists. + if (resolved.switchbackServing.status === 0) { + expect(variant).toEqual(0); + expect(config).toBeNull(); + expect(sbcExposures).toEqual([]); + return null; + } + return { + unit: resolved.unitType, + eligible: resolved.eligible, + silent: resolved.switchbackSilent === true, + variant, + fullOn: resolved.fullOn, + ruleOverride: resolved.ruleOverride, + config, + exposures: sbcExposures, + }; +} + +function sbc(attributes, units) { + return sbcWith(attributes, [experiment], units); +} + +// An ineligible cluster resolution is still an assignment, as control, under the first linked-type +// unit in declared order, and no exposure is recorded for it. +function expectIneligible(attributes, expectedUnit, units) { + const assignment = sbc(attributes, units); + expect(assignment).not.toBeNull(); + expect(assignment).toEqual({ + unit: expectedUnit, + eligible: false, + silent: true, + variant: 0, + fullOn: false, + ruleOverride: false, + config: "test config 0", + exposures: [], + }); +} + +const store = (value) => ({ store: value }); + +describe("switchback cluster rule", () => { + it("returns only a legacy ineligible control for a missing or unreadable cluster configuration", () => { + for (const broken of [ + "null-cluster", + "missing-links", + "unreadable-path", + "geo.city", + "'geo.city'", + '"geo.city"', + "unknown-unit", + ]) { + unlinkAll(); + if (broken === "unreadable-path") { + link(SESSION, "'geo"); + } else if (broken === "unknown-unit") { + // A readable map whose only linked type (device_id) is absent from the context. + link("device_id", "session_store"); + expect([broken, sbc({ session_store: "s-1" }, { [SESSION]: "x1", [USER]: "u1" })]).toEqual([ + broken, + null, + ]); + continue; + } else if (broken === "missing-links") { + experiment.switchbackClusters = {}; + } else if (broken !== "null-cluster") { + link(SESSION, broken); + } + const attributes = { geo: { city: "Porto" }, "geo.city": "Faro", session_store: "s-1" }; + // The declared unit (user_id) only identifies an ineligible control response. + expectIneligible(attributes, USER, { [SESSION]: "x1", [USER]: "u1" }); + // Without a unit of the declared type, there is no response at all. + expect([broken, sbc(attributes, { [SESSION]: "x1" })]).toEqual([broken, null]); + } + }); + + it("uses the serving uid for traffic, not the experiment's unit type uid", () => { + // percentageOfTraffic = 40. + experiment.trafficSplit = [0.6, 0.4]; + const ordinary = unitExperiment("ordinary", 901, USER); + const witnesses = [null, null]; + for (let i = 0; i < 1000 && (witnesses[0] === null || witnesses[1] === null); ++i) { + const uid = `traffic-${i}`; + witnesses[ + new VariantAssigner(hashUnit(uid)).assign([0.6, 0.4], TRAFFIC_SEED_HI, TRAFFIC_SEED_LO) === 0 ? 0 : 1 + ] = uid; + } + expect(witnesses).not.toContain(null); + const key = "s-18"; + // The eligible draw must be distinguishable from control. + expect(scheduled(key)).not.toEqual(0); + for (const servingEligible of [false, true]) { + const assignment = sbcWith({ session_store: key, profile: store(key) }, [experiment, ordinary], { + [SESSION]: witnesses[servingEligible ? 1 : 0], + [USER]: witnesses[servingEligible ? 0 : 1], + }); + expect(assignment.unit).toEqual(SESSION); + expect(assignment.eligible).toEqual(servingEligible); + expect(assignment.variant).toEqual(servingEligible ? scheduled(key) : 0); + // A traffic miss on an eligible cluster is still recorded, under the serving unit. + expect(assignment.exposures.map((e) => [e.unit, e.eligible])).toEqual([[SESSION, servingEligible]]); + } + }); + + it("serves the value of one matching unit", () => { + const assignment = sbc({ profile: store("s-17") }, { [USER]: "u1" }); + + expect(assignment.eligible).toBe(true); + expect(assignment.unit).toEqual(USER); + expect(assignment.variant).toEqual(scheduled("s-17")); + }); + + // A strict audience mismatch on an eligible cluster is not assigned, yet still listed, as control + // under the serving unit, and its exposure is published. + it("lists and records a strict audience mismatch on an eligible cluster as control", () => { + experiment.audience = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}'; + experiment.audienceStrict = true; + const assignment = sbc({ session_store: "s-17" }, { [SESSION]: "x1" }); + + expect(assignment).not.toBeNull(); + expect(assignment.unit).toEqual(SESSION); + expect(assignment.eligible).toBe(true); + expect(assignment.silent).toBe(false); + expect(assignment.variant).toEqual(0); + expect(assignment.exposures.length).toEqual(1); + expect(assignment.exposures[0].audienceMismatch).toBe(true); + expect(assignment.exposures[0].assigned).toBe(false); + }); + + it("serves the value two agreeing units give", () => { + const assignment = sbc({ profile: store("s-17"), session_store: "s-17" }, { [USER]: "u1", [SESSION]: "x1" }); + + expect(assignment.eligible).toBe(true); + expect(assignment.variant).toEqual(scheduled("s-17")); + }); + + it("is ineligible when two units disagree", () => { + // session_id (type id 1) is first in declared order whatever the context order. + expectIneligible({ profile: store("s-17"), session_store: "s-18" }, SESSION, { [USER]: "u1", [SESSION]: "x1" }); + }); + + // A context holds one uid per unit type, so a second session_id is rejected. + it("serves one unit per type", () => { + const key = "s-17"; + expect(scheduled(key)).not.toEqual(0); + const context = createContext({ session_store: key }, [experiment], { [SESSION]: "x1" }); + expect(() => context.unit(SESSION, "x2")).toThrow("Unit 'session_id' UID already set."); + + const assignment = sbc({ session_store: key }, { [SESSION]: "x1" }); + expect(assignment.eligible).toBe(true); + expect(assignment.variant).toEqual(scheduled(key)); + }); + + it("does not apply without a unit of a linked type", () => { + expect(sbc({ session_store: "s-1" }, { device_id: "d1" })).toBeNull(); + expect(sbc({ session_store: "s-1" }, {})).toBeNull(); + }); + + it("is ineligible when the matching unit has no value", () => { + expectIneligible({ other: "s-1" }, USER, { [USER]: "u1" }); + expectIneligible({ other: "s-1" }, SESSION, { [USER]: "u1", [SESSION]: "x1" }); + }); + + it("is ineligible for values that are neither non-empty strings nor whole numbers", () => { + // 3.0 is the integer 3 in JS, so it is not in this list (see "keys whole numbers"). + for (const value of [1.5, -0.25, true, false, { a: 1 }, ["a"], [], "", null, 1e21, NaN, Infinity]) { + expectIneligible({ session_store: value }, SESSION, { [SESSION]: "x1" }); + } + }); + + it("keys whole numbers by their decimal text", () => { + expect(scheduled("17")).not.toEqual(0); + const assignment = sbc({ session_store: 17 }, { [SESSION]: "x1" }); + + expect(assignment.eligible).toBe(true); + expect(assignment.variant).toEqual(scheduled("17")); + // Equal to the string "17" from another unit type, so the two agree. + expect(sbc({ session_store: 17, profile: store("17") }, { [SESSION]: "x1", [USER]: "u1" }).eligible).toBe(true); + // JS cannot tell 3.0 from 3, so 17.0 keys like 17 (documented limitation). + expect(sbc({ session_store: 17.0 }, { [SESSION]: "x1" }).variant).toEqual(scheduled("17")); + // Beyond int32 and 2^53 the decimal text is kept exactly as published. + expect(sbc({ session_store: 4000000002 }, { [SESSION]: "x1" }).variant).toEqual(scheduled("4000000002")); + expect(sbc({ session_store: -3 }, { [SESSION]: "x1" }).variant).toEqual(scheduled("-3")); + }); + + it("reads nested and array paths", () => { + unlinkAll(); + link(SESSION, "items/1/store"); + + const assignment = sbc({ items: [store("a"), store("b")] }, { [SESSION]: "x1" }); + expect(assignment.variant).toEqual(scheduled("b")); + expect(scheduled("a")).not.toEqual(scheduled("b")); + }); + + it("exposes under the first matching unit in declared order whatever the context order", () => { + const key = "s-18"; + expect(scheduled(key)).not.toEqual(0); + const assignment = sbc({ profile: store(key), session_store: key }, { [USER]: "u1", [SESSION]: "x1" }); + + expect(assignment.unit).toEqual(SESSION); + expect(assignment.exposures[0].unit).toEqual(SESSION); + expect(assignment.variant).toEqual(scheduled(key)); + }); + + it("never publishes an exposure for an ineligible cluster", async () => { + const context = createContext({ session_store: "a", profile: store("b") }, [experiment], { + [USER]: "u1", + [SESSION]: "x1", + }); + expect(context.treatment("sbc")).toEqual(0); + expect(context.pending()).toEqual(0); + await context.publish(); + expect(publisher.publish).not.toHaveBeenCalled(); + expect(exposures).toEqual([]); + }); + + it("does not serve a unit without a value even if it is first in declared order", () => { + const key = "s-17"; + expect(scheduled(key)).not.toEqual(0); + const assignment = sbc({ profile: store(key) }, { [SESSION]: "x1", [USER]: "u1" }); + + expect(assignment.unit).toEqual(USER); + expect(assignment.exposures[0].unit).toEqual(USER); + expect(assignment.variant).toEqual(scheduled(key)); + }); + + it("is ineligible for a value outside the allow-list", () => { + experiment.switchbackClusterValues = ["s-1", "s-2"]; + + expectIneligible({ session_store: "s-3" }, SESSION, { [SESSION]: "x1" }); + const allowed = sbc({ session_store: "s-2" }, { [SESSION]: "x1" }); + expect(allowed.eligible).toBe(true); + expect(allowed.variant).toEqual(scheduled("s-2")); + }); + + it("assigns every value with a null or empty allow-list", () => { + for (const values of [null, undefined, []]) { + experiment.switchbackClusterValues = values; + for (let i = 0; i < 20; ++i) { + const assignment = sbc({ session_store: `s-${i}` }, { [SESSION]: "x1" }); + expect(assignment.eligible).toBe(true); + expect(assignment.variant).toEqual(scheduled(`s-${i}`)); + } + } + }); + + // A valid cluster map whose linked types are all absent from the context does not fall back to the + // experiment's declared unitType: no assignment, no exposure. + it("does not fall back to the experiment unit without a linked unit", () => { + unlinkAll(); + link(SESSION, "session_store"); + const key = "s-17"; + expect(scheduled(key)).not.toEqual(0); + + expect(sbc({ session_store: key, profile: store(key) }, { [USER]: "u1" })).toBeNull(); + const linked = sbc({ session_store: key }, { [USER]: "u1", [SESSION]: "x1" }); + expect(linked.unit).toEqual(SESSION); + expect(linked.variant).toEqual(scheduled(key)); + }); + + // The Collector's wire-rule oracle SdkSwitchbackRule, transcribed: period index from the anchor + // re-ceiled to the hour, traffic on the serving uid's hash, then the schedule draw over the cluster + // key. A null cluster key has no draw. It shares the assigners with the SDK, whose parity is pinned + // by the golden vectors, so it is a wire-rule parity check, not an independent oracle. + const NO_PERIOD = null; + function oraclePeriodIndex(e, now) { + if (e.switchbackStartAt == null || e.switchbackPeriodMs == null || e.switchbackPeriodMs <= 0) return NO_PERIOD; + if (e.split == null || e.split.length < 2) return NO_PERIOD; + const anchor = Math.ceil(e.switchbackStartAt / HOUR) * HOUR; + if (now < anchor) return NO_PERIOD; + return Math.floor((now - anchor) / e.switchbackPeriodMs); + } + function oracle(e, uid, clusterKey, now) { + const periodIndex = oraclePeriodIndex(e, now); + if (clusterKey == null || periodIndex === NO_PERIOD) return [0, false]; + const eligible = + new VariantAssigner(hashUnit(uid)).assign(e.trafficSplit, e.trafficSeedHi, e.trafficSeedLo) === 1; + if (!eligible) return [0, false]; + return [assignSwitchbackPeriod(clusterKey, periodIndex, e.seedHi, e.seedLo, e.split.length), true]; + } + + function gridContext(cluster, uid, key) { + unlinkAll(); + link(SESSION, "session_store"); + experiment.switchbackClusterValues = null; + switch (cluster) { + case "DISAGREEING_SECOND_SOURCE": + link(USER, "profile/store"); + return createContext({ session_store: key, profile: store(`${key}-other`) }, [experiment], { + [SESSION]: uid, + [USER]: `u-${uid}`, + }); + case "MISSING_VALUE": + return createContext({ other: key }, [experiment], { [SESSION]: uid }); + case "FILTERED_VALUE": + experiment.switchbackClusterValues = [`${key}-allowed`]; + return createContext({ session_store: key }, [experiment], { [SESSION]: uid }); + default: + return createContext({ session_store: key }, [experiment], { [SESSION]: uid }); + } + } + + it("matches the Collector's wire-rule parity grid", () => { + let eligible = 0; + let ineligible = 0; + let trafficMisses = 0; + for (const cluster of ["SINGLE", "DISAGREEING_SECOND_SOURCE", "MISSING_VALUE", "FILTERED_VALUE"]) { + for (const anchor of [ANCHOR, ANCHOR + 7 * HOUR]) { + for (const periodMs of [HOUR, 2 * HOUR, 24 * HOUR]) { + experiment.trafficSplit = [0.3, 0.7]; + experiment.switchbackStartAt = anchor; + experiment.switchbackPeriodMs = periodMs; + for (let u = 0; u < 6; ++u) { + const uid = `uid-${u}`; + for (const key of ["s-1", "s-2", "42", "Lisboa"]) { + for (const now of [ + anchor - HOUR, + anchor - 1, + anchor, + anchor + periodMs - 1, + anchor + periodMs, + anchor + 3 * periodMs + 5, + anchor + 11 * periodMs, + ]) { + // The attributes are set before the resolving reading. + clock = anchor - HOUR; + const context = gridContext(cluster, uid, key); + clock = now; + const oracleKey = cluster === "SINGLE" ? key : null; + const [oracleVariant, oracleEligible] = oracle(experiment, uid, oracleKey, now); + const message = `${cluster}/${anchor}/${periodMs}/${uid}/${key}/${now}`; + expect([message, context.treatment("sbc")]).toEqual([message, oracleVariant]); + expect([message, resolution(context).eligible]).toEqual([message, oracleEligible]); + // Before the anchor nothing is recorded; from it, a keyed cluster records one + // exposure whose eligibility is the oracle's (a traffic miss included). + const expectedExposures = oracleKey !== null && now >= anchor ? 1 : 0; + expect([message, exposures.length]).toEqual([message, expectedExposures]); + if (expectedExposures === 1) { + expect([message, exposures[0].eligible]).toEqual([message, oracleEligible]); + } + if (cluster === "SINGLE") { + if (oracleEligible) { + ++eligible; + } else { + ++ineligible; + if (now >= anchor) ++trafficMisses; + } + } + } + } + } + } + } + } + expect(eligible).toBeGreaterThan(100); + expect(ineligible).toBeGreaterThan(100); + // Pre-anchor cases alone meet the guard above; this one needs the recorded traffic-miss branch. + expect(trafficMisses).toBeGreaterThan(0); + + // The deliberate divergence: an anchor off the hour is unservable in the SDK (as in the Collector's + // Registry), while the transcribed oracle would re-ceil it and draw. + const unaligned = ANCHOR + 7 * HOUR + 1; + experiment.trafficSplit = [0, 1]; + experiment.switchbackStartAt = unaligned; + experiment.switchbackPeriodMs = HOUR; + clock = ANCHOR + 8 * HOUR + 5; + expect(oraclePeriodIndex(experiment, clock)).not.toBeNull(); + expect(oracle(experiment, "uid-0", "s-1", clock)[1]).toBe(true); + const context = gridContext("SINGLE", "uid-0", "s-1"); + expect(context.treatment("sbc")).toEqual(0); + expect(resolution(context).eligible).toBe(false); + expect(exposures).toEqual([]); + }); +}); diff --git a/src/__tests__/context-switchback-keys.test.js b/src/__tests__/context-switchback-keys.test.js new file mode 100644 index 0000000..1375e40 --- /dev/null +++ b/src/__tests__/context-switchback-keys.test.js @@ -0,0 +1,593 @@ +import Client from "../client"; +import SDK from "../sdk"; +import Context from "../context"; +import { hashUnit } from "../utils"; +import { VariantAssigner } from "../assigner"; +import { assignSwitchbackPeriod } from "../switchback"; +import { ContextPublisher } from "../publisher"; +import { ContextDataProvider } from "../provider"; + +jest.mock("../client"); +jest.mock("../sdk"); +jest.mock("../provider"); +jest.mock("../publisher"); + +// Port of java-sdk's ContextSwitchbackClusterTest: cluster key selection inside Context. Variants are +// derived from the raw key and the assigner, both pinned by the platform golden vectors. +const UNIT_TYPE = "store_id"; +const UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec"; +const HOUR = 3600000; +const ANCHOR = 1767225600000; +const SEED_HI = -5; +const SEED_LO = -7; +// 3 arms over 12 periods: two keys in different buckets are told apart by their schedules. +const ARMS = 3; +const GOLD_AUDIENCE = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}'; + +const sdk = new SDK(); +const client = new Client(); +const publisher = new ContextPublisher(); +const provider = new ContextDataProvider(); + +sdk.getContextDataProvider.mockReturnValue(provider); +sdk.getContextPublisher.mockReturnValue(publisher); +sdk.getClient.mockReturnValue(client); +client.getApplication.mockReturnValue({ name: "website", version: 0 }); +client.getEnvironment.mockReturnValue("production"); + +let clock; + +beforeEach(() => { + clock = ANCHOR; + jest.spyOn(Date, "now").mockImplementation(() => clock); + publisher.publish.mockReset(); + publisher.publish.mockReturnValue(Promise.resolve()); + provider.getContextData.mockReset(); +}); + +function attributeSwitchback(path) { + const split = []; + const variants = []; + for (let i = 0; i < ARMS; ++i) { + split.push(1 / ARMS); + variants.push({ name: String.fromCharCode(65 + i), config: `{"sb.arm":${i}}` }); + } + return { + id: 1, + name: "exp_sb", + unitType: UNIT_TYPE, + iteration: 1, + seedHi: SEED_HI, + seedLo: SEED_LO, + split, + trafficSeedHi: 1, + trafficSeedLo: 2, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "website" }], + variants, + audience: null, + audienceStrict: false, + customFieldValues: null, + randomizationType: "switchback", + switchbackClusters: { [UNIT_TYPE]: path }, + switchbackStartAt: ANCHOR, + switchbackPeriodMs: HOUR, + switchbackCarryoverDurationMs: 0, + switchbackBurnInDurationMs: 0, + switchbackBurnOutDurationMs: 0, + switchbackDesignType: "balanced_block", + switchbackEstimand: "global_average_treatment_effect", + }; +} + +const dataOf = (...experiments) => ({ experiments }); + +function createContext(data, units = { [UNIT_TYPE]: UID }) { + return new Context(sdk, { publishDelay: -1, refreshPeriod: 0 }, { units }, data); +} + +async function refreshTo(context, experiment) { + provider.getContextData.mockReturnValue(Promise.resolve(dataOf(experiment))); + await context.refresh(); +} + +async function publishEvent(context) { + publisher.publish.mockClear(); + await context.publish(); + expect(publisher.publish).toHaveBeenCalledTimes(1); + return publisher.publish.mock.calls[0][0]; +} + +async function publishExposures(context) { + return (await publishEvent(context)).exposures; +} + +// The Collector's draw: the raw cluster key, unhashed. +const expected = (key, periodIndex) => assignSwitchbackPeriod(key, periodIndex, SEED_HI, SEED_LO, ARMS); +const expectedSchedule = (key) => [...Array(12).keys()].map((i) => expected(key, i)); + +function peekSchedule(context) { + const result = []; + for (let i = 0; i < 12; ++i) { + clock = ANCHOR + i * HOUR; + result.push(context.peek("exp_sb")); + } + return result; +} + +function exposure(variant, exposedAt, eligible, audienceMismatch, flags = {}) { + return { + id: 1, + name: "exp_sb", + unit: UNIT_TYPE, + exposedAt, + variant, + assigned: true, + eligible, + overridden: false, + fullOn: false, + custom: false, + audienceMismatch, + ruleOverride: false, + ...flags, + }; +} + +async function exposeAndPublish(context) { + clock = ANCHOR; + context.treatment("exp_sb"); + return publishEvent(context); +} + +describe("switchback cluster keys in Context", () => { + // The unit uid is never the cluster key: with no cluster value the unit is ineligible. + it("never keys the cluster by the unit uid", () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(0); + } + expect(context.pending()).toEqual(0); + }); + + // A numeric uid serves and publishes under its canonical string (toFixed(0)), exactly as the same + // string uid does; the cluster key is the attribute. + it("clusters a numeric unit uid like its canonical string", async () => { + for (const [numeric, text] of [ + [123456789, "123456789"], + [123456789.0, "123456789"], + [2 ** 53 + 1, "9007199254740992"], + [125.75, "126"], + ]) { + const numericContext = createContext(dataOf(attributeSwitchback("city")), { [UNIT_TYPE]: numeric }); + clock = ANCHOR; + numericContext.attribute("city", "Lisboa"); + const numericEvent = await exposeAndPublish(numericContext); + const numericSchedule = peekSchedule(numericContext); + const textContext = createContext(dataOf(attributeSwitchback("city")), { [UNIT_TYPE]: text }); + clock = ANCHOR; + textContext.attribute("city", "Lisboa"); + const textEvent = await exposeAndPublish(textContext); + + expect(numericSchedule).toEqual(expectedSchedule("Lisboa")); + expect(numericSchedule).toEqual(peekSchedule(textContext)); + expect(numericEvent.units).toEqual(textEvent.units); + expect(numericEvent.exposures).toEqual(textEvent.exposures); + expect(numericEvent.units[0].uid).toEqual(hashUnit(text)); + } + }); + + // Independent reference (Python MD5/base64url) for the published hash of numeric uids (2 ** 53 + 1 + // is 2 ** 53 as a double, as in Java), and the + // raw-key schedule of 123456789 as a numeric attribute value (murmur3 reference). + it("matches the independent reference for numeric uids and values", async () => { + const schedule = [0, 2, 1, 0, 1, 2, 0, 1, 2, 2, 1, 0]; + for (const [uid, hash] of [ + [123456789, "JfnnlDI7RTiF9RgfG2JNCw"], + [2 ** 53 + 1, "OngwCmjeKhIQyeNybDy4eg"], + ]) { + const context = createContext(dataOf(attributeSwitchback("region")), { [UNIT_TYPE]: uid }); + clock = ANCHOR; + context.attribute("region", 123456789); + const published = await exposeAndPublish(context); + + expect(published.units[0].uid).toEqual(hash); + expect(published.exposures).toEqual([exposure(schedule[0], ANCHOR, true, false)]); + expect(peekSchedule(context)).toEqual(schedule); + } + }); + + // Periods 0..11 of the raw key "Lisboa", from the independent murmur3 reference. + it("serves the raw attribute value", () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + context.attribute("city", "Lisboa"); + expect(peekSchedule(context)).toEqual([0, 2, 1, 2, 1, 0, 1, 0, 2, 0, 1, 2]); + expect(peekSchedule(context)).toEqual(expectedSchedule("Lisboa")); + }); + + it("gives units sharing an attribute value the same schedule", () => { + const lisboa = createContext(dataOf(attributeSwitchback("city"))); + lisboa.attribute("city", "Lisboa"); + const porto = createContext(dataOf(attributeSwitchback("city"))); + porto.attribute("city", "Porto"); + const otherLisboa = createContext(dataOf(attributeSwitchback("city")), { [UNIT_TYPE]: "another-store" }); + otherLisboa.attribute("city", "Lisboa"); + + expect(peekSchedule(lisboa)).toEqual(expectedSchedule("Lisboa")); + expect(peekSchedule(otherLisboa)).toEqual(expectedSchedule("Lisboa")); + expect(peekSchedule(porto)).toEqual(expectedSchedule("Porto")); + expect(expectedSchedule("Lisboa")).not.toEqual(expectedSchedule("Porto")); + }); + + it("resolves nested and array paths and integer values", () => { + const nested = createContext(dataOf(attributeSwitchback("geo/city"))); + nested.attribute("geo", { city: "Porto" }); + expect(peekSchedule(nested)).toEqual(expectedSchedule("Porto")); + + clock = ANCHOR; + const array = createContext(dataOf(attributeSwitchback("items/1/city"))); + array.attribute("items", [{ city: "Lisbon" }, { city: "Faro" }]); + expect(peekSchedule(array)).toEqual(expectedSchedule("Faro")); + + clock = ANCHOR; + const integer = createContext(dataOf(attributeSwitchback("region"))); + integer.attribute("region", 42); + expect(peekSchedule(integer)).toEqual(expectedSchedule("42")); + + // Values are read through their JSON encoding, as the Collector decodes them. + clock = ANCHOR; + const encoded = createContext(dataOf(attributeSwitchback("geo/city"))); + encoded.attribute("geo", { city: { toJSON: () => 42 } }); + expect(peekSchedule(encoded)).toEqual(expectedSchedule("42")); + + clock = ANCHOR + 10; + const fraction = createContext(dataOf(attributeSwitchback("city"))); + fraction.attribute("city", 2.5); + expect(fraction.treatment("exp_sb")).toEqual(0); + expect(fraction.pending()).toEqual(0); + }); + + // Values that yield no cluster key serve variant 0, not eligible, record no exposure and never throw. + it("is ineligible for values without a cluster key", () => { + // 2.0 is the integer 2 in JS, so it is not in this list. + for (const value of [null, undefined, "", true, 1.5, { a: "b" }, ["x"]]) { + const context = createContext(dataOf(attributeSwitchback("city"))); + context.attribute("city", value); + clock = ANCHOR + 10; + expect([value, context.treatment("exp_sb")]).toEqual([value, 0]); + // Variant 0's own config, like any ineligible assignment. + expect([value, context.variableValue("sb.arm", -1)]).toEqual([value, 0]); + expect([value, context.pending()]).toEqual([value, 0]); + } + + const missing = createContext(dataOf(attributeSwitchback("geo/city"))); + missing.attribute("geo", { country: "PT" }); + clock = ANCHOR + 10; + expect(missing.treatment("exp_sb")).toEqual(0); + expect(missing.pending()).toEqual(0); + }); + + // A value with no JSON encoding has no cluster key. + it("is ineligible for values with no JSON encoding", () => { + const cyclic = {}; + cyclic.self = cyclic; + for (const value of [ + cyclic, + { city: 10n }, + { + toJSON: () => { + throw new Error("no"); + }, + }, + ]) { + const context = createContext(dataOf(attributeSwitchback("geo/city"))); + context.attribute("geo", value); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + } + }); + + // Unservable configurations serve an ineligible control to linked units, never a unit-assignment + // draw, and record nothing. + it("is an ineligible control for unservable configurations", () => { + const experiments = ["items/0", "items/-1/city", "", "geo.city", "'city", '"city'].map(attributeSwitchback); + for (const changes of [ + { switchbackPeriodMs: null }, + { switchbackPeriodMs: 0 }, + { switchbackPeriodMs: -HOUR }, + { split: [1] }, + { switchbackClusters: { [UNIT_TYPE]: null } }, + ]) { + experiments.push({ ...attributeSwitchback("city"), ...changes }); + } + for (const experiment of experiments) { + const context = createContext(dataOf(experiment)); + context.attribute("city", "Lisboa"); + context.attribute("items", [{ city: "Lisbon" }]); + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect([experiment.switchbackClusters, context.treatment("exp_sb")]).toEqual([ + experiment.switchbackClusters, + 0, + ]); + } + expect(context.pending()).toEqual(0); + } + }); + + // A missing or empty cluster map takes the legacy path: a unit of the declared unitType only + // identifies an ineligible control (variant 0's config, no exposure); without one it does not apply. + it("is only a legacy ineligible control with a missing or empty cluster map", () => { + for (const clusters of [null, {}]) { + const experiment = { ...attributeSwitchback("city"), switchbackClusters: clusters }; + const context = createContext(dataOf(experiment)); + context.attribute("city", "Lisboa"); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + expect(context.pending()).toEqual(0); + + const other = createContext(dataOf(experiment), { user_id: "u1" }); + other.attribute("city", "Lisboa"); + expect(other.treatment("exp_sb")).toEqual(0); + expect(other.variableValue("sb.arm", -1)).toEqual(-1); + expect(other.pending()).toEqual(0); + } + }); + + // The Collector reads the attribute set at or before the exposure instant, latest setAt first. + it("uses the latest attribute set at or before the resolution instant", () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 2 * HOUR; + context.attribute("city", "Porto"); + clock = ANCHOR + 4 * HOUR; + context.attribute("city", "Lisboa"); + + clock = ANCHOR + HOUR; + expect(context.peek("exp_sb")).toEqual(0); + clock = ANCHOR + 3 * HOUR; + expect(context.peek("exp_sb")).toEqual(expected("Porto", 3)); + clock = ANCHOR + 4 * HOUR; + expect(context.peek("exp_sb")).toEqual(expected("Lisboa", 4)); + }); + + // Within a period the cluster key is fixed at first resolution; the next period reads it again. + it("does not reassign within the period after a mid-period setAttribute", () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 10; + context.attribute("city", "Lisboa"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + + clock = ANCHOR + 20; + context.attribute("city", "Porto"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + expect(context.peek("exp_sb")).toEqual(expected("Lisboa", 0)); + expect(context.pending()).toEqual(1); + + let differing = 0; + for (let i = 1; i < 12; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(expected("Porto", i)); + if (expected("Porto", i) !== expected("Lisboa", i)) ++differing; + } + expect(differing).not.toEqual(0); + expect(context.pending()).toEqual(12); + }); + + // A unit first resolved without a key stays ineligible (and unrecorded) for the rest of the period. + it("waits for the next period after an ineligible resolution", async () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + context.attribute("city", "Lisboa"); + clock = ANCHOR + 20; + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + + clock = ANCHOR + HOUR; + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 1)); + expect(await publishExposures(context)).toEqual([exposure(expected("Lisboa", 1), ANCHOR + HOUR, true, false)]); + }); + + // A slot replaced through a traffic change still keeps the period's first key. + it("keeps the period's key through traffic changes within the period", async () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 10; + context.attribute("city", "Lisboa"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + + clock = ANCHOR + 20; + context.attribute("city", "Porto"); + await refreshTo(context, { ...attributeSwitchback("city"), trafficSplit: [1, 0] }); + expect(context.treatment("exp_sb")).toEqual(0); + + await refreshTo(context, attributeSwitchback("city")); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + expect(context.pending()).toEqual(3); + + clock = ANCHOR + HOUR; + expect(context.treatment("exp_sb")).toEqual(expected("Porto", 1)); + }); + + // The cluster is resolved before traffic: a traffic miss of an eligible cluster is a recorded + // ineligible exposure, and traffic restored later in the period serves the key read first. + it("keeps the key when traffic is restored within the period", async () => { + const context = createContext(dataOf({ ...attributeSwitchback("city"), trafficSplit: [1, 0] })); + clock = ANCHOR + 10; + context.attribute("city", "Faro"); + expect(context.treatment("exp_sb")).toEqual(0); + + clock = ANCHOR + 20; + context.attribute("city", "Lisboa"); + await refreshTo(context, attributeSwitchback("city")); + expect(expected("Faro", 0)).toEqual(1); + expect(context.treatment("exp_sb")).toEqual(expected("Faro", 0)); + expect(await publishExposures(context)).toEqual([ + exposure(0, ANCHOR + 10, false, false), + exposure(expected("Faro", 0), ANCHOR + 20, true, false), + ]); + }); + + // An audience change re-resolves the period slot (new exposure state) but keeps its key. + it("keeps the period's key through an audience revalidation", async () => { + const context = createContext(dataOf({ ...attributeSwitchback("city"), audience: GOLD_AUDIENCE })); + clock = ANCHOR + 10; + context.attribute("city", "Lisboa"); + context.attribute("tier", "gold"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + + clock = ANCHOR + 20; + context.attribute("city", "Porto"); + context.attribute("tier", "silver"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + + expect(await publishExposures(context)).toEqual([ + exposure(expected("Lisboa", 0), ANCHOR + 10, true, false), + exposure(expected("Lisboa", 0), ANCHOR + 20, true, true), + ]); + }); + + // A slot first resolved without a key carries that missing key into its replacement. + it("keeps the missing key through an audience revalidation after an ineligible resolution", () => { + const context = createContext(dataOf({ ...attributeSwitchback("city"), audience: GOLD_AUDIENCE })); + clock = ANCHOR + 10; + context.attribute("tier", "gold"); + expect(context.treatment("exp_sb")).toEqual(0); + + clock = ANCHOR + 20; + context.attribute("city", "Faro"); + context.attribute("tier", "silver"); + expect(expected("Faro", 0)).toEqual(1); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + + clock = ANCHOR + HOUR; + expect(context.peek("exp_sb")).toEqual(expected("Faro", 1)); + // Period 1 of Faro is variant 0; period 2 is not, so the key is visibly read again. + clock = ANCHOR + 2 * HOUR; + expect(expected("Faro", 2)).toEqual(2); + expect(context.peek("exp_sb")).toEqual(expected("Faro", 2)); + }); + + // An ineligible slot is not read again when rebuilt in its period, whatever rebuilds it. + it("keeps the missing key when a refresh rebuilds an ineligible slot", async () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + context.attribute("city", "Faro"); + await refreshTo(context, { ...attributeSwitchback("city"), trafficSplit: [0.0, 1.0, 0.0] }); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + }); + + it("invalidates the period when the cluster path changes", async () => { + const context = createContext(dataOf(attributeSwitchback("city"))); + clock = ANCHOR + 10; + context.attribute("city", "Lisboa"); + context.attribute("geo", { city: "Porto" }); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + expect(context.pending()).toEqual(1); + + await refreshTo(context, attributeSwitchback("city")); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + expect(context.pending()).toEqual(1); + + await refreshTo(context, attributeSwitchback("geo/city")); + expect(context.treatment("exp_sb")).toEqual(expected("Porto", 0)); + expect(context.pending()).toEqual(2); + + await refreshTo(context, { ...attributeSwitchback("geo/city"), switchbackClusterValues: ["Porto", "Faro"] }); + expect(context.treatment("exp_sb")).toEqual(expected("Porto", 0)); + expect(context.pending()).toEqual(3); + }); + + // Re-linking the experiment to another unit type re-keys the period and moves the exposure unit. + it("re-keys the period when the linked unit type changes", async () => { + const context = createContext(dataOf(attributeSwitchback("city")), { [UNIT_TYPE]: UID, user_id: "user-0002" }); + clock = ANCHOR + 1; + context.attribute("city", "Lisboa"); + context.attribute("ucity", "Faro"); + expect(context.treatment("exp_sb")).toEqual(expected("Lisboa", 0)); + + await refreshTo(context, { ...attributeSwitchback("ucity"), switchbackClusters: { user_id: "ucity" } }); + expect(context.treatment("exp_sb")).toEqual(expected("Faro", 0)); + expect((await publishExposures(context)).map((e) => e.unit)).toEqual([UNIT_TYPE, "user_id"]); + }); + + it("applies a custom assignment only to units with a cluster key", () => { + const keyed = createContext(dataOf(attributeSwitchback("city"))); + keyed.attribute("city", "Lisboa"); + keyed.customAssignment("exp_sb", 2); + expect(keyed.treatment("exp_sb")).toEqual(2); + + const unkeyed = createContext(dataOf(attributeSwitchback("city"))); + unkeyed.customAssignment("exp_sb", 2); + expect(unkeyed.treatment("exp_sb")).toEqual(0); + expect(unkeyed.pending()).toEqual(0); + }); + + // A split rule is revalidated over the serving unit: with the linked type differing from unitType, an + // unrelated setAttribute keeps the rule-won slot and records no second exposure. + it("revalidates a split rule over the serving unit without a second exposure", () => { + const experiment = { + ...attributeSwitchback("city"), + unitType: "user_id", + assignmentRules: '{"rules":[{"type":"split","environments":[],"percentages":"34/33/33"}]}', + }; + // store-20's draw differs between the rule's 34/33/33 and the experiment's equal thirds. + const rule = [0.34, 0.33, 0.33]; + const store20 = new VariantAssigner(hashUnit("store-20")); + expect(store20.assign(rule, SEED_HI, SEED_LO)).not.toEqual(store20.assign(experiment.split, SEED_HI, SEED_LO)); + for (const u of [0, 1, 2, 3, 20]) { + const context = createContext(dataOf(experiment), { [UNIT_TYPE]: `store-${u}`, user_id: `user-${u}` }); + context.attribute("city", "Lisboa"); + const variant = context.treatment("exp_sb"); + expect(variant).toEqual(new VariantAssigner(hashUnit(`store-${u}`)).assign(rule, SEED_HI, SEED_LO)); + context.attribute("unrelated", u); + expect(context.treatment("exp_sb")).toEqual(variant); + expect(context.pending()).toEqual(1); + } + }); + + // Inertness: a unit experiment ("unit" or absent) carrying every switchback field serves and + // publishes exactly what the same experiment without them does; a split rule randomizes over its + // unitType, never a cluster unit. + it("ignores cluster fields on unit experiments", async () => { + for (const type of ["unit", undefined]) { + const unit = { + ...attributeSwitchback("city"), + randomizationType: type, + switchbackClusters: { user_id: "city", [UNIT_TYPE]: "'x" }, + switchbackClusterValues: ["nothing"], + switchbackPeriodMs: 0, + assignmentRules: '{"rules":[{"type":"split","environments":[],"percentages":"34/33/33"}]}', + }; + const reference = { ...unit }; + for (const key of Object.keys(reference)) { + if (key.indexOf("switchback") === 0) delete reference[key]; + } + const published = []; + for (const experiment of [unit, reference]) { + const context = createContext(dataOf(experiment), { [UNIT_TYPE]: UID, user_id: "u" }); + context.attribute("city", "Lisboa"); + clock = ANCHOR - HOUR; + const first = context.treatment("exp_sb"); + for (let i = 1; i < 6; ++i) { + clock = ANCHOR - HOUR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(first); + } + published.push(await publishExposures(context)); + } + expect(published[0].length).toEqual(1); + expect(published[0][0]).toEqual( + expect.objectContaining({ + eligible: true, + ruleOverride: true, + exposedAt: ANCHOR - HOUR, + unit: UNIT_TYPE, + }) + ); + expect(published[0]).toEqual(published[1]); + } + }); +}); diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js new file mode 100644 index 0000000..e36a6aa --- /dev/null +++ b/src/__tests__/context-switchback-parity.test.js @@ -0,0 +1,402 @@ +import Client from "../client"; +import SDK from "../sdk"; +import Context from "../context"; +import { hashUnit } from "../utils"; +import { VariantAssigner } from "../assigner"; +import { assignSwitchbackPeriod } from "../switchback"; +import { ContextPublisher } from "../publisher"; +import { ContextDataProvider } from "../provider"; +import pathCases from "./fixtures/switchback/attribute-path-cases.json"; + +jest.mock("../client"); +jest.mock("../sdk"); +jest.mock("../provider"); +jest.mock("../publisher"); + +// Port of java-sdk's SwitchbackServerParityTest: replays the Collector's R33 serving rules +// (ContextAPI.switchbackServing and switchbackVariant) through the public Context API. Each case states, +// independently of SDK code, the serving unit type and the raw cluster key the Collector picks, or that +// it records nothing; the expected variant comes from REFERENCE_SCHEDULES. +const HOUR = 3600000; +const ANCHOR = 1767225600000; +const PERIODS = 4; +const ARMS = 3; +// SEED = 1234567890123 = (287 << 32) | 1912276171. +const SEED_HI = 287; +const SEED_LO = 1912276171; + +const STORE = "store_id"; +const DEVICE = "device_id"; +const USER = "user_id"; +const TWO_SOURCES = { [STORE]: "store_city", [DEVICE]: "geo/city" }; + +const sdk = new SDK(); +const client = new Client(); +const publisher = new ContextPublisher(); +sdk.getContextDataProvider.mockReturnValue(new ContextDataProvider()); +sdk.getContextPublisher.mockReturnValue(publisher); +sdk.getClient.mockReturnValue(client); +client.getApplication.mockReturnValue({ name: "website", version: 0 }); +client.getEnvironment.mockReturnValue("production"); + +let clock; + +beforeEach(() => { + clock = ANCHOR; + jest.spyOn(Date, "now").mockImplementation(() => clock); +}); + +function experiment(clusters, values = null, overrides = {}) { + const split = []; + const variants = []; + for (let i = 0; i < ARMS; ++i) { + split.push(1 / ARMS); + variants.push({ name: String(i), config: null }); + } + return { + id: 1, + name: "exp_sb", + // R33 payloads may still carry unitType; it is never used for switchback assignment. + unitType: USER, + iteration: 1, + seedHi: SEED_HI, + seedLo: SEED_LO, + split, + trafficSeedHi: 0, + trafficSeedLo: 0, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "website" }], + variants, + audience: null, + audienceStrict: false, + customFieldValues: null, + randomizationType: "switchback", + switchbackClusters: clusters, + switchbackClusterValues: values, + switchbackStartAt: ANCHOR, + switchbackPeriodMs: HOUR, + switchbackDesignType: "balanced_block", + ...overrides, + }; +} + +function createContext(experiments, units) { + const exposures = []; + const eventLogger = (_, eventName, data) => { + if (eventName === "exposure") exposures.push(data); + }; + const context = new Context(sdk, { publishDelay: -1, refreshPeriod: 0, eventLogger }, { units }, { experiments }); + return { context, exposures }; +} + +// Serves PERIODS periods with treatment, one call per period. +function serve(exp, units, attributes) { + // The attributes are set at context creation, before every period, as in Java. + clock = ANCHOR; + const { context, exposures } = createContext([exp], units); + if (attributes != null) context.attributes(attributes); + const variants = []; + for (let p = 0; p < PERIODS; ++p) { + clock = ANCHOR + p * HOUR + 1; + variants.push(context.treatment("exp_sb")); + } + return { variants, exposures }; +} + +// Periods 0..3 of each raw key under SEED with 3 arms, from an independent Python murmur3 reference that +// reproduces every platform golden vector; never computed by the SDK. +const REFERENCE_SCHEDULES = { + Lisboa: [0, 1, 2, 2], + Porto: [2, 1, 0, 1], + 42: [0, 2, 1, 2], + Faro: [0, 1, 2, 1], + "-7": [2, 0, 1, 0], + Lisbon: [2, 0, 1, 1], + "plus-one-key": [2, 1, 0, 0], +}; + +function collectorVariant(key, period) { + expect(Object.prototype.hasOwnProperty.call(REFERENCE_SCHEDULES, key)).toBe(true); + return REFERENCE_SCHEDULES[key][period]; +} + +// The Collector served `key` under a unit of `servingType`: one eligible exposure per period under that +// unit, variant from the raw key. +function expectEligible(served, servingType, key, message) { + expect([message, served.exposures.length]).toEqual([message, PERIODS]); + for (let p = 0; p < PERIODS; ++p) { + const expected = collectorVariant(key, p); + const e = served.exposures[p]; + expect([message, p, served.variants[p], e.unit, e.variant, e.assigned, e.eligible, e.exposedAt]).toEqual([ + message, + p, + expected, + servingType, + expected, + true, + true, + ANCHOR + p * HOUR + 1, + ]); + } +} + +// The Collector records nothing: control in every period, no exposure. +function expectSilentControl(served, message) { + expect([message, served.variants]).toEqual([message, [0, 0, 0, 0]]); + expect([message, served.exposures]).toEqual([message, []]); +} + +const twoUnits = () => ({ [STORE]: "s1", [DEVICE]: "d1" }); + +describe("switchback server parity", () => { + // Independent murmur3 reference: periods 0..3 of the raw keys under SEED with 3 arms. + it("matches the independent reference for raw-key schedules", () => { + expectEligible( + serve(experiment({ [STORE]: "city" }), { [STORE]: "s1" }, { city: "Lisboa" }), + STORE, + "Lisboa", + "Lisboa" + ); + // The SDK's own period draw agrees with the reference for every key the suite uses. + for (const key of Object.keys(REFERENCE_SCHEDULES)) { + for (let p = 0; p < PERIODS; ++p) { + expect([key, p, assignSwitchbackPeriod(key, p, SEED_HI, SEED_LO, ARMS)]).toEqual([ + key, + p, + collectorVariant(key, p), + ]); + } + } + }); + + it("serves agreement under the first source unit", () => { + expectEligible( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: "Lisboa", geo: { city: "Lisboa" } }), + STORE, + "Lisboa", + "agreement" + ); + }); + + it("records nothing for a disagreement", () => { + expectSilentControl( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: "Lisboa", geo: { city: "Porto" } }), + "disagreement" + ); + }); + + // A unit yielding no value is skipped; the next unit with a value serves. + it("skips a missing value and serves the next value", () => { + expectEligible( + serve(experiment(TWO_SOURCES), twoUnits(), { geo: { city: "Porto" } }), + DEVICE, + "Porto", + "first missing" + ); + expectEligible( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: "Porto" }), + STORE, + "Porto", + "second missing" + ); + expectSilentControl(serve(experiment(TWO_SOURCES), twoUnits(), { other: "x" }), "no value at all"); + expectSilentControl(serve(experiment(TWO_SOURCES), twoUnits(), null), "no attributes"); + }); + + // A unit linked by a source but absent from the context does not take part. + it("lets only linked units present in the context take part", () => { + expectEligible( + serve(experiment(TWO_SOURCES), { [DEVICE]: "d1" }, { store_city: "Lisboa", geo: { city: "Porto" } }), + DEVICE, + "Porto", + "store unit absent" + ); + }); + + it("records nothing for a filtered value and serves an allowed value", () => { + const lisboa = { store_city: "Lisboa" }; + expectSilentControl(serve(experiment(TWO_SOURCES, ["Porto", "Faro"]), twoUnits(), lisboa), "filtered"); + expectEligible( + serve(experiment(TWO_SOURCES, ["Porto", "Lisboa"]), twoUnits(), lisboa), + STORE, + "Lisboa", + "allowed" + ); + // A null or empty allow-list admits every value. + expectEligible(serve(experiment(TWO_SOURCES, null), twoUnits(), lisboa), STORE, "Lisboa", "null filter"); + expectEligible(serve(experiment(TWO_SOURCES, []), twoUnits(), lisboa), STORE, "Lisboa", "empty filter"); + // The filter compares the normalised text of numeric values. + expectEligible( + serve(experiment(TWO_SOURCES, ["42"]), twoUnits(), { store_city: 42 }), + STORE, + "42", + "numeric filter" + ); + // A filtered first value is not replaced by a later allowed one: they disagree. + expectSilentControl( + serve(experiment(TWO_SOURCES, ["Porto"]), twoUnits(), { store_city: "Lisboa", geo: { city: "Porto" } }), + "filtered first value" + ); + }); + + // An ineligible cluster is listed under the first linked unit present, not the unit that gave the + // rejected value: an override shows that unit. + it("records an override on an ineligible cluster under the first linked unit", () => { + clock = ANCHOR; + const { context, exposures } = createContext([experiment(TWO_SOURCES, ["Lisboa"])], twoUnits()); + context.attribute("geo", { city: "Porto" }); + context.override("exp_sb", 2); + clock = ANCHOR + 1; + expect(context.treatment("exp_sb")).toEqual(2); + expect(exposures.map((e) => [e.unit, e.variant, e.overridden])).toEqual([[STORE, 2, true]]); + }); + + it("rejects a second uid of the same type", () => { + const { context } = createContext([], { [STORE]: "s1" }); + expect(() => context.unit(STORE, "s2")).toThrow("Unit 'store_id' UID already set."); + expectEligible( + serve(experiment({ [STORE]: "city" }), { [STORE]: "s1" }, { city: "Faro" }), + STORE, + "Faro", + "single unit" + ); + }); + + // The declared order decides, not the order units were set or named. + it("serves the lower unit type id source first", () => { + const agreeing = { store_city: "Lisboa", geo: { city: "Lisboa" } }; + const units = { [STORE]: "s1", [DEVICE]: "d1" }; + expectEligible( + serve(experiment({ [DEVICE]: "geo/city", [STORE]: "store_city" }), units, agreeing), + DEVICE, + "Lisboa", + "device declared first" + ); + expectEligible(serve(experiment(TWO_SOURCES), units, agreeing), STORE, "Lisboa", "store declared first"); + }); + + // Booleans, fractions, objects, arrays, null and "" yield no value: skipped, never a disagreement. + // (JS cannot tell 2.0 from 2, so 2.0 is keyed like the integer and is not in this list.) + it("ignores values that give no key", () => { + for (const value of [true, false, 1.5, { a: "b" }, ["x"], [], null, ""]) { + const message = `ignored ${JSON.stringify(value)}`; + expectEligible( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: value, geo: { city: "Porto" } }), + DEVICE, + "Porto", + message + ); + expectSilentControl( + serve(experiment({ [STORE]: "store_city" }), { [STORE]: "s1" }, { store_city: value }), + `${message} alone` + ); + } + }); + + // Integral numbers are keyed by their base-10 text, so they agree with that text. + it("keys numeric values as text", () => { + for (const store of [42, "42"]) { + for (const device of [42, "42"]) { + expectEligible( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: store, geo: { city: device } }), + STORE, + "42", + `${typeof store}/${typeof device}` + ); + } + } + expectEligible(serve(experiment({ [STORE]: "n" }), { [STORE]: "s1" }, { n: -7 }), STORE, "-7", "negative"); + expectSilentControl( + serve(experiment(TWO_SOURCES), twoUnits(), { store_city: 42, geo: { city: "042" } }), + "42 vs 042 disagree" + ); + }); + + // A malformed path makes the whole experiment unservable: ineligible control for any linked unit, even + // when another source is valid. + it("records nothing for malformed paths", () => { + const attributes = { store_city: "Lisboa", geo: { city: "Porto" }, "geo.city": "Faro" }; + for (const path of ["'geo/city", '"geo', "geo/'city", "geo.city", "geo/a.b", "'geo.city'", '"geo.city"']) { + expectSilentControl( + serve(experiment({ [STORE]: "store_city", [DEVICE]: path }), twoUnits(), attributes), + path + ); + expectSilentControl(serve(experiment({ [DEVICE]: path }), twoUnits(), attributes), `${path} alone`); + } + }); + + // No context unit of any linked type: the experiment does not apply; unitType is never used. + it("does not apply without a linked unit", () => { + expectSilentControl( + serve(experiment(TWO_SOURCES), { [USER]: "u1" }, { store_city: "Lisboa" }), + "no linked unit" + ); + }); + + // Traffic eligibility is sticky on the serving unit's hash: it equals that of a unit experiment on the + // serving unit's type with the same traffic seed and split, in every period. + it("follows the serving unit's hash for traffic", () => { + let eligible = 0; + let ineligible = 0; + for (let u = 0; u < 24; ++u) { + const traffic = { trafficSplit: [0.5, 0.5], trafficSeedHi: 3, trafficSeedLo: 4 }; + const switchback = experiment(TWO_SOURCES, null, traffic); + const twin = { ...experiment(TWO_SOURCES, null, traffic), id: 2, name: "exp_unit", unitType: DEVICE }; + delete twin.randomizationType; + clock = ANCHOR; + const { context, exposures } = createContext([switchback, twin], { + [STORE]: "s1", + [DEVICE]: `device-${u}`, + }); + // Only the device unit has a value, so it serves. + context.attribute("geo", { city: "Porto" }); + context.treatment("exp_unit"); + const twinEligible = exposures[0].eligible; + expect(twinEligible).toEqual(new VariantAssigner(hashUnit(`device-${u}`)).assign([0.5, 0.5], 3, 4) === 1); + for (let p = 0; p < PERIODS; ++p) { + clock = ANCHOR + p * HOUR; + const variant = context.treatment("exp_sb"); + expect([exposures[p + 1].unit, exposures[p + 1].eligible]).toEqual([DEVICE, twinEligible]); + expect(variant).toEqual(twinEligible ? collectorVariant("Porto", p) : 0); + } + if (twinEligible) ++eligible; + else ++ineligible; + } + expect(eligible).toBeGreaterThan(0); + expect(ineligible).toBeGreaterThan(0); + }); + + // Each attribute-path-cases.json case, served as a cluster path over the fixture's attributes: + // unsupported paths are unservable, a null value is ineligible, and any other value serves. + it("matches the Collector on every attribute path case", () => { + let eligibleCases = 0; + for (const c of pathCases.cases) { + const served = serve(experiment({ [STORE]: c.path }), { [STORE]: "s1" }, pathCases.attributes); + if (!c.supported || c.value == null) { + expectSilentControl(served, c.path); + continue; + } + expectEligible(served, STORE, c.value, c.path); + ++eligibleCases; + } + expect(eligibleCases).toEqual(3); + }); + + // The latest supplied value of a repeated attribute name serves; names are matched trimmed. + it("resolves repeated attribute names to the latest", () => { + expectEligible( + serve(experiment({ [STORE]: "cluster" }), { [STORE]: "s1" }, { " cluster ": "Porto" }), + STORE, + "Porto", + "trimmed" + ); + clock = ANCHOR; + const { context, exposures } = createContext([experiment({ [STORE]: "cluster" })], { [STORE]: "s1" }); + context.attribute("cluster", "Lisboa"); + context.attribute("cluster", "Porto"); + clock = ANCHOR + 1; + expect(context.treatment("exp_sb")).toEqual(collectorVariant("Porto", 0)); + expect(exposures[0].eligible).toBe(true); + }); +}); diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js new file mode 100644 index 0000000..4a7c765 --- /dev/null +++ b/src/__tests__/context-switchback.test.js @@ -0,0 +1,1933 @@ +import Client from "../client"; +import SDK from "../sdk"; +import Context from "../context"; +import { hashUnit } from "../utils"; +import { VariantAssigner } from "../assigner"; +import { assignSwitchbackPeriod } from "../switchback"; +import { ContextPublisher } from "../publisher"; +import { ContextDataProvider } from "../provider"; +import { SDK_VERSION } from "../version"; + +jest.mock("../client"); +jest.mock("../sdk"); +jest.mock("../provider"); +jest.mock("../publisher"); + +// Port of java-sdk's ContextSwitchbackTest (java-sdk#15) through the public Context API. +const UNIT_TYPE = "store_id"; +const UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec"; +// hashUnit(UID): the MD5/base64url string the Collector's UnitHasher also produces. +const UID_HASH = "pAE3a1i5Drs5mKRNq56adA"; + +const HOUR = 3600000; +const DAY = 24 * HOUR; +// 2026-01-01T00:00:00Z, hour aligned. +const ANCHOR = 1767225600000; + +const SEED_HI = -5; +const SEED_LO = -7; + +// The store unit's cluster value: attribute CLUSTER_PATH, set on every default context. +const CLUSTER_PATH = "store_key"; +const CLUSTER_KEY = "store-42"; +// Periods 0..11 of the raw cluster key "store-42" under seed (SEED_HI, SEED_LO), from an independent +// Python reference (murmur3 over the platform formulas) that reproduces every golden vector. +const EXPECTED_2_ARMS = [0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1]; +const EXPECTED_3_ARMS = [0, 2, 1, 2, 1, 0, 1, 2, 0, 1, 0, 2]; +const EXPECTED_10_ARMS = [8, 3, 7, 4, 2, 0, 5, 1, 9, 6, 3, 7]; +// Same reference fed UID_HASH and the raw UID: what keying by the unit instead of the cluster would serve. +const UID_HASH_3_ARMS = [1, 2, 0, 2, 1, 0, 2, 0, 1, 1, 2, 0]; +const UID_3_ARMS = [2, 0, 1, 0, 1, 2, 1, 2, 0, 0, 1, 2]; + +const ASSIGN_VARIANT_1 = '{"rules":[{"type":"assign","environments":[],"variant":1}]}'; +const ASSIGN_VARIANT_2 = '{"rules":[{"type":"assign","environments":[],"variant":2}]}'; +// An audience the default context never matches (no "tier" attribute). +const STRICT_GOLD_AUDIENCE = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}'; + +const sdk = new SDK(); +const client = new Client(); +const publisher = new ContextPublisher(); +const provider = new ContextDataProvider(); + +sdk.getContextDataProvider.mockReturnValue(provider); +sdk.getContextPublisher.mockReturnValue(publisher); +sdk.getClient.mockReturnValue(client); +sdk.getEventLogger.mockReturnValue(SDK.defaultEventLogger); +client.getAgent.mockReturnValue("absmartly-javascript-sdk"); +client.getApplication.mockReturnValue({ name: "website", version: 0 }); +client.getEnvironment.mockReturnValue("production"); + +let clock; +// When set, the next Date.now() returns it once, then reads fall back to `clock`. +let nextRead; + +beforeEach(() => { + clock = ANCHOR; + nextRead = undefined; + jest.spyOn(Date, "now").mockImplementation(() => { + if (nextRead !== undefined) { + const value = nextRead; + nextRead = undefined; + return value; + } + return clock; + }); + publisher.publish.mockReset(); + publisher.publish.mockReturnValue(Promise.resolve()); + provider.getContextData.mockReset(); +}); + +function switchback(id, experimentName, armCount, periodMs) { + const split = []; + const variants = []; + for (let i = 0; i < armCount; ++i) { + split.push(1 / armCount); + variants.push({ name: String.fromCharCode(65 + i), config: `{"sb.arm":${i}}` }); + } + return { + id, + name: experimentName, + unitType: UNIT_TYPE, + iteration: 1, + seedHi: SEED_HI, + seedLo: SEED_LO, + split, + trafficSeedHi: 1, + trafficSeedLo: 2, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "website" }], + variants, + audience: null, + audienceStrict: false, + customFieldValues: null, + randomizationType: "switchback", + switchbackClusters: { [UNIT_TYPE]: CLUSTER_PATH }, + switchbackStartAt: ANCHOR, + switchbackPeriodMs: periodMs, + switchbackCarryoverDurationMs: 0, + switchbackBurnInDurationMs: 0, + switchbackBurnOutDurationMs: 0, + switchbackDesignType: "balanced_block", + switchbackEstimand: "global_average_treatment_effect", + }; +} + +function sb(armCount, periodMs) { + return switchback(1, "exp_sb", armCount, periodMs); +} + +// The same experiment without any switchback field: a unit experiment. +function asUnit(experiment) { + const unit = { ...experiment }; + for (const key of Object.keys(unit)) { + if (key.indexOf("switchback") === 0 || key === "randomizationType") delete unit[key]; + } + return unit; +} + +function dataOf(...experiments) { + return { experiments }; +} + +function createContext(data, units = { [UNIT_TYPE]: UID }, eventLogger = jest.fn()) { + const context = new Context(sdk, { publishDelay: -1, refreshPeriod: 0, eventLogger }, { units }, data); + context.attribute(CLUSTER_PATH, CLUSTER_KEY); + return context; +} + +function exposure(id, experimentName, variant, exposedAt, assigned, eligible, flags = {}) { + return { + id, + name: experimentName, + unit: UNIT_TYPE, + exposedAt, + variant, + assigned, + eligible, + overridden: false, + fullOn: false, + custom: false, + audienceMismatch: false, + ruleOverride: false, + ...flags, + }; +} + +// A rule win is published exactly like a unit experiment's: ruleOverride set, assigned false. +function ruleExposure(experimentName, variant, exposedAt) { + return exposure(1, experimentName, variant, exposedAt, false, true, { ruleOverride: true }); +} + +function strictMismatchExposure(exposedAt) { + return exposure(1, "exp_sb", 0, exposedAt, false, true, { audienceMismatch: true }); +} + +async function publishRequests(context, expectedPublishes = 1) { + await context.publish(); + expect(publisher.publish).toHaveBeenCalledTimes(expectedPublishes); + return publisher.publish.mock.calls.map((call) => call[0]); +} + +async function publishExposures(context) { + const requests = await publishRequests(context); + return requests[0].exposures ?? []; +} + +function peekSchedule(context, experimentName, periodMs, periods) { + const result = []; + for (let i = 0; i < periods; ++i) { + clock = ANCHOR + i * periodMs; + result.push(context.peek(experimentName)); + } + return result; +} + +async function refreshTo(context, ...experiments) { + provider.getContextData.mockReturnValue(Promise.resolve(dataOf(...experiments))); + await context.refresh(); +} + +// Holdout 11 for UID under seed (13, 111); split decides whether UID is held out. +function holdout(split) { + return { id: 11, name: "holdout_a", unitType: UNIT_TYPE, iteration: 1, seedHi: 13, seedLo: 111, split }; +} + +const seedOf = (seedHi, seedLo) => [seedHi, seedLo]; +const draw = (key, period, seed, arms) => assignSwitchbackPeriod(key, period, seed[0], seed[1], arms); + +describe("switchback serving through Context", () => { + it("keys the cluster by the raw attribute value, neither hashed nor the unit uid", () => { + expect(hashUnit(UID)).toEqual(UID_HASH); + + const context = createContext(dataOf(sb(3, HOUR))); + const served = peekSchedule(context, "exp_sb", HOUR, 12); + + expect(served).toEqual(EXPECTED_3_ARMS); + expect(served).not.toEqual(UID_HASH_3_ARMS); + expect(served).not.toEqual(UID_3_ARMS); + const hashedKey = hashUnit(CLUSTER_KEY); + let hashedDiffers = false; + for (let i = 0; i < 12; ++i) { + expect(draw(CLUSTER_KEY, i, seedOf(SEED_HI, SEED_LO), 3)).toEqual(served[i]); + hashedDiffers = hashedDiffers || draw(hashedKey, i, seedOf(SEED_HI, SEED_LO), 3) !== served[i]; + } + expect(hashedDiffers).toBe(true); + }); + + it("serves two-, three- and ten-arm permutations", () => { + const context = createContext( + dataOf(switchback(1, "exp_2", 2, HOUR), switchback(2, "exp_3", 3, HOUR), switchback(3, "exp_10", 10, HOUR)) + ); + + expect(peekSchedule(context, "exp_2", HOUR, 12)).toEqual(EXPECTED_2_ARMS); + expect(peekSchedule(context, "exp_3", HOUR, 12)).toEqual(EXPECTED_3_ARMS); + expect(peekSchedule(context, "exp_10", HOUR, 12)).toEqual(EXPECTED_10_ARMS); + }); + + it("switches at the exact edge milliseconds of a one-hour period", () => { + const context = createContext(dataOf(sb(2, HOUR))); + + for (const [now, expected] of [ + [ANCHOR - 1, 0], + [ANCHOR, EXPECTED_2_ARMS[0]], + [ANCHOR + HOUR - 1, EXPECTED_2_ARMS[0]], + [ANCHOR + HOUR, EXPECTED_2_ARMS[1]], + [ANCHOR + 3 * HOUR - 1, EXPECTED_2_ARMS[2]], + [ANCHOR + 3 * HOUR, EXPECTED_2_ARMS[3]], + ]) { + clock = now; + expect([now, context.peek("exp_sb")]).toEqual([now, expected]); + } + }); + + it("switches at the exact edge milliseconds of a 24-hour period", () => { + const context = createContext(dataOf(sb(2, DAY))); + + for (const [now, expected] of [ + [ANCHOR - 1, 0], + [ANCHOR, EXPECTED_2_ARMS[0]], + [ANCHOR + HOUR, EXPECTED_2_ARMS[0]], + [ANCHOR + DAY - 1, EXPECTED_2_ARMS[0]], + [ANCHOR + DAY, EXPECTED_2_ARMS[1]], + [ANCHOR + 4 * DAY - 1, EXPECTED_2_ARMS[3]], + [ANCHOR + 4 * DAY, EXPECTED_2_ARMS[4]], + ]) { + clock = now; + expect([now, context.peek("exp_sb")]).toEqual([now, expected]); + } + }); + + // The anchor is served without rounding; before it the experiment is an ineligible control that + // records no exposure. An anchor that is not hour aligned is unservable in every period. + it("treats an unaligned anchor as unservable and pre-anchor resolutions as ineligible", async () => { + const aligned = switchback(1, "exp_aligned", 2, HOUR); + aligned.switchbackStartAt = ANCHOR + HOUR; + const unaligned = switchback(2, "exp_unaligned", 2, HOUR); + const start = ANCHOR + 1234567; + unaligned.switchbackStartAt = start; + const context = createContext(dataOf(aligned, unaligned)); + + for (const now of [ANCHOR, start - 1, start, ANCHOR + HOUR - 1]) { + clock = now; + expect(context.treatment("exp_aligned")).toEqual(0); + expect(context.treatment("exp_unaligned")).toEqual(0); + } + expect(context.pending()).toEqual(0); + for (let i = 1; i < 4; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_aligned")).toEqual(EXPECTED_2_ARMS[i - 1]); + expect(context.treatment("exp_unaligned")).toEqual(0); + clock = start + i * HOUR; + expect(context.treatment("exp_unaligned")).toEqual(0); + } + + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_aligned", EXPECTED_2_ARMS[0], ANCHOR + HOUR, true, true), + exposure(1, "exp_aligned", EXPECTED_2_ARMS[1], ANCHOR + 2 * HOUR, true, true), + exposure(1, "exp_aligned", EXPECTED_2_ARMS[2], ANCHOR + 3 * HOUR, true, true), + ]); + }); + + // The Registry's anchor bounds: hour aligned and in [0, 10000-01-01T00:00:00Z). Unservable is an + // ineligible control on resolution and nothing on publish. + it("treats an anchor off the hour or out of bounds as unservable", async () => { + const maxAnchor = 253402300800000; + for (const startAt of [ + ANCHOR + 1, + ANCHOR - 1, + ANCHOR + 30 * 60000, + ANCHOR + HOUR - 1, + -HOUR, + -1, + maxAnchor, + maxAnchor + HOUR, + Number.MAX_SAFE_INTEGER - (Number.MAX_SAFE_INTEGER % HOUR), + ]) { + const experiment = sb(2, HOUR); + experiment.switchbackStartAt = startAt; + // The cluster attribute is set at context creation, before every resolution below. + clock = 0; + const context = createContext(dataOf(experiment)); + for (const now of [0, ANCHOR, ANCHOR + 2 * HOUR + 1, startAt, startAt + HOUR, maxAnchor + DAY]) { + clock = now; + expect([startAt, now, context.treatment("exp_sb")]).toEqual([startAt, now, 0]); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + } + expect([startAt, context.pending()]).toEqual([startAt, 0]); + await context.publish(); + expect(publisher.publish).not.toHaveBeenCalled(); + } + + // In-range hour-aligned anchors, including 0 and the last hour before the bound, serve. + for (const startAt of [0, ANCHOR, maxAnchor - HOUR]) { + const experiment = sb(2, HOUR); + experiment.switchbackStartAt = startAt; + clock = startAt + HOUR; + const context = createContext(dataOf(experiment)); + expect([startAt, context.treatment("exp_sb")]).toEqual([startAt, EXPECTED_2_ARMS[1]]); + expect(context.pending()).toEqual(1); + } + }); + + it("is an ineligible control with no start and never falls back to unit assignment", () => { + for (const startAt of [null, undefined]) { + const experiment = sb(2, HOUR); + experiment.switchbackStartAt = startAt; + const context = createContext(dataOf(experiment)); + + for (let i = 0; i < 4; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(0); + // Variant 0's own config, like any ineligible assignment. + expect(context.variableValue("sb.arm", -1)).toEqual(0); + } + expect(context.pending()).toEqual(0); + } + }); + + it("caches a period and rolls over to the next with one exposure each", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + clock = ANCHOR + HOUR - 1; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.peek("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + + clock = ANCHOR + HOUR; + expect(context.peek("exp_sb")).toEqual(EXPECTED_2_ARMS[1]); + expect(context.pending()).toEqual(1); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[1]); + expect(context.pending()).toEqual(2); + clock = ANCHOR + HOUR + 30 * 60000; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[1]); + expect(context.pending()).toEqual(2); + + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 10, true, true), + exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true), + ]); + }); + + it("follows the period through variable lookups and exposes once per period", () => { + const context = createContext(dataOf(sb(3, HOUR))); + + expect(context.variableKeys()).toEqual({ "sb.arm": ["exp_sb"] }); + expect(context.experiments()).toEqual(["exp_sb"]); + + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.peekVariableValue("sb.arm", -1)).toEqual(EXPECTED_3_ARMS[i]); + expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_3_ARMS[i]); + expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_3_ARMS[i]); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_3_ARMS[i]); + } + expect(context.pending()).toEqual(3); + }); + + // No unit of a linked type: the experiment does not apply and records nothing. unitType is never a fallback. + it("does not apply without a linked unit and never falls back to the unit type", async () => { + const experiment = sb(2, HOUR); + experiment.unitType = "user_id"; + const context = createContext(dataOf(experiment), { user_id: UID }); + + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.peek("exp_sb")).toEqual(0); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(-1); + } + expect(context.pending()).toEqual(0); + + // Setting a linked unit later makes the experiment apply. + context.unit(UNIT_TYPE, UID); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[2]); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[2], ANCHOR + 2 * HOUR, true, true), + ]); + }); + + it("serves the full-on variant in every period", async () => { + const experiment = sb(3, HOUR); + experiment.fullOnVariant = 2; + const context = createContext(dataOf(experiment)); + + for (let i = 0; i < 4; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(2); + } + const exposures = await publishExposures(context); + expect(exposures.length).toEqual(4); + for (const e of exposures) { + expect(e).toEqual(expect.objectContaining({ variant: 2, fullOn: true })); + } + }); + + it("lets an override and a custom assignment win in every period", async () => { + const context = createContext( + dataOf(switchback(1, "exp_override", 3, HOUR), switchback(2, "exp_custom", 3, HOUR)) + ); + context.override("exp_override", 7); + context.customAssignment("exp_custom", 2); + + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_override")).toEqual(7); + expect(context.treatment("exp_custom")).toEqual(2); + } + const exposures = await publishExposures(context); + expect(exposures.length).toEqual(6); + for (const e of exposures) { + if (e.name === "exp_override") { + expect(e).toEqual(exposure(1, "exp_override", 7, e.exposedAt, false, true, { overridden: true })); + } else { + expect(e).toEqual(exposure(2, "exp_custom", 2, e.exposedAt, true, true, { custom: true })); + } + } + }); + + // Traffic eligibility uses the serving unit's traffic hash, so it matches a unit-randomized twin + // with the same traffic seed and stays fixed across periods. + it("keeps traffic eligibility sticky per serving unit", async () => { + let eligibleCount = 0; + let ineligibleCount = 0; + for (let u = 0; u < 24; ++u) { + publisher.publish.mockClear(); + const experiment = switchback(1, "exp_sb", 2, HOUR); + experiment.trafficSplit = [0.5, 0.5]; + const twin = asUnit(switchback(2, "exp_unit", 2, HOUR)); + twin.trafficSplit = [0.5, 0.5]; + + clock = ANCHOR; + const context = createContext(dataOf(experiment, twin), { [UNIT_TYPE]: `store_${u}` }); + context.treatment("exp_unit"); + for (let i = 0; i < 4; ++i) { + clock = ANCHOR + i * HOUR; + context.treatment("exp_sb"); + } + + const exposures = await publishExposures(context); + expect(exposures.length).toEqual(5); + const twinEligible = exposures[0].eligible; + for (let i = 1; i < exposures.length; ++i) { + expect(exposures[i].name).toEqual("exp_sb"); + expect(exposures[i].eligible).toEqual(twinEligible); + if (!twinEligible) expect(exposures[i].variant).toEqual(0); + } + if (twinEligible) ++eligibleCount; + else ++ineligibleCount; + } + expect(eligibleCount).toBeGreaterThan(0); + expect(ineligibleCount).toBeGreaterThan(0); + }); + + it("leaves unit experiments unaffected", () => { + const unit = sb(2, HOUR); + unit.randomizationType = "unit"; + const absent = asUnit(switchback(2, "exp_absent", 2, HOUR)); + const unknown = switchback(3, "exp_unknown", 2, HOUR); + unknown.randomizationType = "something_new"; + + const context = createContext(dataOf(unit, absent, unknown)); + const variant = context.treatment("exp_sb"); + const absentVariant = context.treatment("exp_absent"); + const unknownVariant = context.treatment("exp_unknown"); + for (let i = 1; i < 6; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(variant); + expect(context.treatment("exp_absent")).toEqual(absentVariant); + expect(context.treatment("exp_unknown")).toEqual(unknownVariant); + } + expect(context.pending()).toEqual(3); + }); + + it("starts a new epoch when grid fields change, but not for analysis-only fields", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + + const burnsChanged = sb(2, HOUR); + burnsChanged.switchbackBurnInDurationMs = 600000; + burnsChanged.switchbackBurnOutDurationMs = 300000; + burnsChanged.switchbackCarryoverDurationMs = 900000; + burnsChanged.switchbackEstimand = "other"; + burnsChanged.seedHi = 99; + burnsChanged.split = [0.9, 0.1]; + await refreshTo(context, burnsChanged); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + + // Same period index 0 under both grids, so only the identity comparison can invalidate. + await refreshTo(context, sb(2, 2 * HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(2); + + const designChanged = sb(2, 2 * HOUR); + designChanged.switchbackDesignType = "other_design"; + await refreshTo(context, designChanged); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(3); + + const toUnit = sb(2, 2 * HOUR); + toUnit.randomizationType = "unit"; + await refreshTo(context, toUnit); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(4); + + await refreshTo(context, sb(2, 2 * HOUR)); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(5); + + // The cluster map (types, paths and their order) and the allow-list are identity. + const pathChanged = sb(2, 2 * HOUR); + pathChanged.switchbackClusters = { [UNIT_TYPE]: "'store_key'" }; + await refreshTo(context, pathChanged); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(6); + + const linkAdded = sb(2, 2 * HOUR); + linkAdded.switchbackClusters = { [UNIT_TYPE]: "'store_key'", device_id: "city" }; + await refreshTo(context, linkAdded); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(7); + + const linksReordered = sb(2, 2 * HOUR); + linksReordered.switchbackClusters = { device_id: "city", [UNIT_TYPE]: "'store_key'" }; + await refreshTo(context, linksReordered); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(8); + + const valuesSet = sb(2, 2 * HOUR); + valuesSet.switchbackClusters = linksReordered.switchbackClusters; + valuesSet.switchbackClusterValues = [CLUSTER_KEY]; + await refreshTo(context, valuesSet); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(9); + + // An unrelated unitType edit is not identity: switchbacks with a readable map never read it. + const unitTypeChanged = { ...valuesSet, unitType: "anything" }; + await refreshTo(context, unitTypeChanged); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(9); + }); + + it("starts the grid when a refresh sets the anchor", async () => { + const pending = sb(2, HOUR); + pending.switchbackStartAt = null; + const context = createContext(dataOf(pending)); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + }); + + // Holdouts never apply to a switchback: a holdout that would hold the unit out neither suppresses + // it nor records its own exposure through it. + it("never applies holdouts", async () => { + for (const split of [ + [0.1, 0.9], + [0, 1], + [1, 0, 0], + ]) { + publisher.publish.mockClear(); + clock = ANCHOR; + const covered = sb(2, HOUR); + covered.holdoutIds = [11]; + const data = { ...dataOf(covered), holdouts: [holdout(split)] }; + const context = createContext(data); + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[i]); + expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[i]); + expect(context.peekVariableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[i]); + } + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR, true, true), + exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true), + exposure(1, "exp_sb", EXPECTED_2_ARMS[2], ANCHOR + 2 * HOUR, true, true), + ]); + } + }); + + // Assignment rules are evaluated first for a switchback too, so a matching rule assigns its + // variant even before the anchor, recorded with ruleOverride. + it("lets an assignment rule override the schedule, before the anchor too", async () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = ASSIGN_VARIANT_1; + for (let u = 0; u < 10; ++u) { + publisher.publish.mockClear(); + clock = ANCHOR - 1; + const context = createContext(dataOf(experiment), { [UNIT_TYPE]: `user-${u}` }); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.variableValue("sb.arm", -1)).toEqual(1); + for (let i = 0; i < 4; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(1); + } + const exposures = await publishExposures(context); + expect(exposures).toEqual([ + ruleExposure("exp_sb", 1, ANCHOR - 1), + ...[0, 1, 2, 3].map((i) => ruleExposure("exp_sb", 1, ANCHOR + i * HOUR)), + ]); + } + }); + + // An unservable schedule only replaces the schedule draw: full-on and rules still apply. + it("lets full-on and rules apply with an unservable schedule", async () => { + const fullOn = switchback(1, "sb_full_on", 2, HOUR); + fullOn.switchbackStartAt = null; + fullOn.fullOnVariant = 1; + const rules = switchback(2, "sb_rules", 2, HOUR); + rules.switchbackPeriodMs = 0; + rules.assignmentRules = ASSIGN_VARIANT_1; + const unalignedRules = switchback(3, "sb_unaligned_rules", 2, HOUR); + unalignedRules.switchbackStartAt = ANCHOR + 1; + unalignedRules.assignmentRules = ASSIGN_VARIANT_1; + const context = createContext(dataOf(fullOn, rules, unalignedRules), { [UNIT_TYPE]: "15" }); + + expect(context.treatment("sb_full_on")).toEqual(1); + expect(context.treatment("sb_rules")).toEqual(1); + expect(context.treatment("sb_unaligned_rules")).toEqual(1); + expect(await publishExposures(context)).toEqual([ + exposure(1, "sb_full_on", 1, ANCHOR, true, true, { fullOn: true }), + exposure(2, "sb_rules", 1, ANCHOR, false, true, { ruleOverride: true }), + exposure(3, "sb_unaligned_rules", 1, ANCHOR, false, true, { ruleOverride: true }), + ]); + }); + + it("does not evaluate assignment rules for an ineligible cluster", () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = ASSIGN_VARIANT_1; + experiment.switchbackClusterValues = ["other-store"]; + const context = createContext(dataOf(experiment)); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + expect(context.pending()).toEqual(0); + }); + + // A split rule randomizes over the serving unit, not over the payload's unitType. + it("randomizes a split rule over the serving unit", async () => { + const experiment = sb(2, HOUR); + experiment.unitType = "user_id"; + experiment.assignmentRules = '{"rules":[{"type":"split","environments":[],"percentages":"50/50"}]}'; + let ones = 0; + for (let u = 0; u < 32; ++u) { + publisher.publish.mockClear(); + const uid = `store-${u}`; + const expected = new VariantAssigner(hashUnit(uid)).assign([0.5, 0.5], SEED_HI, SEED_LO); + const context = createContext(dataOf(experiment), { [UNIT_TYPE]: uid, user_id: "fixed-user" }); + expect([uid, context.treatment("exp_sb")]).toEqual([uid, expected]); + expect(await publishExposures(context)).toEqual([ruleExposure("exp_sb", expected, ANCHOR)]); + ones += expected; + } + expect(ones).toBeGreaterThan(0); + expect(ones).toBeLessThan(32); + }); + + it("records a strict audience mismatch as control", async () => { + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + const context = createContext(dataOf(experiment)); + clock = ANCHOR + HOUR; + expect(context.treatment("exp_sb")).toEqual(0); + expect(await publishExposures(context)).toEqual([strictMismatchExposure(ANCHOR + HOUR)]); + }); + + // Runs in period 1, whose draw is 1, so the variant 0 is the strict mismatch's control. + it("publishes a strict audience mismatch exactly", async () => { + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + const context = createContext(dataOf(experiment)); + expect(EXPECTED_2_ARMS[1]).toEqual(1); + clock = ANCHOR + HOUR + 5; + context.treatment("exp_sb"); + clock = ANCHOR + HOUR + 9; + + const [request] = await publishRequests(context); + expect(JSON.stringify(request)).toEqual( + JSON.stringify({ + publishedAt: ANCHOR + HOUR + 9, + units: [{ type: UNIT_TYPE, uid: UID_HASH }], + hashed: true, + sdkVersion: SDK_VERSION, + exposures: [strictMismatchExposure(ANCHOR + HOUR + 5)], + attributes: [{ name: CLUSTER_PATH, value: CLUSTER_KEY, setAt: ANCHOR }], + }) + ); + }); + + // The audience check comes before the period check, so a strict mismatch before the anchor or + // with an unservable schedule is still recorded. + it("records a strict audience mismatch before the anchor and with an unservable schedule", async () => { + for (const [startAt, now] of [ + [ANCHOR, ANCHOR - 1], + [null, ANCHOR + HOUR + 3], + ]) { + publisher.publish.mockClear(); + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + experiment.switchbackStartAt = startAt; + clock = now; + const context = createContext(dataOf(experiment)); + expect(context.treatment("exp_sb")).toEqual(0); + expect(await publishExposures(context)).toEqual([strictMismatchExposure(now)]); + } + }); + + // A missing or unreadable cluster map takes the legacy path, an ineligible control before the + // audience is evaluated, so a strict mismatch there records nothing. + it("records nothing for a strict audience mismatch with a missing or unreadable cluster map", () => { + for (const clusters of [null, undefined, {}, { [UNIT_TYPE]: "'geo" }]) { + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + experiment.switchbackClusters = clusters; + clock = ANCHOR + HOUR + 3; + const context = createContext(dataOf(experiment)); + expect([clusters, context.treatment("exp_sb")]).toEqual([clusters, 0]); + expect([clusters, context.pending()]).toEqual([clusters, 0]); + } + }); + + // A strict-mismatched switchback is not assigned, so on a shared variable key it gives way to the + // next experiment that declares the key, as a unit experiment does. + it("gives way on a shared variable key when strict-mismatched", async () => { + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + const unit = asUnit(switchback(2, "exp_unit", 2, HOUR)); + unit.variants = [ + { name: "A", config: '{"sb.arm":10}' }, + { name: "B", config: '{"sb.arm":11}' }, + ]; + unit.fullOnVariant = 1; + clock = ANCHOR + HOUR + 3; + const context = createContext(dataOf(experiment, unit)); + expect(context.variableKeys()).toEqual({ "sb.arm": ["exp_sb", "exp_unit"] }); + + expect(context.peekVariableValue("sb.arm", -1)).toEqual(11); + expect(context.pending()).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(11); + expect(await publishExposures(context)).toEqual([ + exposure(2, "exp_unit", 1, ANCHOR + HOUR + 3, true, true, { fullOn: true }), + ]); + }); + + // A refresh that adds a prototype-named key must not let a cached period slot resolve the + // inherited member. + it("does not resolve inherited members from a cached period slot after a refresh adds such a key", async () => { + const experiment = sb(2, HOUR); + clock = ANCHOR + HOUR + 3; + const context = createContext(dataOf(experiment)); + const served = context.treatment("exp_sb"); + const refreshed = sb(2, HOUR); + refreshed.variants = refreshed.variants.map((variant, i) => + i === served ? variant : { ...variant, config: '{"sb.arm":9,"toString":"T","valueOf":"V"}' } + ); + await refreshTo(context, refreshed); + for (const key of ["toString", "valueOf"]) { + expect(context.peekVariableValue(key, -1)).toEqual(-1); + expect(context.variableValue(key, -1)).toEqual(-1); + } + }); + + const threeArms = (over = {}) => { + const experiment = switchback(1, "exp_sb", 3, HOUR); + experiment.variants = experiment.variants.map((v, i) => ({ ...v, config: JSON.stringify({ k: `v${i}` }) })); + return { ...experiment, ...over }; + }; + const twoArms = (over = {}) => { + const experiment = threeArms(over); + return { ...experiment, variants: experiment.variants.slice(0, 2), split: [0.5, 0.5] }; + }; + + it("follows a period-less slot's arm that a refresh removes and a later refresh restores", async () => { + clock = ANCHOR - 1000; + const context = createContext(dataOf(threeArms())); + context.override("exp_sb", 2); + const seen = [context.variableValue("k", "DEF")]; + await refreshTo(context, twoArms()); + seen.push(context.peekVariableValue("k", "DEF"), context.variableValue("k", "DEF")); + await refreshTo(context, threeArms()); + seen.push(context.peekVariableValue("k", "DEF"), context.variableValue("k", "DEF")); + expect(seen).toEqual(["v2", "DEF", "DEF", "v2", "v2"]); + }); + // A non-override period-less full-on assignment must follow the removed/restored-arm contract. + it("follows a period-less fullOn arm across refreshes", async () => { + clock = ANCHOR - 1000; + const before = switchback(1, "exp_sb", 3, HOUR); + before.variants = before.variants.map((v, i) => ({ ...v, config: JSON.stringify({ k: `v${i}` }) })); + before.fullOnVariant = 2; + const context = createContext(dataOf(before)); + expect(context.variableValue("k", "DEF")).toBe("v2"); + const removed = { ...before, variants: before.variants.slice(0, 2), fullOnVariant: 2 }; + await refreshTo(context, removed); + expect(context.peekVariableValue("k", "DEF")).toBe("DEF"); + expect(context.variableValue("k", "DEF")).toBe("DEF"); + await refreshTo(context, before); + expect(context.peekVariableValue("k", "DEF")).toBe("v2"); + expect(context.variableValue("k", "DEF")).toBe("v2"); + }); + + it.each(["custom", "draw"])( + "follows a %s period slot's arm that a refresh removes and a later refresh restores", + async (kind) => { + clock = ANCHOR + HOUR + 3; + const seeds = kind === "draw" ? { seedHi: -5, seedLo: -7 } : {}; + const context = createContext(dataOf(threeArms(seeds))); + if (kind === "custom") context.customAssignment("exp_sb", 2); + const arm = context.treatment("exp_sb"); + expect(arm).toEqual(2); + const seen = [context.variableValue("k", "DEF")]; + await refreshTo(context, twoArms(seeds)); + seen.push(context.peekVariableValue("k", "DEF"), context.variableValue("k", "DEF")); + await refreshTo(context, threeArms(seeds)); + seen.push(context.peekVariableValue("k", "DEF"), context.variableValue("k", "DEF")); + expect(seen).toEqual(["v2", "DEF", "DEF", "v2", "v2"]); + } + ); + + it("follows a cached period slot's arm that a refresh removes and a later refresh restores", async () => { + const experiment = switchback(1, "exp_sb", 3, HOUR); + clock = ANCHOR + HOUR + 3; + const context = createContext(dataOf(experiment)); + context.override("exp_sb", 2); + expect(context.variableValue("sb.arm", -1)).toEqual(2); + const twoArmExperiment = switchback(1, "exp_sb", 2, HOUR); + await refreshTo(context, twoArmExperiment); + expect(context.peekVariableValue("sb.arm", -1)).toEqual(-1); + expect(context.variableValue("sb.arm", -1)).toEqual(-1); + await refreshTo(context, experiment); + expect(context.peekVariableValue("sb.arm", -1)).toEqual(2); + expect(context.variableValue("sb.arm", -1)).toEqual(2); + }); + + it("does not resolve inherited members from a cached period-less slot after a refresh", async () => { + const experiment = sb(2, HOUR); + experiment.variants = [ + { name: "A", config: '{"sb.arm":0}' }, + { name: "B", config: '{"sb.arm":1}' }, + ]; + clock = ANCHOR - 1000; + const context = createContext(dataOf(experiment)); + context.override("exp_sb", 1); + expect(context.variableValue("sb.arm", -1)).toEqual(1); + const refreshed = sb(2, HOUR); + // The keys land on the arm the unit is not in, so the override's arm must return the default. + refreshed.variants = [ + { name: "A", config: '{"sb.arm":0,"toString":"T","valueOf":"V"}' }, + { name: "B", config: '{"sb.arm":1}' }, + ]; + await refreshTo(context, refreshed); + expect(context.peekVariableValue("valueOf", -1)).toEqual(-1); + expect(context.variableValue("toString", -1)).toEqual(-1); + expect(context.variableValue("sb.arm", -1)).toEqual(1); + }); + + // Before its schedule starts a switchback is assigned but silent: it wins the key, serves control + // and records nothing, so the later experiment is neither returned nor exposed. + it("serves control without exposure when a silent switchback wins a shared variable key", () => { + const experiment = sb(2, HOUR); + const unit = asUnit(switchback(2, "exp_unit", 2, HOUR)); + unit.variants = [ + { name: "A", config: '{"sb.arm":10}' }, + { name: "B", config: '{"sb.arm":11}' }, + ]; + unit.fullOnVariant = 1; + clock = ANCHOR - 1; + const context = createContext(dataOf(experiment, unit)); + + expect(context.peekVariableValue("sb.arm", -1)).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + expect(context.pending()).toEqual(0); + }); + + it("returns the default value on a variable key it holds alone when strict-mismatched", () => { + const experiment = sb(2, HOUR); + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + clock = ANCHOR + HOUR + 3; + const context = createContext(dataOf(experiment)); + expect(context.peekVariableValue("sb.arm", -1)).toEqual(-1); + expect(context.pending()).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(-1); + }); + + // The SWITCHBACK.md "Exposure flags" table: every branch an eligible-cluster switchback shares with a + // unit experiment publishes the same flags. Columns: assigned, eligible, overridden, fullOn, + // custom, audienceMismatch, ruleOverride. The variant is served at ANCHOR + 2 * HOUR + 3 (period 2, + // whose 3-arm draw is 1); forced variants are 2, which differs from both control and the draw. + describe.each([ + ["override", [false, true, true, false, false, false, false], 2], + ["override over strict mismatch", [false, true, true, false, false, false, false], 2], + ["rule", [false, true, false, false, false, false, true], 2], + ["rule over strict mismatch", [false, true, false, false, false, false, true], 2], + ["strict mismatch", [false, true, false, false, false, true, false], 0], + ["strict mismatch over full-on", [false, true, false, false, false, true, false], 0], + ["strict mismatch over traffic miss", [false, true, false, false, false, true, false], 0], + ["non-strict mismatch", [true, true, false, false, false, true, false], EXPECTED_3_ARMS[2]], + ["full-on", [true, true, false, true, false, false, false], 2], + ["traffic miss", [true, false, false, false, false, false, false], 0], + ["custom", [true, true, false, false, true, false, false], 2], + ["draw", [true, true, false, false, false, false, false], EXPECTED_3_ARMS[2]], + ])("exposure flags for %s", (branch, flags, expectedVariant) => { + const configure = (experiment) => { + if (branch.indexOf("strict mismatch") >= 0) { + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = branch !== "non-strict mismatch"; + } + if (branch === "strict mismatch over full-on" || branch === "full-on") experiment.fullOnVariant = 2; + if (branch.indexOf("traffic miss") >= 0) experiment.trafficSplit = [1, 0]; + if (branch.indexOf("rule") === 0) experiment.assignmentRules = ASSIGN_VARIANT_2; + return experiment; + }; + const exposeOnce = async (experiment) => { + publisher.publish.mockClear(); + const context = createContext(dataOf(configure(experiment))); + if (branch.indexOf("override") === 0) context.override("exp_parity", 2); + if (branch === "custom") context.customAssignment("exp_parity", 2); + context.treatment("exp_parity"); + const exposures = await publishExposures(context); + expect(exposures.length).toEqual(1); + return exposures[0]; + }; + const flagsOf = (e) => [ + e.assigned, + e.eligible, + e.overridden, + e.fullOn, + e.custom, + e.audienceMismatch, + e.ruleOverride, + ]; + + it("matches a unit experiment and the table", async () => { + clock = ANCHOR + 2 * HOUR + 3; + expect(EXPECTED_3_ARMS[2]).toEqual(1); + + const unitExposure = await exposeOnce(asUnit(switchback(1, "exp_parity", 3, HOUR))); + const switchbackExposure = await exposeOnce(switchback(1, "exp_parity", 3, HOUR)); + + expect(flagsOf(unitExposure)).toEqual(flags); + expect(flagsOf(switchbackExposure)).toEqual(flags); + expect(switchbackExposure.variant).toEqual(expectedVariant); + if (branch !== "draw" && branch !== "non-strict mismatch") { + expect(unitExposure.variant).toEqual(expectedVariant); + } + expect([switchbackExposure.id, switchbackExposure.name, switchbackExposure.exposedAt]).toEqual([ + unitExposure.id, + unitExposure.name, + unitExposure.exposedAt, + ]); + }); + }); + + // A traffic miss on an eligible cluster is recorded (eligible=false, variant 0, under the serving + // unit); an ineligible cluster records nothing. + it("records a traffic miss on an eligible cluster as ineligible", async () => { + const miss = switchback(1, "exp_miss", 2, HOUR); + miss.trafficSplit = [1, 0]; + const ineligibleCluster = switchback(2, "exp_cluster_ineligible", 2, HOUR); + ineligibleCluster.trafficSplit = [1, 0]; + ineligibleCluster.switchbackClusterValues = ["other-store"]; + const context = createContext(dataOf(miss, ineligibleCluster)); + clock = ANCHOR + 2 * HOUR + 3; + expect(context.treatment("exp_miss")).toEqual(0); + expect(context.treatment("exp_cluster_ineligible")).toEqual(0); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_miss", 0, ANCHOR + 2 * HOUR + 3, true, false), + ]); + }); + + it("keeps custom field values and unit lookups working", () => { + const experiment = sb(2, HOUR); + experiment.customFieldValues = [{ name: "country", value: "PT", type: "string" }]; + const context = createContext(dataOf(experiment)); + expect(context.getUnit(UNIT_TYPE)).toEqual(UID); + expect(context.customFieldKeys()).toEqual(["country"]); + expect(context.customFieldValue("exp_sb", "country")).toEqual("PT"); + expect(context.customFieldValue("exp_sb", "missing")).toBeNull(); + }); + + it("keeps at most two period slots per experiment", () => { + const context = createContext(dataOf(sb(2, HOUR), switchback(2, "exp_other", 2, HOUR))); + for (let i = 0; i < 50; ++i) { + clock = ANCHOR + i * HOUR; + context.treatment("exp_sb"); + context.peek("exp_other"); + } + const retained = (experimentName) => Object.keys(context._switchbackEpochs[experimentName].slots).length; + expect([retained("exp_sb"), retained("exp_other")]).toEqual([2, 2]); + expect(Object.keys(context._assignments)).toEqual([]); + expect(context.pending()).toEqual(50); + }); + + it("does not use the unit type for assignment", async () => { + const experiment = sb(2, HOUR); + experiment.unitType = "user_id"; + const context = createContext(dataOf(experiment), { [UNIT_TYPE]: UID, user_id: "u1" }); + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[i]); + } + const exposures = await publishExposures(context); + expect(exposures.map((e) => e.unit)).toEqual([UNIT_TYPE, UNIT_TYPE, UNIT_TYPE]); + }); + + // The publish payload carries no switchback-specific field, and the cluster attribute is published + // timestamped: the Collector re-resolves the cluster at exposedAt from it. + it("publishes no new fields", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 5; + context.treatment("exp_sb"); + clock = ANCHOR + HOUR + 7; + context.treatment("exp_sb"); + clock = ANCHOR + HOUR + 9; + + const [request] = await publishRequests(context); + expect(JSON.stringify(request)).toEqual( + JSON.stringify({ + publishedAt: ANCHOR + HOUR + 9, + units: [{ type: UNIT_TYPE, uid: UID_HASH }], + hashed: true, + sdkVersion: SDK_VERSION, + exposures: [ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 5, true, true), + exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR + 7, true, true), + ], + attributes: [{ name: CLUSTER_PATH, value: CLUSTER_KEY, setAt: ANCHOR }], + }) + ); + expect(EXPECTED_2_ARMS[0]).not.toEqual(EXPECTED_2_ARMS[1]); + }); + + it("keeps one exposure per period across flushes", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR; + context.treatment("exp_sb"); + await context.publish(); + clock = ANCHOR + 1; + context.treatment("exp_sb"); + expect(context.pending()).toEqual(0); + clock = ANCHOR + HOUR; + context.treatment("exp_sb"); + + const requests = await publishRequests(context, 2); + expect(requests.map((r) => r.exposures.map((e) => e.variant))).toEqual([ + [EXPECTED_2_ARMS[0]], + [EXPECTED_2_ARMS[1]], + ]); + }); + + // The clock crosses into period 1 between the resolution's reading and any later one; the exposure + // still carries the reading that selected period 0. + it("stamps a treatment exposure with the resolution instant", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + HOUR; + nextRead = ANCHOR + HOUR - 1; + + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true), + ]); + }); + + it("stamps a variable exposure with the resolution instant", async () => { + const covered = sb(2, HOUR); + covered.holdoutIds = [11]; + const context = createContext({ ...dataOf(covered), holdouts: [holdout([0, 1])] }); + clock = ANCHOR + HOUR; + nextRead = ANCHOR + HOUR - 1; + + expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[0]); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true), + ]); + }); + + // One reading per variable lookup: every switchback visited on the key resolves and exposes at it. + it("resolves every experiment on a variable key at one instant", async () => { + const first = switchback(1, "exp_first", 2, HOUR); + first.audience = STRICT_GOLD_AUDIENCE; + first.audienceStrict = true; + const second = switchback(2, "exp_second", 2, HOUR); + const context = createContext(dataOf(first, second)); + clock = ANCHOR + HOUR; + nextRead = ANCHOR + HOUR - 1; + + expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[0]); + expect(await publishExposures(context)).toEqual([ + exposure(2, "exp_second", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true), + ]); + }); + + // A peek caches the period's assignment without exposing; the later treatment exposes at its own instant. + it("stamps an exposure after a peek with the exposing call's instant", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + expect(context.peek("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + clock = ANCHOR + 20 * 60000; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 20 * 60000, true, true), + ]); + }); + + // Unit experiments keep stamping at enqueue time and read the clock as before. + it("leaves unit exposure timing unchanged", async () => { + const unit = sb(2, HOUR); + unit.randomizationType = "unit"; + const context = createContext(dataOf(unit)); + clock = ANCHOR + HOUR; + nextRead = ANCHOR + HOUR - 1; + + const variant = context.treatment("exp_sb"); + expect(await publishExposures(context)).toEqual([ + exposure(1, "exp_sb", variant, ANCHOR + HOUR - 1, true, true), + ]); + }); + + it("reads the clock no more often for unit experiments in a payload without switchbacks", () => { + const context = createContext(dataOf(asUnit(sb(2, HOUR)))); + Date.now.mockClear(); + context.peek("exp_sb"); + context.peekVariableValue("sb.arm", -1); + context.variableValue("sb.arm", -1); + context.treatment("exp_sb"); + // One reading, for the one exposure, as before switchbacks. + expect(Date.now).toHaveBeenCalledTimes(1); + }); + + // A grid change that lowers the current index below the retained ones must not evict the entry + // it just installed. + it("exposes once after a grid refresh to a lower index", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 99 * HOUR; + context.treatment("exp_sb"); + clock = ANCHOR + 100 * HOUR; + context.treatment("exp_sb"); + expect(context.pending()).toEqual(2); + + const restarted = sb(2, HOUR); + restarted.switchbackStartAt = ANCHOR + 100 * HOUR; + await refreshTo(context, restarted); + for (let i = 0; i < 3; ++i) { + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + } + expect(context.pending()).toEqual(3); + }); + + it("exposes once after a period-length refresh to a lower index", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 100 * HOUR; + context.treatment("exp_sb"); + clock = ANCHOR + 101 * HOUR; + context.treatment("exp_sb"); + + await refreshTo(context, sb(2, 200 * HOUR)); + context.treatment("exp_sb"); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(3); + }); + + // Rewinding the clock across retained periods re-exposes each re-entered evicted period at most once. + it("re-exposes an evicted period at most once after a clock rewind", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + for (let i = 0; i < 3; ++i) { + clock = ANCHOR + i * HOUR; + context.treatment("exp_sb"); + } + expect(context.pending()).toEqual(3); + + clock = ANCHOR; + for (let i = 0; i < 3; ++i) { + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + } + expect(context.pending()).toEqual(4); + + // Retained {0, 2}: period 2 is still deduplicated, period 1 was evicted. + clock = ANCHOR + 2 * HOUR; + context.treatment("exp_sb"); + expect(context.pending()).toEqual(4); + clock = ANCHOR + HOUR; + for (let i = 0; i < 3; ++i) { + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[1]); + } + expect(context.pending()).toEqual(5); + + const exposures = await publishExposures(context); + expect(exposures[3]).toEqual(exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR, true, true)); + expect(exposures[4]).toEqual(exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true)); + }); + + // An overridden switchback slot is re-resolved on a grid change; the override still wins and the + // holdout never fires. + it("re-resolves an override when the grid changes", async () => { + const original = sb(3, HOUR); + original.holdoutIds = [11]; + const context = createContext({ ...dataOf(original), holdouts: [holdout([0, 1])] }); + context.override("exp_sb", 2); + + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(2); + expect(context.variableValue("sb.arm", -1)).toEqual(2); + expect(context.pending()).toEqual(1); + + // Same index 0 under the new period length; variant 2 now carries a different value. + const regridded = sb(3, 2 * HOUR); + regridded.holdoutIds = [11]; + regridded.variants[2] = { name: "C", config: '{"sb.arm":22}' }; + provider.getContextData.mockReturnValue(Promise.resolve({ ...dataOf(regridded), holdouts: [holdout([0, 1])] })); + await context.refresh(); + + expect(context.treatment("exp_sb")).toEqual(2); + expect(context.variableValue("sb.arm", -1)).toEqual(22); + expect(context.pending()).toEqual(2); + + const exposures = await publishExposures(context); + expect(exposures).toEqual([ + exposure(1, "exp_sb", 2, ANCHOR + 10, false, true, { overridden: true }), + exposure(1, "exp_sb", 2, ANCHOR + 10, false, true, { overridden: true }), + ]); + }); + + // Each identity transition is a new epoch: returning to an identical grid re-resolves. + it("re-resolves after switchback to unit to identical switchback", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + + const toUnit = sb(2, HOUR); + toUnit.randomizationType = "unit"; + await refreshTo(context, toUnit); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(2); + + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(3); + }); + + it("re-resolves a removed and restored switchback", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + + await refreshTo(context); + // An experiment missing from the data is exposed as variant 0, as before. + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(2); + + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(3); + }); + + it("drops the pre-anchor slot when the grid changes", async () => { + const gridA = sb(2, HOUR); + gridA.switchbackStartAt = ANCHOR + 10 * HOUR; + const context = createContext(dataOf(gridA)); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(1); + + await refreshTo(context, gridA); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(1); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + expect(context.pending()).toEqual(1); + }); + + // Switchback slots live in the experiment's epoch, which the switch to a unit experiment drops, so + // neither the pre-anchor slot nor any period slot outlives it. + it("drops every switchback slot when the experiment becomes a unit experiment", async () => { + const preAnchor = sb(2, HOUR); + preAnchor.switchbackStartAt = ANCHOR + 10 * HOUR; + const context = createContext(dataOf(preAnchor, switchback(2, "exp_periods", 2, HOUR))); + clock = ANCHOR + 10; + expect(context.peek("exp_sb")).toEqual(0); + expect(context.peek("exp_periods")).toEqual(EXPECTED_2_ARMS[0]); + clock = ANCHOR + HOUR; + expect(context.peek("exp_periods")).toEqual(EXPECTED_2_ARMS[1]); + expect(Object.keys(context._assignments)).toEqual([]); + expect(context._switchbackEpochs.exp_sb.periodless).toBeDefined(); + expect(Object.keys(context._switchbackEpochs.exp_periods.slots)).toEqual(["0", "1"]); + + const unit = asUnit(sb(2, HOUR)); + const periodsUnit = asUnit(switchback(2, "exp_periods", 2, HOUR)); + await refreshTo(context, unit, periodsUnit); + const expected = new VariantAssigner(hashUnit(UID)).assign(unit.split, unit.seedHi, unit.seedLo); + expect(context.treatment("exp_sb")).toEqual(expected); + context.treatment("exp_periods"); + expect(context.pending()).toEqual(2); + expect(Object.keys(context._assignments).sort()).toEqual(["exp_periods", "exp_sb"]); + expect(Object.keys(context._switchbackEpochs)).toEqual([]); + expect((await publishExposures(context)).map((e) => [e.name, e.variant, e.assigned])).toEqual([ + ["exp_sb", expected, true], + ["exp_periods", expect.any(Number), true], + ]); + }); + + // A unit assignment cached before a refresh made the experiment a switchback must not be served for + // its pre-anchor, unservable or legacy (period-less) resolution. + it("does not reuse a unit assignment when a refresh makes the experiment a switchback without a period", async () => { + for (const changes of [ + { switchbackStartAt: ANCHOR + 10 * HOUR }, + { switchbackPeriodMs: 0 }, + { switchbackClusters: null }, + ]) { + publisher.publish.mockClear(); + clock = ANCHOR + 10; + const unit = asUnit(sb(2, HOUR)); + unit.seedHi = 1; + const context = createContext(dataOf(unit)); + const expected = new VariantAssigner(hashUnit(UID)).assign(unit.split, unit.seedHi, unit.seedLo); + expect(expected).toEqual(1); + expect(context.treatment("exp_sb")).toEqual(1); + + await refreshTo(context, { ...sb(2, HOUR), seedHi: 1, ...changes }); + expect([changes, context.treatment("exp_sb")]).toEqual([changes, 0]); + expect([changes, context.variableValue("sb.arm", -1)]).toEqual([changes, 0]); + expect([changes, context.pending()]).toEqual([changes, 1]); + } + }); + + // A new epoch drops every slot of the old one on the next resolution, not only the one it replaces. + it("does not retain the slots of an earlier epoch", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + clock = ANCHOR + HOUR; + context.treatment("exp_sb"); + expect(Object.keys(context._switchbackEpochs.exp_sb.slots)).toEqual(["0", "1"]); + + await refreshTo(context, { ...sb(2, HOUR), switchbackDesignType: "other" }); + context.treatment("exp_sb"); + expect(Object.keys(context._switchbackEpochs.exp_sb.slots)).toEqual(["1"]); + }); + + // Period slots are kept apart from unit assignments, so an experiment named like a period slot key + // cannot replace one. + it("keeps a unit experiment named like a period slot apart from the switchback", async () => { + const unit = { ...asUnit(switchback(2, "exp_sb\u001f0", 2, HOUR)), seedHi: 1 }; + const context = createContext(dataOf(sb(2, HOUR), unit)); + clock = ANCHOR + 10; + for (let i = 0; i < 3; ++i) { + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + context.treatment("exp_sb\u001f0"); + } + expect((await publishExposures(context)).map((e) => e.name)).toEqual(["exp_sb", "exp_sb\u001f0"]); + }); + + // Switchbacks named like Object members (`__proto__` included) are cached and exposed like any + // other, through every read API, before the anchor and in a period, and setting a unit later works. + it("serves switchbacks named like Object members", async () => { + const names = ["constructor", "toString", "hasOwnProperty", "valueOf", "__proto__"]; + const inPeriod = names.map((n, i) => switchback(i + 1, n, 2, HOUR)); + const preAnchor = names.map((n, i) => ({ ...switchback(i + 11, `${n}_pre`, 2, HOUR), name: n })); + for (const [label, experiments, expected, exposed] of [ + ["in a period", inPeriod, EXPECTED_2_ARMS[0], names.length], + ["before the anchor", preAnchor.map((e) => ({ ...e, switchbackStartAt: ANCHOR + 10 * HOUR })), 0, 0], + ]) { + publisher.publish.mockClear(); + clock = ANCHOR + 10; + const context = createContext(dataOf(...experiments), { device_id: "d" }); + context.unit(UNIT_TYPE, UID); + for (const n of names) { + for (let i = 0; i < 2; ++i) { + expect([label, n, context.treatment(n), context.peek(n)]).toEqual([label, n, expected, expected]); + } + } + expect([label, context.pending()]).toEqual([label, exposed]); + context.override("constructor", 1); + expect(context.treatment("constructor")).toEqual(1); + // A unit set after the resolutions walks every cached slot. + expect(() => context.unit("user_id", "u")).not.toThrow(); + const published = (await publishExposures(context)).map((e) => e.name); + expect([label, published]).toEqual([label, exposed === 0 ? ["constructor"] : [...names, "constructor"]]); + } + }); + + // A unit assignment cached before a switchback stint is not served again when the experiment returns + // to a unit experiment: it is resolved and exposed again, as Java's dropSwitchbackEpoch does. + it("re-resolves a unit experiment after a switchback stint", async () => { + for (const startAt of [ANCHOR, ANCHOR + 10 * HOUR]) { + const context = createContext(dataOf(asUnit(sb(2, HOUR)))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + expect(context.pending()).toEqual(1); + + await refreshTo(context, { ...sb(2, HOUR), switchbackStartAt: startAt }); + context.treatment("exp_sb"); + const afterSwitchback = startAt === ANCHOR ? 2 : 1; + expect([startAt, context.pending()]).toEqual([startAt, afterSwitchback]); + + await refreshTo(context, asUnit(sb(2, HOUR))); + context.treatment("exp_sb"); + expect([startAt, context.pending()]).toEqual([startAt, afterSwitchback + 1]); + } + }); + + it("re-resolves an overridden experiment removed after a switchback stint", async () => { + const context = createContext(dataOf(asUnit(sb(2, HOUR)))); + context.override("exp_sb", 1); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + await refreshTo(context, sb(2, HOUR)); + context.treatment("exp_sb"); + await refreshTo(context); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(3); + }); + + // Setting a unit later re-resolves a period-less slot read without any linked unit, and only that. + it("re-resolves a period-less slot without a linked unit once the unit is set", async () => { + const preAnchor = { ...sb(2, HOUR), switchbackStartAt: ANCHOR + 10 * HOUR, fullOnVariant: 1 }; + const context = createContext(dataOf(preAnchor), {}); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + context.unit(UNIT_TYPE, UID); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.pending()).toEqual(1); + // A slot that already had its unit is kept when an unrelated unit is set. + context.unit("user_id", "u"); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.pending()).toEqual(1); + }); + + // Before the anchor there is no period: a clock moved back from period 0 does not reuse its slot. + it("does not serve a period slot before the anchor", () => { + const context = createContext(dataOf(sb(2, HOUR))); + const seeds = { ...sb(2, HOUR), seedLo: -6 }; + expect(assignSwitchbackPeriod(CLUSTER_KEY, 0, seeds.seedHi, seeds.seedLo, 2)).toEqual(1); + const drawn = createContext(dataOf(seeds)); + clock = ANCHOR + 10; + expect(drawn.treatment("exp_sb")).toEqual(1); + clock = ANCHOR - 10; + expect(drawn.treatment("exp_sb")).toEqual(0); + expect(drawn.pending()).toEqual(1); + expect(context.peek("exp_sb")).toEqual(0); + }); + + // An overridden period-less slot exposed without a linked unit is kept when a unit is set; an + // unexposed one is re-resolved. + it("keeps an exposed overridden period-less slot when a unit is set", () => { + const preAnchor = { ...sb(2, HOUR), switchbackStartAt: ANCHOR + 10 * HOUR }; + const exposed = createContext(dataOf(preAnchor), {}); + exposed.override("exp_sb", 1); + clock = ANCHOR + 10; + expect(exposed.treatment("exp_sb")).toEqual(1); + const slot = exposed._switchbackEpochs.exp_sb.periodless; + exposed.unit(UNIT_TYPE, UID); + expect(exposed._switchbackEpochs.exp_sb.periodless).toBe(slot); + expect(exposed.treatment("exp_sb")).toEqual(1); + expect(exposed.pending()).toEqual(1); + + const peeked = createContext(dataOf(preAnchor), {}); + peeked.override("exp_sb", 1); + expect(peeked.peek("exp_sb")).toEqual(1); + peeked.unit(UNIT_TYPE, UID); + expect(peeked._switchbackEpochs.exp_sb.periodless).toBeUndefined(); + }); + + // Java keeps a dropped slot's period index retained after a late unit, so a rollback past the two + // retained indices re-exposes as in java-sdk (3 exposures for periods 0, 1, 0). + it("keeps invalidated period indices retained when a linked unit arrives, as Java does", () => { + const context = createContext(dataOf(sb(2, HOUR)), {}); + for (const period of [2, 3]) { + clock = ANCHOR + period * HOUR; + context.treatment("exp_sb"); + } + context.unit(UNIT_TYPE, UID); + expect(context._switchbackEpochs.exp_sb.periods).toEqual([2, 3]); + expect(Object.keys(context._switchbackEpochs.exp_sb.slots)).toEqual([]); + for (const period of [0, 1, 0]) { + clock = ANCHOR + period * HOUR; + context.treatment("exp_sb"); + } + expect(context.pending()).toEqual(3); + }); + + it("drops the slots of an earlier epoch when the same period is resolved again", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + const regridded = sb(2, HOUR); + regridded.switchbackDesignType = "other"; + await refreshTo(context, regridded); + // Same cache key (period 0), new epoch: resolved and exposed again. + context.peek("exp_sb"); + expect(context.pending()).toEqual(1); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(2); + }); + + // Epochs are reconciled lazily; an intermediate state never looked up still ends the epoch. + it("re-resolves after transitions without an intervening lookup", async () => { + const context = createContext(dataOf(sb(2, HOUR))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + expect(context.pending()).toEqual(1); + + const toUnit = sb(2, HOUR); + toUnit.randomizationType = "unit"; + await refreshTo(context, toUnit); + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(2); + + await refreshTo(context); + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(3); + + const regridded = sb(2, HOUR); + regridded.switchbackDesignType = "other"; + await refreshTo(context, regridded); + await refreshTo(context, sb(2, HOUR)); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(context.pending()).toEqual(4); + + // An unchanged identity keeps the epoch. + await refreshTo(context, sb(2, HOUR)); + context.treatment("exp_sb"); + expect(context.pending()).toEqual(4); + }); + + // A legacy switchback serves under its declared unitType, so a unitType change is identity for it. + it("treats a unitType change on the legacy path as identity", async () => { + const legacy = sb(2, HOUR); + legacy.switchbackClusters = null; + const logger = jest.fn(); + const context = createContext(dataOf(legacy), { [UNIT_TYPE]: UID, user_id: "u1" }, logger); + clock = ANCHOR + 10; + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + + await refreshTo(context, { ...legacy, unitType: "other" }); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(-1); + + await refreshTo(context, { ...legacy, unitType: "user_id" }); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.variableValue("sb.arm", -1)).toEqual(0); + // An override shows which unit the legacy control is recorded under. + context.override("exp_sb", 1); + expect(context.treatment("exp_sb")).toEqual(1); + expect(await publishExposures(context)).toEqual([ + { ...exposure(1, "exp_sb", 1, ANCHOR + 10, false, true, { overridden: true }), unit: "user_id" }, + ]); + }); + + // Port of Java's staleRuleTransitionEvaluatesTheRulesTwice for a switchback: a rule outcome that changes + // after an attribute is set is evaluated once to find the slot stale and once to rebuild it, and the + // rebuilt slot is current afterwards. + it("evaluates the rules twice on a stale rule transition", () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = + '{"rules":[{"type":"assign","environments":[],"variant":1,"conditions":{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]}}]}'; + const context = createContext(dataOf(experiment)); + const rules = jest.spyOn(context._audienceMatcher, "evaluateParsedRules"); + clock = ANCHOR + 5; + expect(context.peek("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect(rules).toHaveBeenCalledTimes(1); + + context.attribute("country", "US"); + rules.mockClear(); + expect(context.peek("exp_sb")).toEqual(1); + expect(rules).toHaveBeenCalledTimes(2); + expect(context.peek("exp_sb")).toEqual(1); + expect(rules).toHaveBeenCalledTimes(2); + }); + + // An ineligible or absent switchback slot never consulted its rules, so neither a set attribute nor + // a rules refresh re-evaluates them or changes its result. + it("does not re-evaluate rules for an ineligible or absent slot", async () => { + const ineligible = switchback(1, "exp_ineligible", 2, HOUR); + ineligible.assignmentRules = ASSIGN_VARIANT_1; + ineligible.switchbackClusterValues = ["other-store"]; + const absent = switchback(2, "exp_absent", 2, HOUR); + absent.assignmentRules = ASSIGN_VARIANT_1; + absent.switchbackClusters = { device_id: CLUSTER_PATH }; + const context = createContext(dataOf(ineligible, absent)); + const evaluate = jest.spyOn(context._audienceMatcher, "evaluateParsedRules"); + clock = ANCHOR + 10; + expect(context.treatment("exp_ineligible")).toEqual(0); + expect(context.treatment("exp_absent")).toEqual(0); + expect(evaluate).not.toHaveBeenCalled(); + + context.attribute("x", 1); + const changedRules = '{"rules":[{"type":"assign","environments":[],"variant":1,"name":"changed"}]}'; + await refreshTo( + context, + { ...ineligible, assignmentRules: changedRules }, + { ...absent, assignmentRules: changedRules } + ); + + expect(context.treatment("exp_ineligible")).toEqual(0); + expect(context.treatment("exp_absent")).toEqual(0); + expect(evaluate).not.toHaveBeenCalled(); + expect(context.pending()).toEqual(0); + }); + + // A rule-won switchback re-resolved in the same period keeps its variant and is exposed once. + it("keeps the variant and exposes once after an in-period rule refresh", async () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = ASSIGN_VARIANT_1; + const context = createContext(dataOf(experiment)); + clock = ANCHOR + 5; + expect(context.treatment("exp_sb")).toEqual(1); + + context.attribute("tier", "x"); + const refreshed = sb(2, HOUR); + refreshed.assignmentRules = + '{"rules":[{"type":"assign","environments":[],"variant":1,"conditions":{"and":[{"eq":[{"var":"tier"},{"value":"x"}]}]}}]}'; + await refreshTo(context, refreshed); + clock = ANCHOR + 6; + expect(context.treatment("exp_sb")).toEqual(1); + expect(await publishExposures(context)).toEqual([ruleExposure("exp_sb", 1, ANCHOR + 5)]); + }); + + // A same-outcome revalidation advances the slot's stamps, so later reads do not evaluate again. + it("evaluates rules and audience once per change on a cached slot", () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = + '{"rules":[{"type":"assign","environments":[],"variant":1,"conditions":{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]}}]}'; + experiment.audience = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}'; + const context = createContext(dataOf(experiment)); + const rules = jest.spyOn(context._audienceMatcher, "evaluateParsedRules"); + const audience = jest.spyOn(context._audienceMatcher, "evaluate"); + clock = ANCHOR + 5; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_2_ARMS[0]); + expect([rules.mock.calls.length, audience.mock.calls.length]).toEqual([1, 1]); + + for (let i = 0; i < 3; ++i) context.peek("exp_sb"); + expect([rules.mock.calls.length, audience.mock.calls.length]).toEqual([1, 1]); + + context.attribute("unrelated", 1); + for (let i = 0; i < 3; ++i) context.peek("exp_sb"); + expect([rules.mock.calls.length, audience.mock.calls.length]).toEqual([2, 2]); + + context.attribute("country", "US"); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.pending()).toEqual(2); + for (let i = 0; i < 3; ++i) context.peek("exp_sb"); + expect(rules.mock.calls.length).toEqual(4); + }); + + // Before the anchor nothing is recorded, a traffic miss included, because the period check precedes + // traffic. From the anchor the same miss is recorded. + it("is silent for a pre-anchor traffic miss", async () => { + const experiment = sb(2, HOUR); + experiment.trafficSplit = [1, 0]; + clock = ANCHOR - 1; + const context = createContext(dataOf(experiment)); + expect(context.treatment("exp_sb")).toEqual(0); + expect(context.pending()).toEqual(0); + + clock = ANCHOR; + expect(context.treatment("exp_sb")).toEqual(0); + expect(await publishExposures(context)).toEqual([exposure(1, "exp_sb", 0, ANCHOR, true, false)]); + }); + + // An override on a switchback with no serving unit is exposed under the declared unitType when the + // cluster map is missing or unreadable, and under the first declared type of a readable map. + it("exposes an override without a serving unit under the legacy or first linked unit type", async () => { + const missing = switchback(1, "exp_missing_map", 2, HOUR); + missing.unitType = "user_id"; + missing.switchbackClusters = null; + const unreadable = switchback(2, "exp_unreadable_map", 2, HOUR); + unreadable.unitType = "user_id"; + unreadable.switchbackClusters = { [UNIT_TYPE]: "'unterminated" }; + const noUnit = switchback(3, "exp_no_unit", 2, HOUR); + noUnit.unitType = "user_id"; + noUnit.switchbackClusters = { device_id: "x", [UNIT_TYPE]: "y" }; + const context = createContext(dataOf(missing, unreadable, noUnit), { user_id: "u1" }); + context.override("exp_missing_map", 1); + context.override("exp_unreadable_map", 1); + context.override("exp_no_unit", 1); + clock = ANCHOR + 5; + expect(context.treatment("exp_missing_map")).toEqual(1); + expect(context.treatment("exp_unreadable_map")).toEqual(1); + expect(context.treatment("exp_no_unit")).toEqual(1); + + expect(await publishExposures(context)).toEqual([ + { ...exposure(1, "exp_missing_map", 1, ANCHOR + 5, false, true, { overridden: true }), unit: "user_id" }, + { ...exposure(2, "exp_unreadable_map", 1, ANCHOR + 5, false, true, { overridden: true }), unit: "user_id" }, + { ...exposure(3, "exp_no_unit", 1, ANCHOR + 5, false, true, { overridden: true }), unit: "device_id" }, + ]); + }); + + // An overridden switchback exposed with no linked unit is not resolved again when one is set, so + // the override is not exposed twice; an unexposed one is. + it("keeps an exposed override without a linked unit when a unit is set", async () => { + const context = createContext(dataOf(sb(2, HOUR), switchback(2, "exp_peeked", 2, HOUR)), {}); + context.override("exp_sb", 1); + context.override("exp_peeked", 1); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.peek("exp_peeked")).toEqual(1); + context.unit(UNIT_TYPE, UID); + expect(context.treatment("exp_sb")).toEqual(1); + expect(context.treatment("exp_peeked")).toEqual(1); + const exposures = await publishExposures(context); + expect(exposures.map((e) => [e.name, e.unit])).toEqual([ + ["exp_sb", UNIT_TYPE], + ["exp_peeked", UNIT_TYPE], + ]); + }); + + // A slot read while no linked unit was set is read again when it is rebuilt: an exposed override kept + // across setUnit, then changed, is recorded under the unit that now serves. + it("reads the cluster again for a slot resolved without a linked unit", async () => { + const experiment = sb(2, HOUR); + experiment.switchbackClusters = { device_id: "device_key", [UNIT_TYPE]: CLUSTER_PATH }; + const context = createContext(dataOf(experiment), {}); + context.override("exp_sb", 1); + expect(context.treatment("exp_sb")).toEqual(1); + context.unit(UNIT_TYPE, UID); + expect(context.treatment("exp_sb")).toEqual(1); + context.override("exp_sb", 0); + expect(context.treatment("exp_sb")).toEqual(0); + expect((await publishExposures(context)).map((e) => [e.variant, e.unit])).toEqual([ + [1, "device_id"], + [0, UNIT_TYPE], + ]); + }); + + it("publishes rule-won and traffic-miss exposures exactly", async () => { + const rule = switchback(1, "exp_rule", 2, HOUR); + rule.assignmentRules = ASSIGN_VARIANT_1; + const miss = switchback(2, "exp_miss", 2, HOUR); + miss.trafficSplit = [1, 0]; + const context = createContext(dataOf(rule, miss)); + clock = ANCHOR + 5; + context.treatment("exp_rule"); + context.treatment("exp_miss"); + clock = ANCHOR + 9; + + const [request] = await publishRequests(context); + expect(JSON.stringify(request)).toEqual( + JSON.stringify({ + publishedAt: ANCHOR + 9, + units: [{ type: UNIT_TYPE, uid: UID_HASH }], + hashed: true, + sdkVersion: SDK_VERSION, + exposures: [ + ruleExposure("exp_rule", 1, ANCHOR + 5), + exposure(2, "exp_miss", 0, ANCHOR + 5, true, false), + ], + attributes: [{ name: CLUSTER_PATH, value: CLUSTER_KEY, setAt: ANCHOR }], + }) + ); + }); + + // Traffic comes before the custom assignment: a traffic miss wins over it and is recorded, custom=false. + it("lets a traffic miss win over a custom assignment", async () => { + const miss = sb(3, HOUR); + miss.trafficSplit = [1, 0]; + const context = createContext(dataOf(miss)); + context.customAssignment("exp_sb", 2); + clock = ANCHOR + 2 * HOUR; + expect(context.treatment("exp_sb")).toEqual(0); + expect(await publishExposures(context)).toEqual([exposure(1, "exp_sb", 0, ANCHOR + 2 * HOUR, true, false)]); + }); + + // A custom assignment set or changed later re-resolves the slot, as for a unit experiment. + it("re-resolves a slot when the custom assignment changes", async () => { + const context = createContext(dataOf(sb(3, HOUR))); + clock = ANCHOR + 2 * HOUR; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_3_ARMS[2]); + context.customAssignment("exp_sb", 2); + expect(context.treatment("exp_sb")).toEqual(2); + context.customAssignment("exp_sb", 2); + expect(context.treatment("exp_sb")).toEqual(2); + expect(context.pending()).toEqual(2); + }); + + it("re-resolves a slot when full-on or traffic changes on refresh", async () => { + const context = createContext(dataOf(sb(3, HOUR))); + clock = ANCHOR + 2 * HOUR; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_3_ARMS[2]); + await refreshTo(context, { ...sb(3, HOUR), fullOnVariant: 2 }); + expect(context.treatment("exp_sb")).toEqual(2); + await refreshTo(context, { ...sb(3, HOUR), fullOnVariant: 2, trafficSplit: [1, 0] }); + expect(context.treatment("exp_sb")).toEqual(2); + await refreshTo(context, { ...sb(3, HOUR), trafficSplit: [1, 0] }); + expect(context.treatment("exp_sb")).toEqual(0); + // Each change re-resolves and exposes once, as for a unit experiment. + expect(context.pending()).toEqual(4); + }); + + // The serving unit and cluster key are read once per period slot: a later setAttribute does not + // move the unit to another cluster, even when an audience change rebuilds the slot. + it("reads the cluster once per period slot", async () => { + const experiment = sb(3, HOUR); + experiment.audience = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}'; + const context = createContext(dataOf(experiment)); + clock = ANCHOR + 2 * HOUR; + const first = context.treatment("exp_sb"); + expect(first).toEqual(EXPECTED_3_ARMS[2]); + + context.attribute(CLUSTER_PATH, "store-7"); + expect(context.treatment("exp_sb")).toEqual(first); + // The audience now matches, so the slot is rebuilt and exposed again, under the same cluster. + context.attribute("tier", "gold"); + expect(context.treatment("exp_sb")).toEqual(first); + expect(context.pending()).toEqual(2); + + // The next period reads the attributes again. + clock = ANCHOR + 3 * HOUR; + expect(context.treatment("exp_sb")).toEqual(draw("store-7", 3, seedOf(SEED_HI, SEED_LO), 3)); + }); + + // Only attributes set at or before the resolving reading are seen; the latest setAt wins and a tie + // goes to the one set last. System attributes are not visible to cluster paths. + it("reads the attribute the Collector reads at the resolution instant", () => { + // Ten arms and values whose period-2 draws all differ (v8 -> 0, v28 -> 1, v0 -> 2, v2 -> 3, v1 -> 4), + // so every wrong pick serves a different arm. + const experiment = sb(10, HOUR); + const systemOnly = switchback(2, "exp_system", 3, HOUR); + systemOnly.switchbackClusters = { [UNIT_TYPE]: "application" }; + clock = ANCHOR + 2 * HOUR - 10; + const context = createContext(dataOf(experiment, systemOnly)); + context.attribute(CLUSTER_PATH, "v8"); + clock = ANCHOR + 2 * HOUR - 5; + // Names are compared trimmed; the latest setAt wins and a tie goes to the one set last. + context.attribute(` ${CLUSTER_PATH} `, "v28"); + context.attribute(CLUSTER_PATH, "v0"); + clock = ANCHOR + 2 * HOUR + 5; + // Set after the resolving reading below: not seen. + context.attribute(CLUSTER_PATH, "v2"); + clock = ANCHOR + 2 * HOUR; + const expected = draw("v0", 2, seedOf(SEED_HI, SEED_LO), 10); + expect(expected).toEqual(2); + expect(context.peek("exp_sb")).toEqual(expected); + // System attributes are not visible to cluster paths. + expect(context.treatment("exp_system")).toEqual(0); + expect(context.pending()).toEqual(0); + }); + + it("reads a trimmed attribute name like the Collector", () => { + clock = ANCHOR + 2 * HOUR; + const context = createContext(dataOf(sb(10, HOUR))); + context.attribute(` ${CLUSTER_PATH}\t`, "v1"); + expect(context.peek("exp_sb")).toEqual(draw("v1", 2, seedOf(SEED_HI, SEED_LO), 10)); + expect(context.peek("exp_sb")).toEqual(4); + }); + + it("tolerates unknown and future switchback fields", () => { + const experiment = { + ...sb(3, HOUR), + switchbackClusterUnitType: UNIT_TYPE, + switchbackClusterCount: 10, + switchbackClusterAttribute: CLUSTER_PATH, + switchbackFuture: { nested: [1, { a: null }] }, + switchbackCarryoverDurationMs: "not a number", + switchbackEstimand: { unexpected: true }, + }; + const phase1e = { + ...sb(3, HOUR), + id: 2, + name: "exp_phase1e", + switchbackClusters: undefined, + switchbackClusterCount: 4, + }; + const context = createContext(dataOf(experiment, phase1e, asUnit(switchback(3, "exp_unit", 2, HOUR)))); + clock = ANCHOR + 2 * HOUR; + expect(context.treatment("exp_sb")).toEqual(EXPECTED_3_ARMS[2]); + expect(context.treatment("exp_phase1e")).toEqual(0); + expect(context.treatment("exp_unit")).toEqual(expect.any(Number)); + expect(context.pending()).toEqual(2); + }); + + it("keeps the declared cluster order of a parsed payload", () => { + const json = `{"experiments":[${JSON.stringify(sb(3, HOUR)).replace( + `"switchbackClusters":{"${UNIT_TYPE}":"${CLUSTER_PATH}"}`, + `"switchbackClusters":{"user_id":"profile/city","device_id":"device/city","${UNIT_TYPE}":"store_city"}` + )}]}`; + const data = JSON.parse(json); + expect(Object.keys(data.experiments[0].switchbackClusters)).toEqual(["user_id", "device_id", UNIT_TYPE]); + const context = createContext(data, { device_id: "d1", [UNIT_TYPE]: UID, user_id: "u1" }); + context.attributes({ profile: { city: "many-3" }, device: { city: "many-3" }, store_city: "many-3" }); + context.override("exp_sb", 1); + context.treatment("exp_sb"); + expect(context._exposures.map((e) => e.unit)).toEqual(["user_id"]); + }); +}); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7497958..f16a09a 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6025,47 +6025,1058 @@ describe("Context", () => { expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); }); - // A throwing eventLogger for one candidate's exposure is isolated by _logEvent (it never - // propagates), so it must not stop the loop from visiting (and firing exposures for) the - // remaining candidates sharing the key. - it("a throwing eventLogger for one candidate does not stop later candidates in the loop from being visited and exposed", () => { - const firstExperiment = holdoutVarExperiment({ - id: 1, - name: "exp_holdout_var_throw_first", - holdoutIds: [11], + const winnerAfterHoldout = (over) => ({ + ...holdoutVarExperiment({}), + id: 2, + name: "exp_holdout_var_later_winner", + split: [0, 1], + fullOnVariant: 1, + holdoutIds: null, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "button.color": "WINNER_AFTER_HOLDOUT" }) }, + ], + ...over, + }); + + // A throwing eventLogger for the first candidate's holdout exposure is isolated by _logEvent, + // so the loop still reaches the later winner and exposes it. + it("a throwing eventLogger for one candidate does not stop the loop from reaching and exposing the winner", () => { + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure" && data.name === "holdout_var") { + throw new Error("boom"); + } + }); + + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + + const exposureCalls = eventLogger.mock.calls.filter((c) => c[1] === "exposure"); + expect(exposureCalls.map((c) => c[2].name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); + expect(context.pending()).toEqual(2); + }); + + // A logger that finalizes from a holdout's exposure callback must still send the winner: + // every exposure of the read is queued before any user callback runs. + it("sends the winner when an exposure callback finalizes the context mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure" && data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } }); - const secondExperiment = holdoutVarExperiment({ + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); + }); + + it("queues no extra callbacks when a callback re-reads an already exposed key", () => { + const names = []; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.variableValue("button.color", "APP_FALLBACK"); + } + }); + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(names).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); + expect(context.pending()).toEqual(2); + }); + + // An attribute getter is user code that can re-enter variableValue() mid-read; the nested read + // must not release the outer read's deferral before the outer winner is queued. + it("keeps deferring when an attribute getter re-enters variableValue() mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let reentered = false; + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const other = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_other_key", + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "other.key": "OTHER" }) }, + ], + }; + const response = buildHoldoutResponse([strictFirst, winnerAfterHoldout({}), other], []); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + if (!reentered) { + reentered = true; + context.variableValue("other.key", "D"); + } + return "free"; + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual([ + "exp_other_key", + "exp_holdout_var_later_winner", + ]); + }); + + it("creates no deferred list and arms no timer on a warmed read", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + clearTimeout(context._publishTimeout); + context._publishTimeout = undefined; + const schedule = jest.spyOn(context, "_setTimeout"); + const lists = []; + let deferredLogs; + Object.defineProperty(context, "_deferredLogs", { + configurable: true, + get: () => deferredLogs, + set: (value) => { + if (value !== undefined) lists.push(value); + deferredLogs = value; + }, + }); + for (let i = 0; i < 5; i++) context.variableValue("button.color", "APP_FALLBACK"); + expect(lists).toEqual([]); + expect(schedule).not.toHaveBeenCalled(); + }); + + it("replays a read's exposure and error callbacks in the order they were raised", () => { + const events = []; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure") events.push(`exposure:${data.name}`); + if (eventName === "error") events.push("error"); + }); + const strictSecond = { + ...holdoutVarExperiment({}), id: 2, - name: "exp_holdout_var_throw_second", - holdoutIds: [12], + name: "exp_strict_second", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), strictSecond, winnerAfterHoldout({ id: 3 })], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, }); + context.attribute("user", user); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(events).toEqual(["exposure:holdout_var", "error", "exposure:exp_holdout_var_later_winner"]); + }); - const secondHoldout = alwaysHoldsOut({ id: 12, name: "holdout_var_second" }); + it("arms no publish timer when a read raises only an error", () => { + const strictOnly = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100, eventLogger: jest.fn() }, + contextParams, + buildHoldoutResponse([strictOnly], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.pending()).toEqual(0); + expect(context._publishTimeout).toBeUndefined(); + }); + + it("sends a treatment's holdout exposure when its exposure callback finalizes", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const covered = { ...winnerAfterHoldout({}), holdoutIds: [11] }; + const neverHolds = alwaysHoldsOut({ split: [0, 1] }); + const response = buildHoldoutResponse([covered], [neverHolds]); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.treatment("exp_holdout_var_later_winner")).toBe(1); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name).sort()).toEqual( + ["exp_holdout_var_later_winner", "holdout_var"].sort() + ); + }); + it("reports a nested treatment() exposure raised from an exposure callback", () => { + const names = []; + let nested = false; const eventLogger = jest.fn((ctx, eventName, data) => { - if (eventName === "exposure" && data.name === "holdout_var") { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.treatment("exp_holdout_var_later_winner"); + } + }); + const covered = { ...winnerAfterHoldout({ id: 3, name: "exp_covered" }), holdoutIds: [11] }; + const neverHolds = alwaysHoldsOut({ split: [0, 1] }); + const response = buildHoldoutResponse([covered, winnerAfterHoldout({})], [neverHolds]); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.treatment("exp_covered"); + expect(names).toEqual(["exp_covered", "holdout_var", "exp_holdout_var_later_winner"]); + expect(context._deferredLogs).toBeUndefined(); + expect(context.pending()).toEqual(3); + }); + + it("keeps a read's deferral when an attribute getter calls treatment() mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + let reentered = false; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const plain = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_plain", + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + }; + const response = buildHoldoutResponse( + [strictFirst, winnerAfterHoldout({}), plain], + [alwaysHoldsOut({ split: [0, 1] })] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + if (!reentered) { + reentered = true; + context.treatment("exp_plain"); + } + return "free"; + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual([ + "exp_plain", + "holdout_var", + "exp_holdout_var_later_winner", + ]); + }); + + it("logs callbacks in queue order when a replayed callback reads another key", () => { + const names = []; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.variableValue("other.key", "D"); + } + }); + const other = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_other_key", + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "other.key": "OTHER" }) }, + ], + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({}), other], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(names).toEqual(context._exposures.map((e) => e.name)); + expect(names).toEqual(["holdout_var", "exp_holdout_var_later_winner", "exp_other_key"]); + }); + + it("walks each visited candidate's holdouts once per read", () => { + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), { ...winnerAfterHoldout({}), holdoutIds: [12] }], + [alwaysHoldsOut({}), alwaysHoldsOut({ id: 12, name: "holdout_never", split: [0, 1] })] + ); + const context = new Context(sdk, contextOptions, contextParams, response); + const walk = jest.spyOn(context, "_triggerApplicableHoldoutExposures"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(walk).toHaveBeenCalledTimes(2); + }); + + it("returns the default for an unindexed key without assigning any experiment", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, contextOptions, contextParams, response); + const assign = jest.spyOn(context, "_assign"); + expect(context.variableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.peekVariableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(assign).not.toHaveBeenCalled(); + expect(context._deferredLogs).toBeUndefined(); + }); + + it("walks a warmed shared key's candidates without an array iterator", () => { + const response = buildHoldoutResponse([holdoutVarExperiment({}), winnerAfterHoldout({})], []); + const context = new Context(sdk, contextOptions, contextParams, response); + const first = context.variableValue("button.color", "D"); + expect(first).not.toEqual("D"); + const iterator = Array.prototype[Symbol.iterator]; + let walks = 0; + let value; + let peeked; + try { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = function () { + walks++; + return iterator.call(this); + }; + value = context.variableValue("button.color", "D"); + peeked = context.peekVariableValue("button.color", "D"); + } finally { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = iterator; + } + expect([value, peeked, walks]).toEqual([first, first, 0]); + }); + + it("arms the timer for an exposure first queued from a replayed error callback", () => { + const strict = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const other = { + ...winnerAfterHoldout({}), + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"other.key":"OTHER"}' }, + ], + }; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "error") ctx.variableValue("other.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100, eventLogger }, + contextParams, + buildHoldoutResponse([strict, other], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { throw new Error("boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("D"); + expect(context.pending()).toBe(1); + expect(context._publishTimeout).toBeDefined(); + clearTimeout(context._publishTimeout); + }); + + it("does not feed error-observer errors into the replay queue forever", () => { + let count = 0; + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" || eventName === "error") { + if (++count < 50000) { + ctx.attribute("observer.seq", count); + ctx.variableValue("error.key", "D"); + } + } + }); + const experiment = winnerAfterHoldout({ + customFieldValues: [{ name: "bad", type: "future", value: "x" }], + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse( + [ + experiment, + { + ...holdoutVarExperiment({}), + id: 4, + name: "error_exp", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ + filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }], + }), + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"error.key":1}' }, + ], + }, + ], + [] + ) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("observer getter"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBeLessThan(2000); + expect(context._deferredLogs).toBeUndefined(); + } finally { + consoleError.mockRestore(); + } + }); + + it("delivers every callback of finite exposure feedback", () => { + let count = 0; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && ++count < 100) ctx.variableValue("button.color", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBe(100); + expect(context.pending()).toBe(100); + expect(context._deferredLogs).toBeUndefined(); + expect(context._deferringLogs).toBe(false); + }); + + it("returns from unbounded exposure feedback when the clock advances on every callback", () => { + let count = 0; + let now = timeOrigin; + Date.now.mockImplementation(() => now); + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + now += 2; + if (++count < 50000) ctx.variableValue("button.color", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBeLessThan(2000); + expect(context._deferringLogs).toBe(false); + } finally { + consoleError.mockRestore(); + } + }); + + it("reports a re-exposure whose flags differ within the same drain", () => { + const reported = []; + const strict = { + ...winnerAfterHoldout({}), + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "plan" }, { value: "pro" }] }] }), + }; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + reported.push(data.audienceMismatch); + if (reported.length === 1) { + ctx.attribute("plan", "pro"); + ctx.treatment("exp_holdout_var_later_winner"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([strict], []) + ); + context.treatment("exp_holdout_var_later_winner"); + expect(reported).toEqual([true, false]); + expect(context.pending()).toBe(2); + }); + + it("reports an error raised inside an error callback", () => { + const errors = []; + const strict = (id, experimentName, key) => ({ + ...holdoutVarExperiment({}), + id, + name: experimentName, + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [key]: 1 }) }, + ], + }); + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "error") return; + errors.push(data.message); + if (errors.length === 1) { + ctx.attribute("seq", 1); + ctx.variableValue("second.key", "D"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([strict(1, "e_first", "first.key"), strict(2, "e_second", "second.key")], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("first.key", "D")).toBe("D"); + expect(errors).toHaveLength(2); + }); + + const feedbackDepths = (limit) => { + let depth = 0; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < limit) ctx.variableValue("button.color", "D"); + } finally { + depth--; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + return depths; + }; + + it("keeps finite feedback within the replay rounds at depth 1", () => { + expect(feedbackDepths(31)).toEqual(Array(31).fill(1)); + }); + + it("runs treatment() feedback inline once the replay rounds are spent", () => { + let depth = 0; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < 40) ctx.treatment("exp_holdout_var_later_winner"); + } finally { + depth--; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + context.treatment("exp_holdout_var_later_winner"); + expect(depths).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it("defers again in a later read after a replay spent its rounds", () => { + let depth = 0; + let limit = 40; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < limit) ctx.variableValue("button.color", "D"); + } finally { + depth--; } }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + depths.length = 0; + limit = 10; + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(depths).toEqual(Array(10).fill(1)); + }); + it("sends the winner when a later read finalizes after a replay spent its rounds", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let mode = "loop"; + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (mode === "loop") { + if (++count < 40) ctx.variableValue("loop.key", "D"); + } else if (data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } + }); + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; const response = buildHoldoutResponse( - [firstExperiment, secondExperiment], - [alwaysHoldsOut({}), secondHoldout] + [holdoutVarExperiment({}), winnerAfterHoldout({}), loop], + [alwaysHoldsOut({})] ); const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + expect(count).toBe(40); + mode = "finalize"; + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name).filter((n) => n !== "exp_loop")).toEqual([ + "holdout_var", + "exp_holdout_var_later_winner", + ]); + }); + + it.each([30, 31, 32, 33, 40])( + "sends a read's whole exposure batch when its logger finalizes after %i feedback callbacks", + async (chain) => { + publisher.publish.mockReturnValue(Promise.resolve()); + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (data.name === "exp_loop") { + if (++count < chain) ctx.variableValue("loop.key", "D"); + else if (count === chain) ctx.variableValue("button.color", "APP_FALLBACK"); + } else if (data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } + }); + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({}), loop], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toBe(0); + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures; + expect(sent.map((e) => e.name).filter((n) => n !== "exp_loop")).toEqual([ + "holdout_var", + "exp_holdout_var_later_winner", + ]); + } + ); - expect(() => context.variableValue("button.color", "APP_FALLBACK")).not.toThrow(); + it("bounds the callbacks a replay retains when each callback raises two more", () => { + const strict = (id, experimentName, key) => ({ + ...holdoutVarExperiment({}), + id, + name: experimentName, + holdoutIds: null, + split: [0, 1], + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [key]: 1 }) }, + ], + }); + let count = 0; + let errors = 0; + let maxRetained = 0; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure" && eventName !== "error") return; + if (eventName === "error") errors++; + maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); + if (++count > 2500) return; + ctx.attribute("a", count); + ctx.variableValue("e1.key", "D"); + ctx.attribute("b", count); + ctx.variableValue("e2.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse( + [winnerAfterHoldout({}), strict(5, "e1", "e1.key"), strict(6, "e2", "e2.key")], + [] + ) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + // Without the callback budget each round doubles the held list until round 32. + expect(errors).toBeGreaterThan(2048); + expect(maxRetained).toBeLessThanOrEqual(1024); + expect(context._deferredLogs).toBeUndefined(); + }); - const exposureCalls = eventLogger.mock.calls.filter((c) => c[1] === "exposure"); - expect(exposureCalls.map((c) => c[2].name).sort()).toEqual( - ["holdout_var", "holdout_var_second"].sort() + const cutoffResponse = () => + buildHoldoutResponse( + [ + { + ...holdoutVarExperiment({}), + name: "exp_held", + variants: [ + { name: "A", config: JSON.stringify({ "cut.key": "CONTROL" }) }, + { name: "B", config: JSON.stringify({ "cut.key": "T" }) }, + ], + }, + { + ...winnerAfterHoldout({}), + name: "exp_win", + holdoutIds: [12], + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "cut.key": "WIN" }) }, + ], + }, + { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }, + ], + [ + alwaysHoldsOut({ name: "holdout_a" }), + alwaysHoldsOut({ id: 12, name: "holdout_b", split: [0, 1] }), + ] ); + + const cutoff = async (chain, mode) => { + publisher.publish.mockReturnValue(Promise.resolve()); + const callbacks = []; + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (data.name === "exp_loop") { + if (++count < chain) ctx.variableValue("loop.key", "D"); + else if (count === chain) { + if (mode === "treatment") ctx.treatment("exp_win"); + else ctx.variableValue("cut.key", "D"); + } + return; + } + callbacks.push(data.name); + if (finalizing === undefined) finalizing = ctx.finalize(); + }); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, cutoffResponse()); + context.customAssignment("exp_loop", 0); + if (mode === "treatment") context.override("exp_win", 1); + context.variableValue("loop.key", "D"); + await finalizing; + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures + .map((e) => e.name) + .filter((n) => n !== "exp_loop"); + return { callbacks, sent, pending: context.pending() }; + }; + + it.each([31, 32, 40])( + "sends a treatment()'s whole batch when its logger finalizes after %i feedback callbacks", + async (chain) => { + const result = await cutoff(chain, "treatment"); + expect(result.sent).toEqual(["exp_win", "holdout_b"]); + expect(result.pending).toBe(0); + } + ); + + it.each([31, 32, 40])( + "delivers every callback of a batch after %i feedback callbacks once, in queue order", + async (chain) => { + const result = await cutoff(chain, "variableValue"); + expect(result.callbacks).toEqual(["holdout_a", "holdout_b", "exp_win"]); + expect(result.sent).toEqual(["holdout_a", "holdout_b", "exp_win"]); + } + ); + + it("arms no publish timer for an error-only batch after the replay limit", () => { + const strict = { + ...holdoutVarExperiment({}), + name: "exp_strict", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: JSON.stringify({ "s.key": "a" }) }, + { name: "B", config: JSON.stringify({ "s.key": "b" }) }, + ], + }; + let errors = 0; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "error" || ++errors > 40) return; + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100000, eventLogger }, + contextParams, + buildHoldoutResponse([strict], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + context.variableValue("s.key", "D"); + expect(errors).toBeGreaterThan(32); + expect(context.pending()).toBe(0); + expect(context._publishTimeout).toBeUndefined(); + }); + + it.each([ + [1023, false], + [1024, true], + ])("stops queueing rounds once a replay has delivered %i callbacks: %p", (width, exhausted) => { + const experiments = []; + for (let i = 0; i < width; i++) { + experiments.push({ + ...holdoutVarExperiment({}), + id: 100 + i, + name: `exp_w${i}`, + holdoutIds: null, + split: [0, 1], + fullOnVariant: 1, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [`w${i}`]: i }) }, + ], + }); + } + let fanned = false; + let after; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + if (!fanned) { + fanned = true; + for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); + } else if (after === undefined && ctx._deferringLogs !== undefined) { + after = ctx._replayExhausted; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(context.variableValue("w0", "D")).toBe(0); + expect(after).toBe(exhausted); + expect(context.pending()).toBe(width); + }); + + it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { + const strict = { + ...holdoutVarExperiment({}), + name: "exp_strict", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: JSON.stringify({ "s.key": "a" }) }, + { name: "B", config: JSON.stringify({ "s.key": "b" }) }, + ], + }; + const plain = { + ...winnerAfterHoldout({}), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "p.key": "P" }) }, + ], + }; + const events = []; + let errors = 0; + let done = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure") events.push(`exposure:${data.name}`); + if (eventName !== "error") return; + if (++errors < 40) { + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + } else if (!done) { + done = true; + events.length = 0; + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + ctx.variableValue("p.key", "D"); + } else { + events.push("error"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100000, eventLogger }, + contextParams, + buildHoldoutResponse([strict, plain], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + context.variableValue("s.key", "D"); + try { + expect(events).toEqual(["error", "exposure:exp_holdout_var_later_winner"]); + expect(context.pending()).toBe(1); + expect(context._publishTimeout).toBeDefined(); + } finally { + clearTimeout(context._publishTimeout); + } + }); + + it("runs feedback callbacks inline once the replay rounds are spent", () => { + expect(feedbackDepths(40)).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it("schedules the publish timer after a variable read's deferred exposures", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); + const schedule = jest.spyOn(context, "_setTimeout"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(context.pending()).toEqual(1); + expect(schedule).toHaveBeenCalled(); + expect(context._publishTimeout).toBeDefined(); + clearTimeout(context._publishTimeout); }); - // peekVariableValue() shares the exact same suppressedFallback capture as variableValue() - // (both fixed together in the same commit), but never triggers exposures, so it needs its - // own ordering regression test rather than relying on variableValue()'s coverage. + it("defers an error callback raised mid-read so finalizing from it still sends the winner", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "error" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const response = buildHoldoutResponse([strictFirst, winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual(["exp_holdout_var_later_winner"]); + }); + + // peekVariableValue() picks the same first held-out fallback as variableValue() but never + // triggers exposures, so it needs its own ordering regression test. it("peekVariableValue(): an earlier suppressed candidate without the key blocks a later suppressed candidate that has it", () => { const firstSuppressed = holdoutVarExperiment({ id: 1, @@ -6140,13 +7151,9 @@ describe("Context", () => { expect(exposureCalls.map((c) => c[2].name)).toContain("exp_holdout_var_winner_after_throw_2"); }); - // java's override write path never sets `suppressed` at all (see Assignment.suppressed's - // doc comment), so an override can never become java's suppressedFallback. The JS port - // pins `suppressed` eagerly on the override path too, so the fallback capture must - // explicitly exclude overridden assignments to reproduce the same outcome — otherwise an - // override to a variant that happens to omit the requested key could win the fallback - // slot ahead of a genuinely suppressed sibling that actually defines it. - it("excludes an overridden assignment from the suppressedFallback even when it is also held out", () => { + // An override wins even when its selected variant omits the key; holdout fallback + // must not replace it with another experiment's control value. + it("returns the winning override default even when it is also held out", () => { const overriddenExperiment = { id: 1, name: "exp_holdout_var_overridden", @@ -6161,8 +7168,6 @@ describe("Context", () => { fullOnVariant: 0, applications: [{ name: "website" }], variants: [ - // Override target (variant 0) omits the key, so this candidate can't win - // outright, and must not be allowed to claim the fallback slot either. { name: "A", config: null }, { name: "B", config: JSON.stringify({ "button.color": "OVERRIDE_SIBLING" }) }, ], @@ -6204,13 +7209,13 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, response); context.override("exp_holdout_var_overridden", 0); - expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("GENUINE_SUPPRESSED_CTRL"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.pending()).toEqual(2); }); - // _peekVariable carries the identical override-exclusion guard as _variableValue (same - // fix, same commit), but never triggers exposures, so it needs its own regression test - // rather than relying on variableValue()'s coverage of the guard. - it("peekVariableValue(): excludes an overridden assignment from the suppressedFallback even when it is also held out", () => { + // peekVariableValue() stops at the same override winner as variableValue() but never + // triggers exposures, so it needs its own regression test. + it("peekVariableValue(): returns the winning override default even when it is also held out", () => { const overriddenExperiment = { id: 1, name: "exp_holdout_var_peek_overridden", @@ -6266,12 +7271,392 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, response); context.override("exp_holdout_var_peek_overridden", 0); - expect(context.peekVariableValue("button.color", "APP_FALLBACK")).toEqual("GENUINE_SUPPRESSED_CTRL"); + expect(context.peekVariableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); expect(context.pending()).toEqual(0); }); }); }); + describe("shared variable winner", () => { + const shared = (id, split, config, over = {}) => ({ + ...getContextResponse.experiments[0], + id, + name: `shared_${id}`, + split, + trafficSplit: [0, 1], + variants: [ + { name: "A", config: JSON.stringify(config) }, + { name: "B", config: JSON.stringify({ shared: `value_${id}` }) }, + ], + ...over, + }); + + it.each([0, 1])("keeps the first assigned experiment in arm %i, independent of key presence", (arm) => { + const eventLogger = jest.fn(); + // Reverse payload order to test experiment-id precedence, not insertion order. + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(2, [1, 0], { shared: "SECOND" }), shared(1, arm ? [0, 1] : [1, 0], {})], + }); + const expected = arm ? "value_1" : "SENTINEL"; + expect(context.peekVariableValue("shared", "SENTINEL")).toBe(expected); + expect(context.pending()).toBe(0); + expect(eventLogger.mock.calls.filter((c) => c[1] === "exposure")).toEqual([]); + expect(context.variableValue("shared", "SENTINEL")).toBe(expected); + expect(context.variableValue("shared", "SENTINEL")).toBe(expected); + expect(context.pending()).toBe(1); + expect(eventLogger.mock.calls.filter((c) => c[1] === "exposure").map((c) => c[2])).toEqual([ + expect.objectContaining({ name: "shared_1", variant: arm, assigned: true }), + ]); + }); + + it.each([null, false, 0, ""])( + "returns the present value %p rather than default or another experiment", + (value) => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [1, 0], { shared: value }), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe(value); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe(value); + expect(context.pending()).toBe(1); + } + ); + + it.each(["override", "rule"])("stops at a missing key when the first experiment wins by %s", (mode) => { + const assignmentRules = JSON.stringify({ + rules: [{ name: "control", type: "assign", conditions: { value: true }, environments: [], variant: 0 }], + }); + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [ + shared(1, [0, 1], {}, { trafficSplit: [1, 0], ...(mode === "rule" ? { assignmentRules } : {}) }), + shared(2, [1, 0], { shared: "SECOND" }), + ], + }); + if (mode === "override") context.override("shared_1", 0); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(1); + }); + + describe("variables named like Object.prototype members", () => { + const protoKeyed = (config) => ({ + ...shared(1, [0, 1], {}), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify(config) }, + ], + }); + const keys = ["toString", "constructor", "hasOwnProperty", "__proto__", "valueOf"]; + // From JSON, as the payload arrives: a `__proto__:` literal key would set the prototype instead. + const config = JSON.parse( + '{"toString":"ts","constructor":0,"hasOwnProperty":false,"__proto__":"p","valueOf":null}' + ); + + it("creates a ready context and resolves each defined key", () => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [protoKeyed(config)] }); + expect(context.isReady()).toBe(true); + expect(context.isFailed()).toBe(false); + for (const key of keys) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe(config[key]); + expect(context.variableValue(key, "SENTINEL")).toBe(config[key]); + } + expect(context.pending()).toBe(1); + }); + + it.each([null, "", "[]", "0", "false", '"string"', "null", '{"other":1}'])( + "returns the default when the winner config %p does not define the key", + (selectedConfig) => { + const winner = { ...protoKeyed(config), split: [1, 0] }; + winner.variants = [{ name: "A", config: selectedConfig }, winner.variants[1]]; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); + for (const key of keys) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + } + expect(context.pending()).toBe(1); + } + ); + + it("treats a config defining only toString as prototype-keyed", () => { + const winner = { ...protoKeyed({ toString: "T" }), split: [1, 0] }; + winner.variants = [ + { name: "A", config: '{"other":1}' }, + { name: "B", config: '{"toString":"T"}' }, + ]; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); + expect(context.peekVariableValue("toString", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("toString", "SENTINEL")).toBe("SENTINEL"); + }); + + it.each(["override", "assigned", "custom"])( + "follows a cached %s arm that a refresh removes and a later refresh restores", + async (kind) => { + const variants = [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ]; + const before = { ...shared(1, [0, 0, 1], {}), variants }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + if (kind === "override") context.override("shared_1", 2); + if (kind === "custom") context.customAssignment("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + provider.getContextData.mockReturnValue( + Promise.resolve({ experiments: [{ ...before, variants: variants.slice(0, 2), split: [0, 1] }] }) + ); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [before] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("c"); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + } + ); + + it("does not restore a removed arm's variables once the experiment id changes", async () => { + const variants = [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ]; + const before = { ...shared(1, [0, 0, 1], {}), variants }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + context.override("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + provider.getContextData.mockReturnValue( + Promise.resolve({ experiments: [{ ...before, variants: variants.slice(0, 2), split: [0, 1] }] }) + ); + await context.refresh(); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + // A different experiment now uses the name: the cached assignment must not adopt its arm. + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [{ ...before, id: 99 }] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + }); + + it("returns the default when a refresh removes a cached override's arm", async () => { + const before = { + ...shared(1, [1, 0], {}), + variants: [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ], + split: [0.34, 0.33, 0.33], + }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + context.override("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + const after = { ...before, variants: before.variants.slice(0, 2), split: [0.5, 0.5] }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + }); + + it("keeps a retained unit's value and ordinary snapshot across a refresh", async () => { + const before = { + ...shared(1, [0, 1], {}), + variants: [ + { name: "A", config: '{"k":"a1"}' }, + { name: "B", config: '{"k":"OLD"}' }, + ], + }; + const plain = { ...shared(2, [0, 1], { other: 1 }), name: "plain" }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before, plain] }); + expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.treatment("plain")).toBe(1); + const after = { + ...before, + variants: [ + { name: "A", config: '{"k":"a1","valueOf":"V"}' }, + { name: "B", config: '{"k":"NEW"}' }, + ], + }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after, plain] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.variableValue("valueOf", "SENTINEL")).toBe("SENTINEL"); + expect(Object.getPrototypeOf(context._assignments.plain.variables)).toBe(Object.prototype); + }); + + it("refreshes after an overridden experiment named like an Object.prototype member stops", async () => { + const named = { ...shared(1, [0, 1], {}), name: "toString" }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named] }); + context.override("toString", 1); + expect(context.treatment("toString")).toBe(1); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [] })); + await expect(context.refresh()).resolves.toBeUndefined(); + expect(context.experiments()).toEqual([]); + }); + + it("keeps Object.prototype on ordinary configs", () => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [0, 1], {}), { ...protoKeyed(config), id: 2, name: "shared_2" }], + }); + expect(Object.getPrototypeOf(context._index.shared_1.variables[1])).toBe(Object.prototype); + expect(Object.getPrototypeOf(context._index.shared_2.variables[1])).toBe(null); + }); + + it("does not resolve inherited members after a refresh makes an experiment prototype-keyed", async () => { + const before = { + ...shared(1, [1, 0], {}), + variants: [ + { name: "A", config: '{"other":1}' }, + { name: "B", config: null }, + ], + }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + expect(context.treatment("shared_1")).toBe(0); + const after = { + ...before, + variants: [before.variants[0], { name: "B", config: '{"toString":"T","valueOf":"V"}' }], + }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after] })); + await context.refresh(); + for (const key of ["toString", "valueOf"]) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + } + }); + + it("lists each key as an own entry of variableKeys()", () => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [protoKeyed(config), { ...protoKeyed({ toString: "x" }), id: 2, name: "shared_2" }], + }); + const variableKeys = context.variableKeys(); + expect(Object.getPrototypeOf(variableKeys)).toBe(Object.prototype); + expect(Object.keys(variableKeys).sort()).toEqual([...keys].sort()); + expect(variableKeys.toString).toEqual(["shared_1", "shared_2"]); + expect(Object.getOwnPropertyDescriptor(variableKeys, "__proto__").value).toEqual(["shared_1"]); + }); + }); + + it.each(["toString", "valueOf", "hasOwnProperty", "__proto__", "constructor"])( + "returns the caller default for the unindexed prototype-named key %s", + (key) => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [0, 1], {})], + }); + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + } + ); + + const exposures = (eventLogger) => eventLogger.mock.calls.filter((c) => c[1] === "exposure").map((c) => c[2]); + const notInFirst = { + audienceMismatch: { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }, + missingUnit: { unitType: "device_id" }, + }; + + it.each(Object.keys(notInFirst))( + "exposes only the later winner when the lower-id candidate is not entered (%s)", + (reason) => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], {}, notInFirst[reason]), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(1); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_2", variant: 0 })]); + } + ); + + it("exposes only the winner whose variant lacks the key, not the later candidate", () => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], {}), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_1", variant: 0 })]); + }); + + it("returns the default and exposes nothing when no candidate is entered", () => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [ + shared(1, [1, 0], {}, notInFirst.audienceMismatch), + shared(2, [1, 0], { shared: "SECOND" }, notInFirst.missingUnit), + ], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + expect(exposures(eventLogger)).toEqual([]); + }); + + it.each(["override", "rule"])("a lower-id %s winner beats a later assigned candidate", (mode) => { + const eventLogger = jest.fn(); + const assignmentRules = JSON.stringify({ + rules: [{ name: "treat", type: "assign", conditions: { value: true }, environments: [], variant: 1 }], + }); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [ + shared( + 1, + [1, 0], + {}, + { ...notInFirst.audienceMismatch, ...(mode === "rule" ? { assignmentRules } : {}) } + ), + shared(2, [1, 0], { shared: "SECOND" }), + ], + }); + if (mode === "override") context.override("shared_1", 1); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("value_1"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("value_1"); + expect(exposures(eventLogger)).toEqual([ + expect.objectContaining({ + name: "shared_1", + variant: 1, + overridden: mode === "override", + ruleOverride: mode === "rule", + }), + ]); + }); + + it("fires the winner's applicable holdouts before its own exposure, like Java", () => { + const eventLogger = jest.fn(); + const holdout = { + ...shared(11, [0, 1], {}), + name: "holdout_11", + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + }; + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], { shared: "FIRST" }, { holdoutIds: [11] })], + holdouts: [holdout], + }); + expect(context.variableValue("shared", "SENTINEL")).toBe("FIRST"); + expect(exposures(eventLogger).map((e) => e.name)).toEqual(["holdout_11", "shared_1"]); + }); + + it.each(["override", "custom", "fullOn"])("exposes an out-of-range %s winner like Java", (mode) => { + const eventLogger = jest.fn(); + // Control defines the key, so serving variant 0 instead of the default would be caught. + const first = shared(1, [1, 0], { shared: "CONTROL" }, mode === "fullOn" ? { fullOnVariant: 7 } : {}); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [first, shared(2, [1, 0], { shared: "SECOND" })], + }); + if (mode === "override") context.override("shared_1", 7); + if (mode === "custom") context.customAssignment("shared_1", 7); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_1", variant: 7 })]); + }); + }); + describe("variableValue()", () => { it("should not return variable values when unassigned", (done) => { const context = new Context(sdk, contextOptions, contextParams, audienceStrictContextResponse); @@ -6645,46 +8030,14 @@ describe("Context", () => { }); }); - it("should queue exposure with audienceMatch false and control variant on audience mismatch in strict mode", (done) => { + // The unit is not in a strict-mismatched experiment, so a variable read must not expose it; + // treatment() still records the audience mismatch (see the treatment() tests). + it("should not queue an exposure on audience mismatch in strict mode", () => { const context = new Context(sdk, contextOptions, contextParams, audienceStrictContextResponse); expect(context.variableValue("banner.size", "small")).toEqual("small"); - expect(context.pending()).toEqual(1); - - publisher.publish.mockReturnValue(Promise.resolve()); - - context.publish().then(() => { - expect(publisher.publish).toHaveBeenCalledWith( - { - publishedAt: 1611141535729, - units: publishUnits, - hashed: true, - sdkVersion: SDK_VERSION, - exposures: [ - { - id: 1, - assigned: false, - eligible: true, - exposedAt: 1611141535729, - name: "exp_test_ab", - overridden: false, - unit: "session_id", - variant: 0, - fullOn: false, - custom: false, - audienceMismatch: true, - ruleOverride: false, - }, - ], - }, - sdk, - context, - undefined - ); - - done(); - }); + expect(context.pending()).toEqual(0); }); it("should throw after finalized() call", (done) => { diff --git a/src/__tests__/fixtures/switchback/attribute-path-cases.json b/src/__tests__/fixtures/switchback/attribute-path-cases.json new file mode 100644 index 0000000..7b1d3fe --- /dev/null +++ b/src/__tests__/fixtures/switchback/attribute-path-cases.json @@ -0,0 +1,16 @@ +{ + "description": "Cluster attribute paths read by both the Collector (SwitchbackAttributePath) and analysis (ClickHouseSwitchbackExpr). An unquoted segment is an array index exactly when Guava Ints.tryParse parses it (no '+', ASCII digits only). supported: accepted by isSupported and by requireSupportedAttributePath; a negative index is unsupported because ClickHouse throws ZERO_ARRAY_OR_TUPLE_INDEX on the [0] subscript pathToArgs renders for it. value: what the path resolves to in attributes; null means missing (no cluster key).", + "attributes": { + "items": [{ "city": "Lisbon" }, { "city": "Faro" }], + "geo": { "city": "Porto", "-1": "minus-one-key", "+1": "plus-one-key" } + }, + "cases": [ + { "path": "items/0/city", "supported": true, "value": "Lisbon" }, + { "path": "items/+0/city", "supported": true, "value": null }, + { "path": "items/-1/city", "supported": false, "value": null }, + { "path": "geo/-1", "supported": false, "value": null }, + { "path": "geo/+1", "supported": true, "value": "plus-one-key" }, + { "path": "items/\u0660/city", "supported": true, "value": null }, + { "path": "geo/city", "supported": true, "value": "Porto" } + ] +} diff --git a/src/__tests__/fixtures/switchback/golden-vectors.json b/src/__tests__/fixtures/switchback/golden-vectors.json new file mode 100644 index 0000000..b314abe --- /dev/null +++ b/src/__tests__/fixtures/switchback/golden-vectors.json @@ -0,0 +1,1392 @@ +{ + "assignSwitchback": [ + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2} + ], + "fisherYatesPermutation": [ + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [0, 3, 7, 5, 8, 2, 6, 4, 1, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [6, 0, 3, 8, 9, 7, 2, 4, 5, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [3, 0, 4, 8, 1, 6, 9, 2, 7, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [0, 2, 7, 9, 1, 6, 4, 5, 3, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [6, 9, 8, 3, 4, 7, 2, 5, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [1, 7, 8, 3, 9, 5, 0, 4, 6, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [8, 9, 3, 6, 4, 1, 5, 0, 2, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [6, 4, 3, 1, 0, 7, 8, 9, 5, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [9, 4, 3, 5, 8, 0, 2, 6, 7, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [3, 8, 4, 0, 1, 7, 5, 6, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [4, 1, 5, 3, 6, 7, 0, 9, 2, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [7, 0, 1, 5, 2, 9, 8, 6, 4, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [9, 1, 7, 3, 4, 5, 2, 6, 8, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [0, 5, 7, 2, 6, 1, 9, 4, 8, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [2, 4, 0, 7, 5, 1, 3, 8, 9, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [6, 2, 5, 3, 4, 1, 7, 8, 9, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [3, 7, 2, 9, 5, 8, 0, 1, 4, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [0, 8, 1, 6, 3, 4, 5, 9, 7, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [1, 3, 2, 0, 7, 6, 8, 4, 9, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [5, 7, 0, 6, 1, 4, 3, 8, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [6, 5, 2, 0, 1, 3, 4, 9, 8, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [0, 6, 9, 1, 4, 2, 3, 8, 7, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [8, 1, 3, 6, 5, 0, 4, 9, 7, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [6, 8, 3, 5, 7, 4, 2, 0, 1, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [1, 5, 7, 0, 9, 4, 2, 3, 6, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 4, 9, 8, 0, 3, 5, 1, 2, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 0, 5, 8, 9, 3, 7, 6, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 5, 9, 1, 0, 8, 2, 4, 7, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 7, 2, 5, 8, 4, 1, 0, 3, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 5, 6, 3, 1, 7, 8, 4, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [2, 5, 4, 8, 0, 9, 7, 6, 3, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 8, 6, 3, 1, 7, 2, 0, 4, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 6, 5, 1, 2, 9, 8, 0, 4, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 2, 1, 7, 3, 8, 0, 4, 5, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 1, 2, 5, 7, 9, 0, 6, 4, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 3, 9, 0, 7, 1, 6, 5, 4, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 9, 3, 7, 4, 8, 0, 5, 2, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 4, 8, 9, 2, 3, 7, 5, 6, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 0, 7, 3, 4, 6, 5, 2, 8, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 4, 3, 7, 1, 9, 8, 2, 0, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [3, 9, 6, 8, 4, 7, 2, 5, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [3, 1, 7, 8, 9, 0, 2, 4, 5, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 6, 8, 3, 2, 5, 4, 1, 9, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [8, 3, 7, 6, 2, 9, 5, 4, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 9, 2, 7, 1, 6, 0, 8, 3, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 9, 3, 5, 8, 6, 7, 2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 9, 2, 7, 1, 3, 6, 8, 4, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 5, 1, 0, 6, 7, 2, 4, 8, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [8, 1, 6, 3, 5, 7, 0, 4, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 5, 6, 3, 2, 7, 4, 9, 1, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 9, 5, 3, 4, 6, 8, 2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 7, 5, 3, 6, 2, 4, 9, 1, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 5, 3, 7, 9, 1, 4, 0, 8, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 1, 2, 9, 5, 0, 8, 3, 7, 4]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 5, 6, 9, 4, 8, 2, 0, 1, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 7, 8, 6, 3, 2, 0, 4, 1, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [4, 6, 2, 7, 5, 8, 9, 0, 1, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [1, 2, 5, 9, 8, 6, 0, 3, 4, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [8, 4, 6, 3, 1, 2, 0, 5, 9, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [5, 2, 3, 0, 4, 6, 7, 1, 9, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [9, 7, 8, 2, 1, 6, 0, 3, 4, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [8, 6, 9, 3, 4, 2, 0, 1, 7, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [0, 9, 5, 4, 1, 7, 8, 6, 2, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [5, 8, 0, 2, 9, 7, 6, 3, 4, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [4, 2, 5, 9, 0, 7, 8, 1, 3, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [1, 7, 9, 2, 6, 0, 4, 5, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [2, 8, 7, 5, 6, 9, 3, 4, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [2, 3, 4, 9, 6, 7, 8, 5, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [2, 3, 8, 5, 9, 1, 7, 6, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [4, 6, 2, 3, 0, 5, 9, 1, 8, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [8, 6, 1, 2, 5, 9, 4, 0, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [7, 5, 0, 9, 1, 2, 6, 4, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [9, 2, 3, 8, 0, 6, 5, 1, 7, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [0, 9, 7, 3, 5, 6, 2, 4, 1, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [4, 0, 3, 8, 1, 6, 9, 2, 7, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [5, 9, 3, 0, 4, 8, 6, 7, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [7, 8, 0, 9, 6, 2, 5, 4, 3, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [1, 3, 5, 8, 6, 4, 0, 9, 7, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [3, 1, 0, 8, 2, 7, 6, 4, 5, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [0, 9, 6, 5, 2, 1, 7, 3, 8, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 6, 9, 7, 2, 8, 3, 4, 5, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [1, 5, 2, 9, 3, 8, 6, 7, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 7, 3, 1, 2, 9, 6, 4, 5, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [3, 0, 6, 1, 9, 2, 5, 8, 7, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 5, 1, 4, 3, 7, 6, 0, 2, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [5, 6, 9, 7, 8, 1, 0, 4, 2, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 8, 2, 4, 6, 3, 5, 1, 9, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 3, 8, 6, 0, 2, 5, 9, 7, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [4, 1, 2, 7, 0, 6, 9, 8, 3, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [4, 5, 3, 9, 1, 7, 6, 0, 8, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [7, 8, 6, 9, 0, 3, 5, 4, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 8, 2, 5, 7, 4, 9, 1, 3, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 5, 7, 8, 0, 2, 3, 1, 9, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 6, 4, 5, 0, 7, 9, 8, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 6, 3, 4, 7, 9, 5, 1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [0, 1, 8, 9, 2, 6, 4, 5, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 6, 4, 2, 1, 9, 3, 7, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 2, 3, 8, 1, 5, 0, 9, 7, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 3, 2, 1, 5, 9, 8, 0, 4, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 2, 5, 7, 9, 3, 8, 1, 0, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 4, 1, 8, 9, 2, 7, 0, 6, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [2, 9, 6, 4, 8, 0, 1, 5, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 5, 8, 2, 7, 3, 1, 6, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 9, 6, 0, 2, 5, 1, 8, 3, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 0, 5, 9, 1, 7, 8, 3, 4, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [3, 7, 9, 8, 4, 2, 1, 6, 5, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 6, 0, 2, 5, 9, 1, 3, 4, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [9, 0, 6, 4, 3, 7, 5, 2, 8, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 1, 9, 4, 8, 5, 3, 2, 0, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 9, 2, 1, 0, 4, 7, 6, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 3, 7, 6, 4, 5, 2, 8, 1, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [8, 0, 5, 9, 7, 4, 6, 3, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [9, 0, 1, 7, 3, 4, 5, 8, 2, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [4, 9, 7, 6, 1, 5, 8, 2, 0, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [4, 1, 5, 8, 9, 6, 2, 3, 0, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [5, 0, 1, 6, 7, 3, 9, 8, 2, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [5, 2, 9, 4, 1, 0, 8, 6, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [7, 5, 8, 3, 0, 9, 2, 6, 1, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [0, 5, 7, 9, 3, 2, 4, 1, 8, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [9, 5, 6, 3, 1, 2, 8, 7, 4, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [9, 7, 4, 8, 1, 0, 5, 3, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [9, 3, 7, 1, 8, 5, 0, 4, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [9, 5, 1, 8, 0, 3, 4, 6, 7, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [4, 9, 3, 1, 6, 8, 7, 2, 5, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [1, 0, 6, 9, 8, 5, 2, 7, 3, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [0, 7, 8, 3, 1, 5, 4, 9, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [1, 9, 5, 4, 8, 2, 0, 7, 6, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [3, 4, 2, 9, 0, 5, 1, 7, 6, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [6, 1, 9, 7, 5, 8, 3, 4, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [2, 8, 3, 0, 1, 7, 9, 6, 4, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [5, 1, 3, 2, 0, 6, 9, 8, 7, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [2, 7, 6, 9, 5, 0, 1, 8, 3, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [8, 5, 4, 3, 2, 1, 0, 7, 9, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [4, 6, 5, 9, 0, 2, 7, 3, 8, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [1, 9, 4, 0, 6, 8, 7, 3, 2, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [8, 1, 4, 7, 0, 9, 3, 2, 6, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 4, 5, 2, 3, 0, 9, 7, 6, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 0, 4, 2, 6, 7, 9, 1, 3, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [2, 8, 7, 6, 9, 0, 5, 4, 3, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [7, 3, 4, 8, 5, 6, 9, 1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [5, 6, 0, 1, 2, 8, 4, 3, 7, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 6, 3, 4, 8, 2, 1, 7, 0, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 2, 0, 5, 1, 3, 8, 9, 6, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 4, 1, 6, 3, 5, 9, 2, 8, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [9, 0, 2, 7, 5, 4, 3, 1, 8, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 1, 2, 7, 5, 3, 0, 9, 4, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [7, 9, 2, 8, 5, 6, 0, 4, 3, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [5, 2, 8, 4, 0, 9, 1, 7, 6, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 0, 7, 3, 5, 6, 4, 8, 9, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 0, 7, 4, 1, 6, 5, 2, 8, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [9, 1, 3, 5, 6, 4, 7, 0, 8, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 2, 0, 7, 8, 1, 3, 4, 5, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 0, 8, 2, 7, 5, 3, 6, 4, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 1, 8, 2, 3, 9, 6, 7, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 0, 8, 2, 9, 4, 1, 6, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 4, 8, 6, 1, 9, 7, 2, 0, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 1, 3, 7, 6, 4, 2, 9, 8, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 2, 9, 6, 1, 4, 8, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 8, 5, 1, 3, 0, 6, 4, 7, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [8, 3, 7, 2, 0, 1, 4, 5, 9, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 6, 8, 1, 7, 9, 4, 2, 3, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [4, 8, 0, 6, 9, 7, 5, 2, 1, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 0, 8, 6, 3, 7, 9, 5, 1, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 2, 3, 5, 7, 1, 9, 8, 0, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 6, 7, 4, 2, 1, 8, 3, 0, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [4, 9, 1, 7, 2, 5, 0, 6, 3, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [3, 4, 1, 2, 8, 0, 5, 9, 6, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 5, 4, 6, 7, 9, 1, 0, 3, 8]} + ] +} diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js new file mode 100644 index 0000000..a4497cc --- /dev/null +++ b/src/__tests__/switchback.test.js @@ -0,0 +1,600 @@ +import { assignSwitchback, parseInt64, switchbackPermutation } from "../switchback-long"; +import { + assignSwitchbackPeriod, + parseSwitchbackPath, + resolveSwitchbackPath, + resolveSwitchbackServing, + sameSwitchbackIdentity, + switchbackClusterKey, + switchbackPeriodIndex, + switchbackSources, + tryParseInt, + SWITCHBACK_ABSENT, + SWITCHBACK_ELIGIBLE, + SWITCHBACK_INELIGIBLE, +} from "../switchback"; +import { hashUnit } from "../utils"; + +// Fixture copied byte-for-byte from absmartly/abs 9bd2b5ca35 +// lib/utils/src/test/resources/switchback/golden-vectors.json (git blob b314abeb9e97). +import goldenVectors from "./fixtures/switchback/golden-vectors.json"; +// Fixture copied byte-for-byte from absmartly/abs 9bd2b5ca35 +// collector/src/test/resources/switchback/attribute-path-cases.json (git blob 7b1d3fed5985). +import pathCases from "./fixtures/switchback/attribute-path-cases.json"; + +const LONG_MIN = "-9223372036854775808"; +const LONG_MAX = "9223372036854775807"; + +// The platform hashes a numeric cluster unit as Long.toString(n); strings pass through. +function clusterUnit(value) { + if (typeof value === "number") { + expect(Number.isSafeInteger(value)).toBe(true); + return String(value); + } + expect(typeof value).toBe("string"); + return value; +} + +// 64-bit fields are decimal strings; a numeric one would mean the fixture regressed to a lossy encoding. +function exactLong(value) { + expect(typeof value).toBe("string"); + return value; +} + +describe("switchback assigner", () => { + it("matches every assignSwitchback golden vector", () => { + const cases = goldenVectors.assignSwitchback; + expect(cases.length).toEqual(882); + + const armCounts = new Set(); + let boundaryCases = 0; + for (const c of cases) { + const periodIndex = exactLong(c.periodIndex); + const seed = exactLong(c.seed); + armCounts.add(c.armCount); + if ([LONG_MIN, LONG_MAX].includes(periodIndex) || [LONG_MIN, LONG_MAX].includes(seed)) ++boundaryCases; + + expect([c, assignSwitchback(clusterUnit(c.clusterUnit), periodIndex, seed, c.armCount)]).toEqual([ + c, + c.expectedVariant, + ]); + } + expect([...armCounts].sort((a, b) => a - b)).toEqual([2, 3, 10]); + expect(boundaryCases).toBeGreaterThan(0); + }); + + it("matches every fisherYatesPermutation golden vector", () => { + const cases = goldenVectors.fisherYatesPermutation; + expect(cases.length).toEqual(504); + + for (const c of cases) { + const actual = switchbackPermutation( + clusterUnit(c.clusterUnit), + exactLong(c.cycleIndex), + exactLong(c.seed), + c.armCount + ); + expect([c, actual]).toEqual([c, c.expectedPermutation]); + } + }); + + it("covers every arm exactly once per cycle", () => { + for (const armCount of [2, 3, 10]) { + for (let cycle = -3; cycle < 20; ++cycle) { + const seen = new Set(); + for (let slot = 0; slot < armCount; ++slot) { + seen.add(assignSwitchback("store_42", String(cycle * armCount + slot), "20015998343868", armCount)); + } + expect(seen.size).toEqual(armCount); + } + } + }); + + it("rejects fewer than two arms and non-integral arm counts", () => { + for (const armCount of [1, 0, -1, 2.5, NaN, "3"]) { + expect(() => assignSwitchback("u", "0", "0", armCount)).toThrow("armCount must be an integer >= 2"); + expect(() => switchbackPermutation("u", "0", "0", armCount)).toThrow("armCount must be an integer >= 2"); + expect(() => assignSwitchbackPeriod("u", 0, 0, 0, armCount)).toThrow("armCount must be an integer >= 2"); + } + }); + + it("parses signed 64-bit decimal strings exactly and rejects everything else", () => { + for (const bad of [ + "", + "-", + "+", + "1.0", + "1e3", + " 1", + "0x10", + "9223372036854775808", + "-9223372036854775809", + "١", + ]) { + expect([bad, parseInt64(bad)]).toEqual([bad, null]); + expect(() => assignSwitchback("u", bad, "0", 2)).toThrow( + "periodIndex must be a signed 64-bit decimal string" + ); + expect(() => assignSwitchback("u", "0", bad, 2)).toThrow("seed must be a signed 64-bit decimal string"); + expect(() => switchbackPermutation("u", bad, "0", 2)).toThrow( + "cycleIndex must be a signed 64-bit decimal string" + ); + } + expect(() => assignSwitchback("u", 5, "0", 2)).toThrow("periodIndex must be a signed 64-bit decimal string"); + + // Leading zeros, '+' and "-0" read as Java's Long.parseLong reads them. + for (const [alias, canonical] of [ + ["007", "7"], + ["+7", "7"], + ["-0", "0"], + ["-0009223372036854775808", LONG_MIN], + ]) { + for (const armCount of [2, 3, 10]) { + expect(assignSwitchback("market_1", alias, alias, armCount)).toEqual( + assignSwitchback("market_1", canonical, canonical, armCount) + ); + } + } + }); + + // periodIndex = floorDiv(p, arms) and floorMod(p, arms) on the 64-bit value, never a double: a + // period one below a cycle boundary differs from the boundary only past 2^53. + it("keeps 64-bit periods and seeds exact past 2^53", () => { + // Golden vector: replacing this seed with 0 draws 0, not 2. + expect(assignSwitchback("market_1", LONG_MAX, LONG_MAX, 3)).toEqual(2); + expect(assignSwitchback("market_1", LONG_MAX, "0", 3)).toEqual(0); + const max = goldenVectors.assignSwitchback.filter((c) => c.periodIndex === LONG_MAX); + expect(max.length).toBeGreaterThan(0); + let differs = 0; + for (const c of max) { + // 2^63 - 1 and 2^63 - 2 are the same double. + differs += + assignSwitchback(clusterUnit(c.clusterUnit), "9223372036854775806", c.seed, c.armCount) !== + c.expectedVariant; + } + expect(differs).toBeGreaterThan(0); + }); + + it("draws a context period like the 64-bit function", () => { + for (const [seedHi, seedLo, seed] of [ + [0, 0, "0"], + [0, 1, "1"], + [-1, -1, "-1"], + [-5, -7, "-17179869191"], + [0x7fffffff, -1, LONG_MAX], + [-0x80000000, 0, LONG_MIN], + [0x1234, 0x5678abcd, "20015998348237"], + ]) { + for (const period of [0, 1, 2, 9, 10, 23, 99, 2 ** 32 - 1, 2 ** 32, 2 ** 40 + 3, Number.MAX_SAFE_INTEGER]) { + for (const armCount of [2, 3, 10]) { + expect(assignSwitchbackPeriod("store-42", period, seedHi, seedLo, armCount)).toEqual( + assignSwitchback("store-42", String(period), seed, armCount) + ); + } + } + } + }); + + // The key is utf8(clusterUnit + U+001F + cycleIndex), as the platform's String.getBytes(UTF_8), + // which encodes a lone surrogate as '?'. Values computed with an independent Python reference. + it("encodes the cluster key as the platform does", () => { + // The decomposed "cafe\u0301" keeps its combining mark: it is not "cafe". + expect(switchbackPermutation("cafe\u0301", "0", "0", 10)).toEqual([7, 2, 9, 3, 5, 4, 6, 1, 8, 0]); + expect(switchbackPermutation("cafe", "0", "0", 10)).toEqual([7, 3, 0, 4, 6, 9, 1, 8, 5, 2]); + expect([ + switchbackPermutation("x\ud800y", "0", "0", 10), + switchbackPermutation("x?y", "0", "0", 10), + switchbackPermutation("😀", "0", "0", 10), + ]).toEqual([ + [6, 7, 4, 8, 5, 3, 1, 0, 2, 9], + [6, 7, 4, 8, 5, 3, 1, 0, 2, 9], + [5, 6, 1, 3, 0, 8, 4, 9, 2, 7], + ]); + }); +}); + +describe("switchback attribute paths", () => { + it("matches every platform path case", () => { + const cases = pathCases.cases; + expect(cases.length).toEqual(7); + for (const c of cases) { + const path = parseSwitchbackPath(c.path); + if (!c.supported) { + expect([c, path]).toEqual([c, null]); + continue; + } + expect(path).not.toBeNull(); + expect([c, resolveSwitchbackPath(path, pathCases.attributes[path.keys[0]])]).toEqual([c, c.value]); + } + }); + + it("reads quoted segments as literal keys", () => { + const geo = { 0: "zero", "a/b": "slash" }; + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/'0'"), geo)).toEqual("zero"); + expect(resolveSwitchbackPath(parseSwitchbackPath('geo/"a/b"'), geo)).toEqual("slash"); + }); + + it("rejects malformed paths", () => { + for (const path of [ + "geo/'0", + "'geo", + '"geo/city', + 'geo/"', + "geo.city", + "geo/a.b", + "a./b", + ".", + "items/0.5/city", + "'geo.city'", + '"geo.city"', + "geo/'a.b'", + ]) { + expect([path, parseSwitchbackPath(path)]).toEqual([path, null]); + } + }); + + it("collapses separators", () => { + const geo = { city: "Porto" }; + expect(resolveSwitchbackPath(parseSwitchbackPath("/geo//city/"), geo)).toEqual("Porto"); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo"), geo)).toEqual(geo); + expect(parseSwitchbackPath("/geo//city/")).toEqual({ keys: ["geo", "city"], indices: [null, null] }); + }); + + it("rejects unsupported paths", () => { + for (const path of [ + null, + undefined, + 7, + {}, + "", + "/", + "//", + "0/city", + "items/0", + "items/0/1/city", + "items/-1/city", + "'", + ]) { + expect([path, parseSwitchbackPath(path)]).toEqual([path, null]); + } + }); + + it("reads arrays only through index segments and objects only through key segments", () => { + const items = [{ city: "Lisbon" }]; + const geo = { 0: { city: "zero" } }; + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/0/city"), geo)).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("items/1/city"), items)).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("name/x"), "scalar")).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("items/city"), items)).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("items/-0/city"), items)).toEqual("Lisbon"); + // Only own keys: an inherited property is not a value. + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/constructor"), {})).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("items/length"), items)).toBeNull(); + }); + + // The Collector reads the attribute as published, through its JSON encoding. + it("reads values through their JSON encoding", () => { + const cyclic = { city: "Porto" }; + cyclic.self = cyclic; + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/city"), cyclic)).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/city"), { city: 10n })).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/when"), { when: new Date(0) })).toEqual( + "1970-01-01T00:00:00.000Z" + ); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/city"), { city: undefined })).toBeNull(); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/city"), { toJSON: () => ({ city: "Faro" }) })).toEqual( + "Faro" + ); + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/0/x"), [{ x: undefined }])).toBeNull(); + // A value reached twice through siblings is not a cycle. + const shared = { a: "b" }; + expect(resolveSwitchbackPath(parseSwitchbackPath("geo/city"), { city: "Porto", x: shared, y: shared })).toEqual( + "Porto" + ); + }); + + it("parses index segments as Guava Ints.tryParse", () => { + expect(tryParseInt("0")).toEqual(0); + expect(Object.is(tryParseInt("-0"), 0)).toBe(true); + expect(tryParseInt("007")).toEqual(7); + expect(tryParseInt("2147483647")).toEqual(2147483647); + expect(tryParseInt("-2147483648")).toEqual(-2147483648); + expect(tryParseInt("00000000002147483647")).toEqual(2147483647); + for (const s of ["", "-", "+1", "1a", " 1", "2147483648", "-2147483649", "99999999999999999999", "٠", "1.0"]) { + expect([s, tryParseInt(s)]).toEqual([s, null]); + } + }); +}); + +describe("switchback cluster values", () => { + it("keys non-empty strings as-is and whole numbers by their decimal text", () => { + expect(switchbackClusterKey("s-1")).toEqual("s-1"); + expect(switchbackClusterKey(" ")).toEqual(" "); + expect(switchbackClusterKey(17)).toEqual("17"); + expect(switchbackClusterKey(-17)).toEqual("-17"); + expect(switchbackClusterKey(0)).toEqual("0"); + expect(switchbackClusterKey(-0)).toEqual("0"); + expect(switchbackClusterKey(4000000002)).toEqual("4000000002"); + expect(switchbackClusterKey(2 ** 53 + 2)).toEqual("9007199254740994"); + expect(switchbackClusterKey(1e20)).toEqual("100000000000000000000"); + // JS cannot tell 3.0 from 3: both are the integer 3 (documented limitation). + expect(switchbackClusterKey(3.0)).toEqual("3"); + }); + + it("gives no key for anything else", () => { + for (const value of [ + 1.5, + -0.5, + 1e21, + -1e21, + NaN, + Infinity, + -Infinity, + true, + false, + {}, + { a: 1 }, + ["a"], + [], + "", + null, + undefined, + 10n, + ]) { + expect([value, switchbackClusterKey(value)]).toEqual([value, null]); + } + }); +}); + +describe("switchback serving", () => { + const paths = (...p) => p.map((x) => parseSwitchbackPath(x)); + const reader = (attrs) => (path) => resolveSwitchbackPath(path, attrs[path.keys[0]]); + + // The declared source order decides, not the order of the units. + it("serves under the first declared source whatever the unit order", () => { + const units = { user_id: "u1", session_id: "x1" }; + const attrs = { session_store: "s-1", user_store: "s-1" }; + expect( + resolveSwitchbackServing( + ["session_id", "user_id"], + paths("session_store", "user_store"), + null, + units, + reader(attrs) + ) + ).toEqual({ status: SWITCHBACK_ELIGIBLE, unitType: "session_id", clusterKey: "s-1" }); + expect( + resolveSwitchbackServing( + ["user_id", "session_id"], + paths("user_store", "session_store"), + null, + units, + reader(attrs) + ) + ).toEqual({ status: SWITCHBACK_ELIGIBLE, unitType: "user_id", clusterKey: "s-1" }); + }); + + it("is absent without a linked unit and ineligible without a value, on disagreement or outside the allow-list", () => { + const types = ["session_id", "user_id"]; + const p = paths("session_store", "user_store"); + expect(resolveSwitchbackServing(types, p, null, { device_id: "d" }, reader({ session_store: "a" }))).toEqual({ + status: SWITCHBACK_ABSENT, + unitType: null, + clusterKey: null, + }); + const both = { session_id: "x", user_id: "u" }; + expect(resolveSwitchbackServing(types, p, null, both, reader({}))).toEqual({ + status: SWITCHBACK_INELIGIBLE, + unitType: "session_id", + clusterKey: null, + }); + expect( + resolveSwitchbackServing(types, p, null, both, reader({ session_store: "a", user_store: "b" })).status + ).toEqual(SWITCHBACK_INELIGIBLE); + expect(resolveSwitchbackServing(types, p, ["b"], both, reader({ session_store: "a" })).status).toEqual( + SWITCHBACK_INELIGIBLE + ); + expect(resolveSwitchbackServing(types, p, ["a"], both, reader({ session_store: "a" })).status).toEqual( + SWITCHBACK_ELIGIBLE + ); + expect(resolveSwitchbackServing(types, p, [], both, reader({ session_store: "a" })).status).toEqual( + SWITCHBACK_ELIGIBLE + ); + // Entries compare as text: a numeric entry admits its decimal key. + expect(resolveSwitchbackServing(types, p, [true], both, reader({ session_store: "true" })).status).toEqual( + SWITCHBACK_ELIGIBLE + ); + expect(resolveSwitchbackServing(types, p, [17], both, reader({ session_store: "17" })).status).toEqual( + SWITCHBACK_ELIGIBLE + ); + expect(resolveSwitchbackServing(types, p, [null], both, reader({ session_store: "null" })).status).toEqual( + SWITCHBACK_INELIGIBLE + ); + for (const entry of [{}, ["a"], null]) { + expect( + resolveSwitchbackServing(types, p, [entry], both, reader({ session_store: String(entry) })).status + ).toEqual(SWITCHBACK_INELIGIBLE); + } + // A malformed allow-list admits nothing rather than everything. + expect(resolveSwitchbackServing(types, p, "a", both, reader({ session_store: "a" })).status).toEqual( + SWITCHBACK_INELIGIBLE + ); + // A unit without a value is skipped: the next one serves. + expect(resolveSwitchbackServing(types, p, null, both, reader({ user_store: "b" }))).toEqual({ + status: SWITCHBACK_ELIGIBLE, + unitType: "user_id", + clusterKey: "b", + }); + // The number 17 and the string "17" agree. + expect( + resolveSwitchbackServing(types, p, null, both, reader({ session_store: 17, user_store: "17" })).status + ).toEqual(SWITCHBACK_ELIGIBLE); + }); + + it("reads the cluster sources in declared order and rejects unreadable maps", () => { + expect(switchbackSources({ user_id: "a", device_id: "b/c", store_id: "'d'" })).toEqual({ + types: ["user_id", "device_id", "store_id"], + paths: paths("a", "b/c", "'d'"), + }); + for (const clusters of [ + null, + undefined, + {}, + [], + "x", + 3, + { a: "'x" }, + { a: "x.y" }, + { a: 7 }, + { a: null }, + { a: "x", 2: "y" }, + ]) { + expect([clusters, switchbackSources(clusters)]).toEqual([clusters, null]); + } + // A lone array-index unit type has no order to lose. + expect(switchbackSources({ 7: "x" })).toEqual({ types: ["7"], paths: paths("x") }); + expect(switchbackSources({ "07": "x", a: "y" })).toEqual({ types: ["07", "a"], paths: paths("x", "y") }); + // 2^32 - 1 is not an array index, so JS keeps it in its declared position. + expect(switchbackSources({ store: "a", 4294967295: "b" })).toEqual({ + types: ["store", "4294967295"], + paths: paths("a", "b"), + }); + }); +}); + +describe("switchback schedule", () => { + const HOUR = 3600000; + const ANCHOR = 1767225600000; + const schedule = (startAt, periodMs, arms = 2) => ({ + switchbackStartAt: startAt, + switchbackPeriodMs: periodMs, + split: new Array(arms).fill(1 / arms), + }); + + it("indexes periods from the anchor and is null before it", () => { + expect(switchbackPeriodIndex(schedule(ANCHOR, HOUR), ANCHOR - 1)).toBeNull(); + expect(switchbackPeriodIndex(schedule(ANCHOR, HOUR), ANCHOR)).toEqual(0); + expect(switchbackPeriodIndex(schedule(ANCHOR, HOUR), ANCHOR + HOUR - 1)).toEqual(0); + expect(switchbackPeriodIndex(schedule(ANCHOR, HOUR), ANCHOR + HOUR)).toEqual(1); + expect(switchbackPeriodIndex(schedule(0, HOUR), 0)).toEqual(0); + expect(switchbackPeriodIndex(schedule(0, 1), Number.MAX_SAFE_INTEGER)).toEqual(Number.MAX_SAFE_INTEGER); + expect(switchbackPeriodIndex(schedule(0, 3), 2 ** 53 - 2)).toEqual(Math.floor((2 ** 53 - 2) / 3)); + // 1440000000000 ms (400,000 h), the cross-SDK grid. + expect( + switchbackPeriodIndex(schedule(1704067200000, 1440000000000), 1704067200000 + 1440000000000 - 1) + ).toEqual(0); + // The double quotient's floor is the exact floor for every integer below 2^53. + for (let periodMs = 7; periodMs < 2 ** 40; periodMs = periodMs * 3 + 1) { + for (const elapsed of [periodMs * 1000 - 1, 2 ** 53 - 1 - ((2 ** 53 - 1) % periodMs) - 1]) { + const index = switchbackPeriodIndex(schedule(0, periodMs), elapsed); + expect(index * periodMs <= elapsed && elapsed < (index + 1) * periodMs).toBe(true); + } + } + }); + + it("is unservable for a bad anchor, period or arm count", () => { + const maxAnchor = 253402300800000; + for (const startAt of [ + ANCHOR + 1, + ANCHOR - 1, + ANCHOR + 30 * 60000, + -HOUR, + -1, + maxAnchor, + maxAnchor + HOUR, + 1.5, + NaN, + Infinity, + null, + undefined, + "0", + String(ANCHOR), + ]) { + expect([startAt, switchbackPeriodIndex(schedule(startAt, HOUR), ANCHOR + 10 * HOUR)]).toEqual([ + startAt, + null, + ]); + } + for (const periodMs of [0, -HOUR, 0.5, NaN, Infinity, null, undefined, "3600000"]) { + expect([periodMs, switchbackPeriodIndex(schedule(ANCHOR, periodMs), ANCHOR + 10 * HOUR)]).toEqual([ + periodMs, + null, + ]); + } + expect(switchbackPeriodIndex(schedule(ANCHOR, HOUR, 1), ANCHOR)).toBeNull(); + expect(switchbackPeriodIndex({ switchbackStartAt: ANCHOR, switchbackPeriodMs: HOUR }, ANCHOR)).toBeNull(); + expect(switchbackPeriodIndex(schedule(maxAnchor - HOUR, HOUR), maxAnchor)).toEqual(1); + }); + + it("keeps the epoch only for the same switchback identity", () => { + const base = { + id: 1, + iteration: 1, + unitType: "store_id", + split: [0.5, 0.5], + seedHi: 1, + switchbackClusters: { store_id: "a", user_id: "b" }, + switchbackClusterValues: ["x"], + switchbackStartAt: ANCHOR, + switchbackPeriodMs: HOUR, + switchbackDesignType: "balanced_block", + switchbackEstimand: "e", + switchbackBurnInDurationMs: 0, + }; + const same = (changes, readable = true) => + sameSwitchbackIdentity(base, readable, { ...base, ...changes }, readable); + expect(same({})).toBe(true); + expect( + same({ + seedHi: 2, + split: [0.1, 0.9], + switchbackEstimand: "f", + switchbackBurnInDurationMs: 5, + unitType: "x", + }) + ).toBe(true); + expect(same({ switchbackClusters: { store_id: "a", user_id: "b" }, switchbackClusterValues: ["x"] })).toBe( + true + ); + expect(same({ switchbackClusterValues: undefined }, true)).toBe(false); + for (const changes of [ + { id: 2 }, + { iteration: 2 }, + { switchbackClusters: { user_id: "b", store_id: "a" } }, + { switchbackClusters: { store_id: "a", user_id: "c" } }, + { switchbackClusters: { store_id: "a" } }, + { switchbackClusterValues: ["y"] }, + { switchbackClusterValues: null }, + { switchbackStartAt: ANCHOR + HOUR }, + { switchbackPeriodMs: 2 * HOUR }, + { switchbackDesignType: "other" }, + ]) { + expect([changes, same(changes)]).toEqual([changes, false]); + } + // On the legacy path the declared unitType is identity. + expect(same({ unitType: "x" }, false)).toBe(false); + expect(sameSwitchbackIdentity(base, true, { ...base, unitType: "x" }, false)).toBe(false); + expect(same({ switchbackClusterValues: null }, false)).toBe(false); + expect( + sameSwitchbackIdentity( + { ...base, switchbackClusterValues: null }, + true, + { ...base, switchbackClusterValues: undefined }, + true + ) + ).toBe(true); + }); +}); + +describe("switchback hashing context", () => { + it("never hashes the cluster key", () => { + // The draw over the raw key differs from a draw over its unit hash. + let differs = 0; + for (let period = 0; period < 12; ++period) { + differs += + assignSwitchbackPeriod("store-42", period, -5, -7, 3) !== + assignSwitchbackPeriod(hashUnit("store-42"), period, -5, -7, 3); + } + expect(differs).toBeGreaterThan(0); + }); +}); diff --git a/src/context.ts b/src/context.ts index 09ccce7..86dd339 100644 --- a/src/context.ts +++ b/src/context.ts @@ -7,6 +7,20 @@ import { ContextPublisher, type PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; import { type ClientRequestOptions } from "./client"; import { SDK_VERSION } from "./version"; +import { + assignSwitchbackPeriod, + legacySwitchbackServing, + resolveSwitchbackPath, + resolveSwitchbackServing, + sameSwitchbackIdentity, + switchbackPeriodIndex, + switchbackSources, + SWITCHBACK_ABSENT, + SWITCHBACK_ELIGIBLE, + SWITCHBACK_INELIGIBLE, + type SwitchbackServing, + type SwitchbackSources, +} from "./switchback"; type JSONPrimitive = string | number | boolean | null; type JSONObject = { [key: string]: JSONValue }; @@ -21,6 +35,8 @@ type CustomFieldValue = { type: CustomFieldValueType; }; +const DEFERRED_REPLAY_ROUNDS = 32; +const DEFERRED_REPLAY_CALLBACKS = 1024; export type ExperimentData = { id: number; name: string; @@ -48,6 +64,20 @@ export type ExperimentData = { audienceMismatch: boolean; customFieldValues: CustomFieldValue[] | null; holdoutIds?: number[]; + // Switchback experiments (R33). Absent on unit experiments; only `randomizationType`, + // `switchbackClusters`, `switchbackClusterValues`, `switchbackStartAt` and `switchbackPeriodMs` + // affect serving. `switchbackClusters` maps a unit type to an attribute path; its key order is + // the declared serving order. + randomizationType?: string | null; + switchbackClusters?: Record | null; + switchbackClusterValues?: string[] | null; + switchbackStartAt?: number | null; + switchbackPeriodMs?: number | null; + switchbackCarryoverDurationMs?: number | null; + switchbackBurnInDurationMs?: number | null; + switchbackBurnOutDurationMs?: number | null; + switchbackDesignType?: string | null; + switchbackEstimand?: string | null; }; type Assignment = { @@ -76,8 +106,27 @@ type Assignment = { // `split.length` at the time `variant` was resolved; a same-iteration refresh can change // the live value without invalidating the cache. holdoutArmCount?: number; + // Set only on switchback assignments: the generation they were resolved under, the serving unit + // and cluster key read for their period slot, the custom assignment read while resolving, and + // whether the resolution records no exposure (no linked unit, an ineligible cluster, no period). + switchbackGeneration?: number; + switchbackServing?: SwitchbackServing; + switchbackCustom?: number; + switchbackSilent?: boolean; }; +// The cache slots of one switchback experiment, all of one generation and kept apart from +// `_assignments` so no experiment name can collide with them: the period-less slot (before the anchor +// or with an unservable schedule) and at most SWITCHBACK_RETAINED_PERIODS period slots. +type SwitchbackEpoch = { + generation: number; + periods: number[]; + slots: Record; + periodless?: Assignment; +}; + +const SWITCHBACK_RETAINED_PERIODS = 2; + export type HoldoutData = { id: number; name: string; @@ -100,6 +149,9 @@ export type Experiment = { // Parsed `data.assignmentRules`, filled on first use; `undefined` until then. The entry is rebuilt // whenever context data is installed, so the cache never outlives the rules it was parsed from. rules?: unknown[] | null; + // Set only for a switchback experiment: its generation, carried over a refresh while its + // switchback identity is unchanged, and its cluster sources (null on the legacy path). + switchback?: { generation: number; sources: SwitchbackSources | null }; }; export type Unit = { @@ -189,9 +241,16 @@ export default class Context { private _holdoutAssignments: Record; private _overrides: Record; private _pending: number; + // While a variable read runs, user eventLogger callbacks it would trigger are held here (the + // list is created on first use) and replayed once every exposure of the read is queued. + private _deferringLogs = false; + private _replayExhausted = false; + private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; + private _switchbackGenerations: number; + private _switchbackEpochs?: Record; private _hashes?: Record; private _promise?: Promise; private _publishTimeout?: ReturnType; @@ -221,6 +280,7 @@ export default class Context { this._attrsSeq = 0; this._attrsMapCache = null; this._attrsMapCacheSeq = -1; + this._switchbackGenerations = 0; if (params.units) { this.units(params.units); @@ -365,6 +425,21 @@ export default class Context { // the assignment was resolved. Evict so `_assign()` rebuilds it; already-exposed ones are kept // since re-resolving would queue a second, conflicting exposure. private _invalidateAssignmentsPinnedWithMissingUnit(unitType: string): void { + const epochs = this._switchbackEpochs; + if (epochs !== undefined) { + for (const experimentName in epochs) { + const slots = epochs[experimentName].slots; + // Period indices stay retained, as in Java's invalidateAssignmentsPinnedWithMissingUnit. + for (const period in slots) { + if (this._isSwitchbackSlotWithoutUnit(slots[period])) delete slots[period]; + } + const periodless = epochs[experimentName].periodless; + if (periodless !== undefined && this._isSwitchbackSlotWithoutUnit(periodless)) { + delete epochs[experimentName].periodless; + } + } + } + for (const experimentName in this._assignments) { const assignment = this._assignments[experimentName]; if (assignment.unitType !== unitType || assignment.exposed) continue; @@ -379,6 +454,14 @@ export default class Context { } } + // A switchback resolved with no linked unit set is resolved again once one may be. Unless overridden + // it published nothing, so it is dropped even when exposed. + private _isSwitchbackSlotWithoutUnit(assignment: Assignment): boolean { + return ( + assignment.switchbackServing?.status === SWITCHBACK_ABSENT && (!assignment.overridden || !assignment.exposed) + ); + } + getUnits() { return { ...this._units }; } @@ -462,11 +545,14 @@ export default class Context { const variableExperiments: Record = {}; + // defineProperty keeps a key such as "__proto__" an own entry of the returned plain object. for (const [key, values] of Object.entries(this._indexVariables)) { - for (const value of values) { - if (variableExperiments[key]) variableExperiments[key].push(value.data.name); - else variableExperiments[key] = [value.data.name]; - } + Object.defineProperty(variableExperiments, key, { + value: values.map((value) => value.data.name), + enumerable: true, + writable: true, + configurable: true, + }); } return variableExperiments; @@ -514,7 +600,13 @@ export default class Context { } } - private _resolveRule(entry: Experiment, attrs: Record, isUnitPinnedMissing: boolean) { + // A split rule randomizes over `unitType`: the experiment's own, or a switchback's serving unit. + private _resolveRule( + entry: Experiment, + attrs: Record, + isUnitPinnedMissing: boolean, + unitType: string | null = entry.data.unitType + ) { const experiment = entry.data; const variantCount = experiment.variants.length; if (entry.rules === undefined) { @@ -531,7 +623,6 @@ export default class Context { } if (action.split.length !== variantCount) return null; - const unitType = experiment.unitType; const unit = unitType != null && !isUnitPinnedMissing ? this._unitHash(unitType) : null; if (unitType == null || unit === null) return { variant: experiment.fullOnVariant, isMissingUnit: true }; @@ -590,7 +681,8 @@ export default class Context { } } - private _assign(experimentName: string) { + // `now` is the clock reading a switchback resolves its period at; read here when not given. + private _assign(experimentName: string, now?: number) { const experimentMatches = (experiment: ExperimentData, assignment: Assignment) => { return ( experiment.id === assignment.id && @@ -677,6 +769,13 @@ export default class Context { const hasOverride = experimentName in this._overrides; const experiment = experimentName in this._index ? this._index[experimentName] : null; + if (this._switchbackEpochs !== undefined) { + this._dropStaleSwitchbackEpoch(experimentName, experiment); + } + if (experiment != null && experiment.switchback !== undefined) { + return this._assignSwitchback(experimentName, experiment, now ?? Date.now()); + } + if (experimentName in this._assignments) { const assignment = this._assignments[experimentName]; if (hasOverride) { @@ -864,24 +963,330 @@ export default class Context { return this._assign(experimentName); } + // Port of java-sdk's switchback branch of getAssignment (the Collector's ContextAPI, R33). The + // serving unit and cluster key decide whether the experiment applies and under which unit; for an + // eligible cluster the precedence is override, assignment rule (a split randomizes over the + // serving unit), strict audience mismatch (recorded), full-on, no period (silent control), traffic + // on the serving unit's hash (a miss is recorded), custom assignment, then the schedule draw over + // the raw cluster key. Holdouts never apply. + private _assignSwitchback(experimentName: string, experiment: Experiment, now: number): Assignment { + const switchback = experiment.switchback as { generation: number; sources: SwitchbackSources | null }; + const data = experiment.data; + const periodIndex = switchback.sources !== null ? switchbackPeriodIndex(data, now) : null; + // Own properties only: an experiment can be named like an Object member (`constructor`). + const hasOverride = Object.prototype.hasOwnProperty.call(this._overrides, experimentName); + const custom = Object.prototype.hasOwnProperty.call(this._cassignments, experimentName) + ? this._cassignments[experimentName] + : undefined; + + // `_assign` dropped the slots of any earlier generation, so a slot found here is current. + const epoch = this._switchbackEpochs?.[experimentName]; + const current = periodIndex === null ? epoch?.periodless : epoch?.slots[periodIndex]; + if (current !== undefined && this._isSwitchbackAssignmentCurrent(experiment, current, hasOverride, custom)) { + return current; + } + + const assignment: Assignment = { + id: data.id, + iteration: data.iteration, + fullOnVariant: data.fullOnVariant, + unitType: null, + variant: 0, + overridden: false, + assigned: false, + exposed: false, + eligible: true, + fullOn: false, + custom: false, + audienceMismatch: false, + ruleOverride: false, + trafficSplit: data.trafficSplit, + attrsSeq: this._attrsSeq, + switchbackGeneration: switchback.generation, + switchbackCustom: custom, + }; + + // Within one period slot the serving unit and cluster key are read once: a slot rebuilt in the + // same epoch, e.g. after an attribute change flipped the audience, keeps its cluster. + const cachedServing = current?.switchbackServing; + const serving = + cachedServing !== undefined && cachedServing.status !== SWITCHBACK_ABSENT + ? cachedServing + : this._resolveSwitchbackServing(experiment, now); + assignment.switchbackServing = serving; + assignment.unitType = + serving.unitType ?? (switchback.sources !== null ? switchback.sources.types[0] : data.unitType); + + if (hasOverride) { + assignment.overridden = true; + assignment.variant = this._overrides[experimentName]; + } else { + this._resolveSwitchbackVariant(experiment, assignment, serving, periodIndex, custom); + } + + if (assignment.variant < data.variants.length) { + assignment.variables = experiment.variables[assignment.variant]; + } + + this._retainSwitchbackSlot(experimentName, switchback.generation, periodIndex, assignment); + return assignment; + } + + private _resolveSwitchbackVariant( + experiment: Experiment, + assignment: Assignment, + serving: SwitchbackServing, + periodIndex: number | null, + custom: number | undefined + ) { + const data = experiment.data; + if (serving.status === SWITCHBACK_ABSENT) { + // No linked unit: the experiment does not apply, like an unset unit type. + assignment.eligible = false; + assignment.switchbackSilent = true; + return; + } + + assignment.assigned = true; + if (serving.status === SWITCHBACK_INELIGIBLE) { + // No rule, audience or full-on is evaluated for an ineligible cluster. + assignment.eligible = false; + assignment.switchbackSilent = true; + return; + } + + assignment.ruleKey = data.assignmentRules ? `${data.assignmentRules}:${this._environmentName}` : ""; + const rule = + data.assignmentRules && data.assignmentRules.length > 0 + ? this._resolveRule(experiment, this._getAttributesMap(), false, serving.unitType) + : null; + assignment.ruleVariant = rule?.variant ?? null; + assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; + if (rule !== null) { + // Recorded like a unit experiment's rule win: ruleOverride set, not "assigned". + assignment.assigned = false; + assignment.ruleOverride = true; + assignment.variant = rule.variant; + return; + } + + if (data.audience && data.audience.length > 0) { + const result = this._evaluateAudience(data.audience); + if (typeof result === "boolean") { + assignment.audienceMismatch = !result; + } + } + if (data.audienceStrict && assignment.audienceMismatch) { + // Recorded like a unit experiment's strict mismatch: control, not "assigned". + assignment.assigned = false; + return; + } + if (data.fullOnVariant !== 0) { + assignment.variant = data.fullOnVariant; + assignment.fullOn = true; + return; + } + if (periodIndex === null) { + // Before the anchor or with an unservable schedule there is no draw: control, no exposure. + assignment.eligible = false; + assignment.switchbackSilent = true; + return; + } + + const unitType = serving.unitType as string; + const unit = this._unitHash(unitType) as string; + const assigner = + unitType in this._assigners ? this._assigners[unitType] : (this._assigners[unitType] = new VariantAssigner(unit)); + if (assigner.assign(data.trafficSplit, data.trafficSeedHi, data.trafficSeedLo) !== 1) { + // A traffic miss on an eligible cluster is recorded, as for a unit experiment. + assignment.eligible = false; + return; + } + if (custom !== undefined) { + assignment.variant = custom; + assignment.custom = true; + return; + } + assignment.variant = assignSwitchbackPeriod( + serving.clusterKey as string, + periodIndex, + data.seedHi, + data.seedLo, + data.split.length + ); + } + + // Revalidates a cached slot of the current generation. Like the unit path, a rule or audience + // re-evaluation that keeps the outcome advances the slot's stamps in place. + private _isSwitchbackAssignmentCurrent( + experiment: Experiment, + assignment: Assignment, + hasOverride: boolean, + custom: number | undefined + ): boolean { + if (hasOverride) { + return assignment.overridden && assignment.variant === this._overrides[experiment.data.name]; + } + + const data = experiment.data; + if ( + assignment.overridden || + assignment.fullOnVariant !== data.fullOnVariant || + !arrayEqualsShallow(assignment.trafficSplit, data.trafficSplit) || + (!assignment.ruleOverride && assignment.switchbackCustom !== custom) + ) { + return false; + } + + // A slot without an eligible cluster never consulted its rules or audience. + if (assignment.switchbackServing?.status !== SWITCHBACK_ELIGIBLE) return true; + + const ruleKey = data.assignmentRules ? `${data.assignmentRules}:${this._environmentName}` : ""; + if (ruleKey === assignment.ruleKey && this._attrsSeq <= (assignment.attrsSeq ?? 0)) return true; + + const rule = + data.assignmentRules && data.assignmentRules.length > 0 + ? this._resolveRule(experiment, this._getAttributesMap(), false, assignment.unitType) + : null; + if ((rule?.variant ?? null) !== (assignment.ruleVariant ?? null)) return false; + + if (!assignment.ruleOverride && data.audience && data.audience.length > 0) { + const result = this._evaluateAudience(data.audience); + const audienceMismatch = result !== null ? !result : assignment.audienceMismatch; + if (audienceMismatch !== assignment.audienceMismatch) return false; + } + + assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; + assignment.ruleKey = ruleKey; + assignment.attrsSeq = this._attrsSeq; + return true; + } + + // The Collector's switchbackServing at `now`. A missing, empty or unreadable cluster map takes the + // legacy path: an ineligible control under a unit of the declared unitType, if one is set. + private _resolveSwitchbackServing(experiment: Experiment, now: number): SwitchbackServing { + const sources = (experiment.switchback as { sources: SwitchbackSources | null }).sources; + if (sources === null) return legacySwitchbackServing(experiment.data.unitType, this._units); + + return resolveSwitchbackServing( + sources.types, + sources.paths, + experiment.data.switchbackClusterValues, + this._units, + (path) => { + // The attribute the Collector reads at `now`: among those named by the path's first segment + // and set at or before now, the latest setAt wins, and on a tie the one set last. + let selected: Attribute | null = null; + for (const attr of this._attrs) { + if ( + attr.setAt <= now && + typeof attr.name === "string" && + attr.name.trim() === path.keys[0] && + (selected === null || attr.setAt >= selected.setAt) + ) { + selected = attr; + } + } + return selected !== null ? resolveSwitchbackPath(path, selected.value) : null; + } + ); + } + + // Drops every slot of an experiment's switchback epoch once the installed definition is gone, is not + // a switchback or carries another generation. + private _dropStaleSwitchbackEpoch(experimentName: string, experiment: Experiment | null) { + const epochs = this._switchbackEpochs as Record; + const epoch = epochs[experimentName]; + if (epoch === undefined || experiment?.switchback?.generation === epoch.generation) return; + + // A unit assignment cached before the experiment became a switchback must not outlive the stint. + delete this._assignments[experimentName]; + delete epochs[experimentName]; + } + + // Installs a slot in the experiment's epoch. At most + // SWITCHBACK_RETAINED_PERIODS period slots are kept per experiment, evicting the lowest index other + // than the one just installed. Re-entering an evicted period (a clock moved back by two or more + // periods) resolves and exposes it once more. + private _retainSwitchbackSlot( + experimentName: string, + generation: number, + periodIndex: number | null, + assignment: Assignment + ) { + // No prototype, so an experiment named like an Object member (`constructor`) has no epoch yet. + const epochs = + this._switchbackEpochs ?? (this._switchbackEpochs = Object.create(null) as Record); + const epoch = + epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [], slots: Object.create(null) }); + if (periodIndex === null) { + epoch.periodless = assignment; + return; + } + + epoch.slots[periodIndex] = assignment; + if (epoch.periods.indexOf(periodIndex) >= 0) return; + epoch.periods.push(periodIndex); + while (epoch.periods.length > SWITCHBACK_RETAINED_PERIODS) { + let evicted = -1; + for (let i = 0; i < epoch.periods.length; ++i) { + if (epoch.periods[i] !== periodIndex && (evicted < 0 || epoch.periods[i] < epoch.periods[evicted])) { + evicted = i; + } + } + delete epoch.slots[epoch.periods[evicted]]; + epoch.periods.splice(evicted, 1); + } + } + private _treatment(experimentName: string) { - const assignment = this._assign(experimentName); + const now = this._switchbackClock(experimentName, undefined); + const assignment = this._assign(experimentName, now); if (!assignment.exposed) { assignment.exposed = true; - this._triggerExposures(experimentName, assignment); + // Queue the experiment's and its holdouts' exposures before any callback runs, so an + // eventLogger that finalizes on the first one still sends the holdout's. + if (this._deferringLogs) { + this._triggerExposures(experimentName, assignment, now); + } else { + this._deferringLogs = true; + try { + this._triggerExposures(experimentName, assignment, now); + } finally { + this._endDeferral(); + } + } } return assignment; } - private _triggerExposures(experimentName: string, assignment: Assignment): void { + // One clock reading per call, taken only when the experiment is a switchback (or `now` is + // already set): unit experiments keep reading the clock when their exposure is queued. + private _switchbackClock(experimentName: string, now: number | undefined): number | undefined { + if (now !== undefined || this._switchbackGenerations === 0) return now; + const experiment = experimentName in this._index ? this._index[experimentName] : null; + return experiment != null && experiment.switchback !== undefined ? Date.now() : undefined; + } + + // A switchback exposure is stamped with `now`, the reading that selected its period, since analysis + // derives the period from `exposedAt`; a later reading could fall in the next period. Holdouts + // never apply to a switchback, so its assignment has none to trigger. + private _triggerExposures(experimentName: string, assignment: Assignment, now?: number, withHoldouts = true): void { + if (assignment.switchbackGeneration !== undefined) { + if (!assignment.switchbackSilent) { + this._queueExposure(experimentName, assignment, now); + } + return; + } + if (!assignment.suppressed || assignment.overridden || assignment.ruleOverride) { this._queueExposure(experimentName, assignment); } - this._triggerApplicableHoldoutExposures(assignment); + if (withHoldouts) this._triggerApplicableHoldoutExposures(assignment); } // Uses the pinned snapshot, not a live re-resolution, so a refresh between the suppression @@ -902,11 +1307,11 @@ export default class Context { }); } - private _queueExposure(experimentName: string, assignment: Assignment) { + private _queueExposure(experimentName: string, assignment: Assignment, exposedAt?: number) { const exposureEvent: Exposure = { id: assignment.id, name: experimentName, - exposedAt: Date.now(), + exposedAt: exposedAt ?? Date.now(), unit: assignment.unitType, variant: assignment.variant, assigned: assignment.assigned, @@ -923,6 +1328,11 @@ export default class Context { this._exposures.push(exposureEvent); this._pending++; + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["exposure", exposureEvent]); + return; + } + try { this._logEvent("exposure", exposureEvent); } finally { @@ -1020,45 +1430,123 @@ export default class Context { return this._customFieldValueType(experimentName, key); } - // A held-out unit reads the control value, not the caller's default, when nothing else wins. - // The first suppressed candidate is captured even if it lacks the key, so a later one can't win. + // Mirrors java-sdk Context.getVariableAssignment. Candidates define the key in any variant, in + // experiment-id order. The first one the unit is actually in (assigned, overridden or + // rule-assigned) wins regardless of its arm; otherwise the first held-out candidate supplies + // its control value. Only the winner gets an exposure, so a unit is never recorded in an + // experiment it only got checked against. Like Java, each visited candidate's applicable + // holdouts still fire on the non-peek path. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { - let suppressedFallback: Record | undefined; + const candidates = this._indexVariables[key]; + if (!Array.isArray(candidates)) return defaultValue; + + // Plain locals rather than tuples: this is a hot path and must not allocate per read. + let selectedName = ""; + let selected: Assignment | undefined; + let now: number | undefined; + + // Indexed loop: a for...of here compiles to a larger body that slows every warmed read. + for (let i = 0; i < candidates.length; i++) { + const experimentName = candidates[i].data.name; + now = this._switchbackClock(experimentName, now); + const assignment = this._assign(experimentName, now); + if (shouldQueueExposure) this._triggerApplicableHoldoutExposures(assignment); + + if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { + selectedName = experimentName; + selected = assignment; + break; + } - for (const experiment of this._indexVariables[key] ?? []) { - const experimentName = experiment.data.name; - const assignment = this._assign(experimentName); - if (assignment.variables !== undefined) { - if (shouldQueueExposure && !assignment.exposed) { - assignment.exposed = true; + if (assignment.suppressed && selected === undefined) { + selectedName = experimentName; + selected = assignment; + } + } - this._triggerExposures(experimentName, assignment); - } + if (selected === undefined) return defaultValue; - if (key in assignment.variables && (assignment.assigned || assignment.overridden || assignment.ruleOverride)) { - return assignment.variables[key] as string; - } + if (shouldQueueExposure && !selected.exposed) { + selected.exposed = true; - if ( - assignment.suppressed && - !assignment.overridden && - !assignment.ruleOverride && - suppressedFallback === undefined - ) { - suppressedFallback = assignment.variables; - } - } + this._triggerExposures(selectedName, selected, now, false); } - if (suppressedFallback !== undefined && key in suppressedFallback) { - return suppressedFallback[key] as string; + // A missing key (or out-of-range arm) returns the caller's default, never a later + // experiment's value: falling through by arm would bias the winning experiment. + const variables = selected.variables; + return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; + } + + // A user eventLogger may call finalize() or publish(). Exposure and error callbacks this read + // triggers run only after every exposure of the read (candidates' holdouts and the winner) is + // queued, so such a call sends all of them instead of sealing the context with one pending. + // The replay lives in its own method so a warmed read, which defers nothing, stays small. + private _variableValue(key: string, defaultValue: string): string { + if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); + + this._deferringLogs = true; + try { + return this._resolveVariableValue(key, defaultValue, true); + } finally { + this._endDeferral(); } + } - return defaultValue; + // Ends a deferral scope, replaying held callbacks in queue order. Deferral stays on while + // replaying, so a nested read or treatment() made from a callback appends its own callbacks + // behind the ones already queued. + private _endDeferral() { + if (this._deferredLogs === undefined) this._deferringLogs = false; + else if (this._replayExhausted) this._deliverDeferredLogs(); + else this._replayDeferredLogs(); + } + + // A callback that keeps feeding new events would drain forever (or grow the queue without + // bound), so once a replay has run DEFERRED_REPLAY_ROUNDS rounds or delivered + // DEFERRED_REPLAY_CALLBACKS callbacks, it stops queueing rounds: each later call still holds + // its own callbacks until all of its exposures are queued, then delivers that batch at once, + // bounded by the call stack as before deferral existed. + private _replayDeferredLogs() { + let exposed = false; + let rounds = 0; + let delivered = 0; + try { + let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; + while (deferred !== undefined) { + this._deferredLogs = undefined; + delivered += deferred.length; + if (++rounds >= DEFERRED_REPLAY_ROUNDS || delivered >= DEFERRED_REPLAY_CALLBACKS) { + this._deferringLogs = false; + this._replayExhausted = true; + } + for (let i = 0; i < deferred.length; i++) { + if (deferred[i][0] === "exposure") exposed = true; + this._logEvent(deferred[i][0], deferred[i][1]); + } + deferred = this._deferredLogs; + } + } finally { + this._deferringLogs = false; + this._replayExhausted = false; + // Only exposures need publishing; an error alone must not arm the timer. + if (exposed) this._setTimeout(); + } } - private _variableValue(key: string, defaultValue: string): string { - return this._resolveVariableValue(key, defaultValue, true); + private _deliverDeferredLogs() { + const deferred = this._deferredLogs as [EventName, Record | Error][]; + this._deferredLogs = undefined; + this._deferringLogs = false; + let exposed = false; + try { + for (let i = 0; i < deferred.length; i++) { + if (deferred[i][0] === "exposure") exposed = true; + this._logEvent(deferred[i][0], deferred[i][1]); + } + } finally { + if (exposed) this._setTimeout(); + } } private _peekVariable(key: string, defaultValue: string): string { @@ -1371,7 +1859,7 @@ export default class Context { } } - private _logEvent(eventName: EventName, data?: Record) { + private _logEvent(eventName: EventName, data?: Record | Error) { if (this._eventLogger) { // A throwing custom eventLogger must never propagate out of this method: // every call site treats logging as a side effect, and letting an @@ -1389,13 +1877,11 @@ export default class Context { } private _logError(error: Error) { - if (this._eventLogger) { - try { - this._eventLogger(this, "error", error); - } catch (observerError) { - console.error(observerError); - } + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["error", error]); + return; } + this._logEvent("error", error); } private _unitHash(unitType: string) { @@ -1517,12 +2003,30 @@ export default class Context { holdouts, }; + if (experiment.randomizationType === "switchback") { + const sources = switchbackSources(experiment.switchbackClusters); + const previous = this._index?.[experiment.name]?.switchback; + const keepsGeneration = + previous !== undefined && + sameSwitchbackIdentity( + this._index[experiment.name].data, + previous.sources !== null, + experiment, + sources !== null + ); + entry.switchback = { + generation: keepsGeneration ? previous.generation : ++this._switchbackGenerations, + sources, + }; + } + index[experiment.name] = entry; + let hasPrototypeVariable = false; for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; - let parsed = {}; + let parsed: Record = {}; if (config != null && config.length > 0) { try { @@ -1540,20 +2044,92 @@ export default class Context { } for (const key of Object.keys(parsed)) { + if (key in Object.prototype) hasPrototypeVariable = true; const value = entry; - if (indexVariables[key]) { + if (Array.isArray(indexVariables[key])) { insertUniqueSorted( indexVariables[key], value, (a, b) => (a as Experiment).data.id < (b as Experiment).data.id ); - } else indexVariables[key] = [value]; + } else { + Object.defineProperty(indexVariables, key, { + value: [value], + enumerable: true, + writable: true, + configurable: true, + }); + } } variables[i] = parsed; } + + // Only experiments defining a prototype-named key need dictionary configs. Classify at + // indexing time so ordinary variable reads retain their existing fast membership check. + if (hasPrototypeVariable) { + for (let i = 0; i < variables.length; i++) { + variables[i] = Object.assign(Object.create(null), variables[i]); + } + } }); + // A reused assignment (or switchback slot) still points at the previous parse of its configs; + // if a refresh made the experiment prototype-keyed, cached variables must not resolve inherited + // members. + const prototypeKeyed = (experimentName: string) => { + // Own lookup: an experiment named like an Object.prototype member must not resolve one. + const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) + ? index[experimentName] + : undefined; + return experiment !== undefined && Object.getPrototypeOf(experiment.variables[0] ?? {}) === null; + }; + const reclassify = (assignment: Assignment | undefined) => { + const variables = assignment?.variables; + if (assignment !== undefined && variables !== undefined && Object.getPrototypeOf(variables) !== null) { + assignment.variables = Object.assign(Object.create(null), variables); + } + }; + for (const experimentName of Object.keys(assignments)) { + if (prototypeKeyed(experimentName)) reclassify(assignments[experimentName]); + } + const epochs = this._switchbackEpochs; + if (epochs !== undefined) { + for (const experimentName of Object.keys(epochs)) { + if (!prototypeKeyed(experimentName)) continue; + const epoch = epochs[experimentName]; + reclassify(epoch.periodless); + for (const period of epoch.periods) reclassify(epoch.slots[period]); + } + } + + // A reused assignment (or switchback slot) follows its arm across refreshes: no variables while + // a refresh has removed the arm, and the arm's current variables again once a later refresh + // restores it. + const followArm = (experiment: Experiment, assignment: Assignment | undefined) => { + if (assignment === undefined) return; + if (assignment.variant >= experiment.data.variants.length) { + assignment.variables = undefined; + } else if (assignment.variables === undefined && assignment.id === experiment.data.id) { + assignment.variables = experiment.variables[assignment.variant]; + } + }; + const indexed = (experimentName: string) => + Object.prototype.hasOwnProperty.call(index, experimentName) ? index[experimentName] : undefined; + for (const experimentName of Object.keys(assignments)) { + const experiment = indexed(experimentName); + if (experiment !== undefined) followArm(experiment, assignments[experimentName]); + } + if (epochs !== undefined) { + for (const experimentName of Object.keys(epochs)) { + const experiment = indexed(experimentName); + if (experiment === undefined) continue; + const epoch = epochs[experimentName]; + followArm(experiment, epoch.periodless); + for (const period of epoch.periods) followArm(experiment, epoch.slots[period]); + } + } + this._index = index; this._indexVariables = indexVariables; this._assignments = assignments; diff --git a/src/switchback-long.ts b/src/switchback-long.ts new file mode 100644 index 0000000..ce482e1 --- /dev/null +++ b/src/switchback-long.ts @@ -0,0 +1,119 @@ +import { baseHash, fisherYatesPermutation, requireValidArmCount } from "./switchback"; + +// The switchback assigner over the full signed 64-bit range of periods, cycles and seeds, which the +// platform golden vectors pin (Long.MIN_VALUE and Long.MAX_VALUE included). Context never needs it: +// its period index is a non-negative safe integer (see assignSwitchbackPeriod). + +// A signed 64-bit integer as a sign and a magnitude in four little-endian 16-bit limbs. JS numbers +// are exact only up to 2^53, and BigInt is unavailable on the declared IE 10 / Node 6 targets. +type Int64 = { negative: boolean; limbs: number[] }; + +const INT64_MAX_DECIMAL = "9223372036854775807"; +const INT64_MIN_MAGNITUDE_DECIMAL = "9223372036854775808"; + +// A decimal integer in [-2^63, 2^63 - 1] as Java's Long.parseLong reads it (an optional sign, then +// ASCII digits), or null. +export function parseInt64(value: string): Int64 | null { + const sign = value.charAt(0); + const negative = sign === "-"; + const digits = negative || sign === "+" ? value.substring(1) : value; + if (!/^[0-9]+$/.test(digits)) return null; + + const trimmed = digits.replace(/^0+(?=.)/, ""); + const bound = negative ? INT64_MIN_MAGNITUDE_DECIMAL : INT64_MAX_DECIMAL; + if (trimmed.length > bound.length || (trimmed.length === bound.length && trimmed > bound)) return null; + + const limbs = [0, 0, 0, 0]; + for (let i = 0; i < trimmed.length; ++i) { + let carry = trimmed.charCodeAt(i) - 48; + for (let l = 0; l < 4; ++l) { + const v = limbs[l] * 10 + carry; + limbs[l] = v & 0xffff; + carry = Math.floor(v / 0x10000); + } + } + return { negative: negative && trimmed !== "0", limbs }; +} + +// Divides a magnitude by a positive integer below 2^37, so every partial dividend stays below 2^53. +function divideMagnitude(limbs: number[], divisor: number): { quotient: number[]; remainder: number } { + const quotient = [0, 0, 0, 0]; + let remainder = 0; + for (let l = 3; l >= 0; --l) { + const v = remainder * 0x10000 + limbs[l]; + quotient[l] = Math.floor(v / divisor); + remainder = v - quotient[l] * divisor; + } + return { quotient, remainder }; +} + +function isZero(limbs: number[]) { + return (limbs[0] | limbs[1] | limbs[2] | limbs[3]) === 0; +} + +function increment(limbs: number[]): number[] { + const result = limbs.slice(); + for (let l = 0; l < 4; ++l) { + if (result[l] < 0xffff) { + ++result[l]; + return result; + } + result[l] = 0; + } + return result; +} + +// floorDiv and floorMod by a positive divisor, as Java's Math.floorDiv / Math.floorMod. +function floorDivMod(value: Int64, divisor: number): { quotient: Int64; modulo: number } { + const { quotient, remainder } = divideMagnitude(value.limbs, divisor); + if (!value.negative) return { quotient: { negative: false, limbs: quotient }, modulo: remainder }; + if (remainder === 0) return { quotient: { negative: !isZero(quotient), limbs: quotient }, modulo: 0 }; + return { quotient: { negative: true, limbs: increment(quotient) }, modulo: divisor - remainder }; +} + +// Signed base-10 text with no leading zeros, as Java's Long.toString. +function int64ToDecimal(value: Int64): string { + let limbs = value.limbs; + if (isZero(limbs)) return "0"; + let text = ""; + while (!isZero(limbs)) { + const { quotient, remainder } = divideMagnitude(limbs, 10000); + limbs = quotient; + const chunk = String(remainder); + text = (isZero(limbs) ? chunk : "0000".substring(chunk.length) + chunk) + text; + } + return value.negative ? `-${text}` : text; +} + +// The two's-complement 32-bit halves: (int) value and (int) (value >>> 32). +function int64Words(value: Int64): { hi: number; lo: number } { + let lo = (value.limbs[0] | (value.limbs[1] << 16)) >>> 0; + let hi = (value.limbs[2] | (value.limbs[3] << 16)) >>> 0; + if (value.negative) { + lo = (~lo + 1) >>> 0; + hi = (~hi + (lo === 0 ? 1 : 0)) >>> 0; + } + return { hi: hi | 0, lo: lo | 0 }; +} + +function requireInt64(field: string, value: string): Int64 { + const parsed = typeof value === "string" ? parseInt64(value) : null; + if (parsed === null) throw new Error(`${field} must be a signed 64-bit decimal string, got ${value}`); + return parsed; +} + +// assignSwitchback(clusterUnit, periodIndex, seed, armCount), periodIndex and seed as decimal strings. +export function assignSwitchback(clusterUnit: string, periodIndex: string, seed: string, armCount: number): number { + requireValidArmCount(armCount); + const { hi, lo } = int64Words(requireInt64("seed", seed)); + const { quotient, modulo } = floorDivMod(requireInt64("periodIndex", periodIndex), armCount); + return fisherYatesPermutation(armCount, baseHash(clusterUnit, int64ToDecimal(quotient), hi, lo))[modulo]; +} + +// fisherYatesPermutation(armCount, baseHash(clusterUnit, cycleIndex, seed)), decimal-string inputs. +export function switchbackPermutation(clusterUnit: string, cycleIndex: string, seed: string, armCount: number) { + requireValidArmCount(armCount); + const { hi, lo } = int64Words(requireInt64("seed", seed)); + const cycle = int64ToDecimal(requireInt64("cycleIndex", cycleIndex)); + return fisherYatesPermutation(armCount, baseHash(clusterUnit, cycle, hi, lo)); +} diff --git a/src/switchback.ts b/src/switchback.ts new file mode 100644 index 0000000..5a84154 --- /dev/null +++ b/src/switchback.ts @@ -0,0 +1,343 @@ +import { murmur3_32 } from "./murmur3_32"; +import { stringToUint8Array, toWellFormedString } from "./utils"; + +// Switchback experiments (R33, cluster-defined): a port of java-sdk's internal Switchback* classes, +// which port the platform's SwitchbackAssignment and the Collector's ContextAPI.switchbackServing. +// See the README section "Switchback experiments" for the serving rules. The full signed 64-bit +// assigner, which Context does not need, is in switchback-long.ts so the browser bundle leaves it out. + +const NORMALIZER = 1.0 / 0xffffffff; + +export function requireValidArmCount(armCount: number) { + if (typeof armCount !== "number" || Math.floor(armCount) !== armCount || armCount < 2 || armCount > 0x7fffffff) { + throw new Error(`armCount must be an integer >= 2, got ${armCount}`); + } +} + +// murmur3_32(le64(seed) ++ le32(murmur3_32(utf8(clusterUnit + "\u001f" + cycleIndex)))). A lone +// surrogate encodes as '?', as the platform's String.getBytes(UTF_8) does. +export function baseHash(clusterUnit: string, cycleIndex: string, seedHi: number, seedLo: number): number { + const key = toWellFormedString(`${clusterUnit}\u001f${cycleIndex}`, "?"); + const keyHash = murmur3_32(stringToUint8Array(key).buffer); + + const buffer = new ArrayBuffer(12); + const view = new DataView(buffer); + view.setUint32(0, seedLo, true); + view.setUint32(4, seedHi, true); + view.setUint32(8, keyHash, true); + return murmur3_32(buffer); +} + +// Fisher-Yates over [0, armCount), each swap drawn from murmur3_32(le32(baseHash) ++ le32(i)). +export function fisherYatesPermutation(armCount: number, hash: number): number[] { + const permutation: number[] = []; + for (let i = 0; i < armCount; ++i) { + permutation[i] = i; + } + + const buffer = new ArrayBuffer(8); + const view = new DataView(buffer); + view.setUint32(0, hash, true); + for (let i = armCount - 1; i > 0; --i) { + view.setUint32(4, i, true); + const prob = murmur3_32(buffer) * NORMALIZER; + // prob == 1.0 would map to i + 1 + const j = Math.min(i, Math.floor(prob * (i + 1))); + + const tmp = permutation[i]; + permutation[i] = permutation[j]; + permutation[j] = tmp; + } + + return permutation; +} + +// The balanced-block draw for a period at or after the anchor under the experiment seed +// (seedHi << 32) | (seedLo & 0xffffffff): permutation[floorMod(periodIndex, armCount)] of the cycle +// floorDiv(periodIndex, armCount). +export function assignSwitchbackPeriod( + clusterKey: string, + periodIndex: number, + seedHi: number, + seedLo: number, + armCount: number +): number { + requireValidArmCount(armCount); + const cycle = Math.floor(periodIndex / armCount); + return fisherYatesPermutation(armCount, baseHash(clusterKey, String(cycle), seedHi, seedLo))[ + periodIndex - cycle * armCount + ]; +} + +// A cluster attribute path, resolved like the Collector's SwitchbackAttributePath: "/" separates +// segments, a segment wrapped in ' or " is a literal key, and an unquoted segment that Guava +// Ints.tryParse accepts indexes an array and nothing else. Every other segment reads an object key. +export type SwitchbackAttributePath = { keys: string[]; indices: (number | null)[] }; + +// Guava Ints.tryParse: an optional '-', then one or more ASCII digits, within int32. "-0" is 0. +export function tryParseInt(value: string): number | null { + const negative = value.charAt(0) === "-"; + const digits = negative ? value.substring(1) : value; + if (!/^[0-9]+$/.test(digits)) return null; + const trimmed = digits.replace(/^0+(?=.)/, ""); + if (trimmed.length > 10) return null; + const parsed = negative ? -Number(trimmed) : Number(trimmed); + return parsed >= -2147483648 && parsed <= 2147483647 ? parsed + 0 : null; +} + +// Null for an unsupported path: a '.' anywhere (quoted or not, dotted paths are not a nesting +// syntax), an unterminated quote, no segment, or an index that is negative, first, last, or directly +// after another index. Analysis cannot read those. +export function parseSwitchbackPath(path: unknown): SwitchbackAttributePath | null { + if (typeof path !== "string" || path.indexOf(".") >= 0) return null; + + const keys: string[] = []; + const indices: (number | null)[] = []; + let i = 0; + while (i < path.length) { + const first = path.charAt(i); + if (first === "/") { + ++i; + } else if (first === "'" || first === '"') { + const end = path.indexOf(first, i + 1); + if (end < 0) return null; + keys.push(path.substring(i + 1, end)); + indices.push(null); + i = end + 1; + } else { + const slash = path.indexOf("/", i); + const end = slash < 0 ? path.length : slash; + const key = path.substring(i, end); + keys.push(key); + indices.push(tryParseInt(key)); + i = end; + } + } + + const n = keys.length; + if (n === 0) return null; + for (let s = 0; s < n; ++s) { + const index = indices[s]; + if (index !== null && (index < 0 || s === 0 || s === n - 1 || indices[s - 1] !== null)) return null; + } + return { keys, indices }; +} + +function step(current: unknown, key: string, index: number | null): unknown { + if (index !== null) { + return Array.isArray(current) && index < current.length ? current[index] : null; + } + if (current !== null && typeof current === "object" && !Array.isArray(current)) { + return Object.prototype.hasOwnProperty.call(current, key) ? (current as Record)[key] : null; + } + return null; +} + +// Resolves the path below its first segment in the value of the attribute that segment names. The +// value is read as the Collector reads it: through its JSON encoding, the form it is published in. +// A value with no JSON encoding (a cycle, a BigInt, undefined) has nothing below it. +export function resolveSwitchbackPath(path: SwitchbackAttributePath, rootValue: unknown): unknown { + let current: unknown = rootValue; + if (current !== null && typeof current === "object") { + try { + current = JSON.parse(JSON.stringify(current)); + } catch (error) { + return null; + } + } + for (let s = 1; s < path.keys.length && current != null; ++s) { + current = step(current, path.keys[s], path.indices[s]); + } + return current; +} + +// The cluster key a value yields, as the Collector's SwitchbackClusterKeys.normalize keys the value +// this SDK publishes: a non-empty string as-is and a whole number as its base-10 text. A JS number +// cannot tell 3.0 from 3, and both publish as 3, so an integral float is keyed like the integer. +// Every other number (fractions, non-finite, and magnitudes the JSON encoding writes with an +// exponent), booleans, objects, arrays, empty strings and null yield no key. +export function switchbackClusterKey(value: unknown): string | null { + if (typeof value === "string") return value.length > 0 ? value : null; + if (typeof value === "number" && Math.floor(value) === value && Math.abs(value) < 1e21) return String(value); + return null; +} + +export const SWITCHBACK_ABSENT = 0; +export const SWITCHBACK_INELIGIBLE = 1; +export const SWITCHBACK_ELIGIBLE = 2; + +export type SwitchbackServing = { + status: number; + // The serving unit type when eligible, the first linked unit type when ineligible, null when absent. + unitType: string | null; + // The raw cluster key when eligible; never hashed. + clusterKey: string | null; +}; + +// Which unit serves and under which cluster key, as the Collector's ContextAPI.switchbackServing: +// the sources in declared order, each read for the context's unit of that type (a context holds one +// uid per type). The first unit yielding a value serves; a later different value is a disagreement. +export function resolveSwitchbackServing( + sourceTypes: string[], + sourcePaths: SwitchbackAttributePath[], + allowedValues: unknown, + units: Record, + read: (path: SwitchbackAttributePath) => unknown +): SwitchbackServing { + let first: string | null = null; + let serving: string | null = null; + let key: string | null = null; + let disagreement = false; + for (let s = 0; s < sourceTypes.length; ++s) { + const type = sourceTypes[s]; + if (!Object.prototype.hasOwnProperty.call(units, type) || units[type] == null) continue; + if (first === null) first = type; + const value = switchbackClusterKey(read(sourcePaths[s])); + if (value === null) continue; + if (key === null) { + key = value; + serving = type; + } else if (key !== value) { + disagreement = true; + } + } + + if (first === null) return { status: SWITCHBACK_ABSENT, unitType: null, clusterKey: null }; + if (key === null || disagreement || !isAllowed(allowedValues, key)) { + return { status: SWITCHBACK_INELIGIBLE, unitType: first, clusterKey: null }; + } + return { status: SWITCHBACK_ELIGIBLE, unitType: serving, clusterKey: key }; +} + +// A null or empty allow-list admits every value. Anything else that is not a list admits none. +function isAllowed(allowedValues: unknown, key: string) { + if (allowedValues == null) return true; + if (!Array.isArray(allowedValues)) return false; + if (allowedValues.length === 0) return true; + // A string entry is compared as-is, and a number or boolean as its text, as Java reads one in this + // string list. + for (let i = 0; i < allowedValues.length; ++i) { + const allowed = allowedValues[i]; + const type = typeof allowed; + if ((type === "string" || type === "number" || type === "boolean") && String(allowed) === key) return true; + } + return false; +} + +// The Collector's path for a missing, empty or unreadable cluster map: the declared unitType only +// identifies an ineligible control; without a unit of that type the experiment does not apply. +export function legacySwitchbackServing(unitType: string | null, units: Record): SwitchbackServing { + if (unitType != null && Object.prototype.hasOwnProperty.call(units, unitType) && units[unitType] != null) { + return { status: SWITCHBACK_INELIGIBLE, unitType, clusterKey: null }; + } + return { status: SWITCHBACK_ABSENT, unitType: null, clusterKey: null }; +} + +// An object key JS enumerates before every other key, in ascending numeric order, whatever its +// position in the JSON text (a canonical array index). +function isArrayIndexKey(key: string) { + return /^(0|[1-9][0-9]*)$/.test(key) && Number(key) < 4294967295; +} + +// The linked unit types and parsed paths of a switchbackClusters object in declared order, or null +// for a map the legacy path serves: missing, empty, not an object, with a non-string type or path, or +// with an unsupported path. A map of two or more entries with an array-index unit type name is +// unreadable too: JS moves such keys first, so their declared order is lost in parsing. +export function switchbackSources(clusters: unknown): SwitchbackSources | null { + if (clusters == null || typeof clusters !== "object" || Array.isArray(clusters)) return null; + const types = Object.keys(clusters); + if (types.length === 0) return null; + + const paths: SwitchbackAttributePath[] = []; + for (const type of types) { + if (types.length > 1 && isArrayIndexKey(type)) return null; + const path = parseSwitchbackPath((clusters as Record)[type]); + if (path === null) return null; + paths.push(path); + } + return { types, paths }; +} + +export type SwitchbackSources = { types: string[]; paths: SwitchbackAttributePath[] }; + +// The Collector's anchor bounds (Registry): hour aligned and in [0, 10000-01-01T00:00:00Z). +const ANCHOR_ALIGNMENT_MS = 3600000; +const MAX_ANCHOR_MS = 253402300800000; + +function isWholeNumber(value: unknown): value is number { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +} + +// floorDiv(now - switchbackStartAt, switchbackPeriodMs), or null when the draw cannot run: before +// the anchor, or with an unservable schedule (an anchor that is unset, unaligned or out of bounds, a +// period that is unset or not positive, or fewer than two arms). The anchor is used as served, never +// rounded. For non-negative integers below 2^53, Math.floor of the double quotient is the exact floor: +// a non-integral quotient is at least 1/periodMs from the next integer, more than half an ulp there. +export function switchbackPeriodIndex(experiment: ExperimentSchedule, now: number): number | null { + const startAt = experiment.switchbackStartAt; + const periodMs = experiment.switchbackPeriodMs; + if (!isWholeNumber(startAt) || startAt < 0 || startAt >= MAX_ANCHOR_MS || startAt % ANCHOR_ALIGNMENT_MS !== 0) { + return null; + } + if (!isWholeNumber(periodMs) || periodMs <= 0) return null; + if (!Array.isArray(experiment.split) || experiment.split.length < 2) return null; + if (now < startAt) return null; + return Math.floor((now - startAt) / periodMs); +} + +type ExperimentSchedule = { + id: number; + iteration: number; + unitType: string | null; + split: number[]; + switchbackClusters?: unknown; + switchbackClusterValues?: unknown; + switchbackStartAt?: unknown; + switchbackPeriodMs?: unknown; + switchbackDesignType?: unknown; +}; + +function orderedEntries(value: unknown): unknown { + if (value == null) return null; + if (typeof value !== "object" || Array.isArray(value)) return value; + const entries: unknown[] = []; + for (const key of Object.keys(value)) { + entries.push(key, (value as Record)[key]); + } + return entries; +} + +// Shallow equality with null and undefined alike; arrays compare element by element. +function sameValue(a: unknown, b: unknown): boolean { + if (a == null || b == null) return a == null && b == null; + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) return false; + } + return true; + } + return a === b; +} + +// Whether a refreshed switchback keeps its predecessor's epoch: the same id and iteration, cluster +// map (types, paths and their order), allow-list, anchor, period length and design, plus the same +// unitType when either side takes the legacy path. Seed, split and the analysis-only fields +// (carryover, burn-in, burn-out, estimand) are not identity. +export function sameSwitchbackIdentity( + previous: ExperimentSchedule, + previousReadable: boolean, + installed: ExperimentSchedule, + installedReadable: boolean +): boolean { + return ( + previous.id === installed.id && + previous.iteration === installed.iteration && + sameValue(orderedEntries(previous.switchbackClusters), orderedEntries(installed.switchbackClusters)) && + sameValue(previous.switchbackClusterValues, installed.switchbackClusterValues) && + sameValue(previous.switchbackStartAt, installed.switchbackStartAt) && + sameValue(previous.switchbackPeriodMs, installed.switchbackPeriodMs) && + sameValue(previous.switchbackDesignType, installed.switchbackDesignType) && + ((previousReadable && installedReadable) || sameValue(previous.unitType, installed.unitType)) + ); +} diff --git a/src/utils.ts b/src/utils.ts index 2c6dd11..30feace 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -152,7 +152,7 @@ export function arrayEqualsShallow(a?: unknown[], b?: unknown[]) { // `String.prototype.toWellFormed()` (ES2024, not assumed available under the // declared Node 6 / IE 10 targets) so `encodeURIComponent` — which throws // `URIError: URI malformed` on a lone surrogate — never sees one. -export function toWellFormedString(value: string): string { +export function toWellFormedString(value: string, replacement = "\ufffd"): string { let result = ""; for (let i = 0; i < value.length; i++) { @@ -163,10 +163,10 @@ export function toWellFormedString(value: string): string { result += value[i] + value[i + 1]; i++; } else { - result += "�"; + result += replacement; } } else if (c >= 0xdc00 && c <= 0xdfff) { - result += "�"; + result += replacement; } else { result += value[i]; }