From f657252e0cbe9c7d8e3604b9bb50174a14fa4943 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 11:01:22 +0000 Subject: [PATCH 01/48] feat(switchback): serve R33 cluster-defined switchback experiments (FT-2537) Port of java-sdk#15: the balanced-block assigner with exact 64-bit period and seed math (no BigInt, for the IE 10 / Node 6 targets), the Collector's attribute paths, cluster-value rule and serving, and the switchback branch of assignment with per-period slots and epochs. Golden vectors and path cases are vendored byte-for-byte from abs. Co-Authored-By: Claude Opus 5.5 --- .prettierignore | 2 + .../switchback/attribute-path-cases.json | 16 + .../fixtures/switchback/golden-vectors.json | 1392 +++++++++++++++++ src/__tests__/switchback.test.js | 577 +++++++ src/context.ts | 396 ++++- src/switchback.ts | 459 ++++++ src/utils.ts | 6 +- 7 files changed, 2835 insertions(+), 13 deletions(-) create mode 100644 src/__tests__/fixtures/switchback/attribute-path-cases.json create mode 100644 src/__tests__/fixtures/switchback/golden-vectors.json create mode 100644 src/__tests__/switchback.test.js create mode 100644 src/switchback.ts 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/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..5812099 --- /dev/null +++ b/src/__tests__/switchback.test.js @@ -0,0 +1,577 @@ +import { + assignSwitchback, + assignSwitchbackPeriod, + parseInt64, + parseSwitchbackPath, + resolveSwitchbackPath, + resolveSwitchbackServing, + sameSwitchbackIdentity, + switchbackClusterKey, + switchbackPeriodIndex, + switchbackPermutation, + 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", () => { + 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", () => { + expect(assignSwitchback("café", "0", "0", 10)).toEqual(assignSwitchback("café", "0", "0", 10)); + 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 + ); + // 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") }); + }); +}); + +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); + // An exact division that rounds up as a double is corrected down. + 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..e925808 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 }; @@ -48,6 +62,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 +104,24 @@ 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: the bare-name slot (before the anchor or with an +// unservable schedule) and at most SWITCHBACK_RETAINED_PERIODS period slots, all of one generation. +type SwitchbackEpoch = { + generation: number; + periods: number[]; +}; + +const SWITCHBACK_RETAINED_PERIODS = 2; + export type HoldoutData = { id: number; name: string; @@ -100,6 +144,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 = { @@ -192,6 +239,8 @@ export default class Context { 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 +270,7 @@ export default class Context { this._attrsSeq = 0; this._attrsMapCache = null; this._attrsMapCacheSeq = -1; + this._switchbackGenerations = 0; if (params.units) { this.units(params.units); @@ -367,6 +417,15 @@ export default class Context { private _invalidateAssignmentsPinnedWithMissingUnit(unitType: string): void { for (const experimentName in this._assignments) { const assignment = this._assignments[experimentName]; + const serving = assignment.switchbackServing; + if (serving !== undefined) { + // A switchback resolved with no linked unit set is resolved again now that one may be. Unless + // overridden it published nothing, so it is dropped even when exposed. + if (serving.status === SWITCHBACK_ABSENT && (!assignment.overridden || !assignment.exposed)) { + delete this._assignments[experimentName]; + } + continue; + } if (assignment.unitType !== unitType || assignment.exposed) continue; const hasMissingHoldoutEntry = assignment.holdoutAssignments?.some( @@ -514,7 +573,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 +596,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 +654,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 +742,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,19 +936,302 @@ 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; + const cacheKey = periodIndex === null ? experimentName : `${experimentName}\u001f${periodIndex}`; + const hasOverride = experimentName in this._overrides; + const custom = experimentName in this._cassignments ? this._cassignments[experimentName] : undefined; + + const cached: Assignment | undefined = this._assignments[cacheKey]; + if ( + cached !== undefined && + cached.switchbackGeneration === switchback.generation && + this._isSwitchbackAssignmentCurrent(experiment, cached, hasOverride, custom) + ) { + return cached; + } + + 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 = cached?.switchbackGeneration === switchback.generation ? cached.switchbackServing : undefined; + 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._assignments[cacheKey] = assignment; + this._retainSwitchbackPeriod(experimentName, switchback.generation, periodIndex); + 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 (its period slots and its bare-name slot) + // 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; + + for (const period of epoch.periods) { + delete this._assignments[`${experimentName}\u001f${period}`]; + } + delete this._assignments[experimentName]; + delete epochs[experimentName]; + } + + // Keeps at most SWITCHBACK_RETAINED_PERIODS period slots 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 _retainSwitchbackPeriod(experimentName: string, generation: number, periodIndex: number | null) { + const epochs = this._switchbackEpochs ?? (this._switchbackEpochs = {}); + const epoch = epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [] }); + if (periodIndex === null || 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 this._assignments[`${experimentName}\u001f${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); + this._triggerExposures(experimentName, assignment, now); } 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. + private _triggerExposures(experimentName: string, assignment: Assignment, now?: number): 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); } @@ -902,11 +1257,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, @@ -1024,15 +1379,17 @@ export default class Context { // The first suppressed candidate is captured even if it lacks the key, so a later one can't win. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { let suppressedFallback: Record | undefined; + let now: number | undefined; for (const experiment of this._indexVariables[key] ?? []) { const experimentName = experiment.data.name; - const assignment = this._assign(experimentName); + now = this._switchbackClock(experimentName, now); + const assignment = this._assign(experimentName, now); if (assignment.variables !== undefined) { if (shouldQueueExposure && !assignment.exposed) { assignment.exposed = true; - this._triggerExposures(experimentName, assignment); + this._triggerExposures(experimentName, assignment, now); } if (key in assignment.variables && (assignment.assigned || assignment.overridden || assignment.ruleOverride)) { @@ -1517,6 +1874,25 @@ export default class Context { holdouts, }; + if (experiment.randomizationType === "switchback") { + // Holdouts never apply to a switchback. + entry.holdouts = null; + 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; for (let i = 0; i < experiment.variants.length; i++) { diff --git a/src/switchback.ts b/src/switchback.ts new file mode 100644 index 0000000..97a4746 --- /dev/null +++ b/src/switchback.ts @@ -0,0 +1,459 @@ +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. + +// 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 }; +} + +// A non-negative safe integer as an Int64. +function int64FromNonNegative(value: number): Int64 { + const hi = Math.floor(value / 0x100000000); + const lo = value - hi * 0x100000000; + return { negative: false, limbs: [lo & 0xffff, lo >>> 16, hi & 0xffff, hi >>> 16] }; +} + +// 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 }; +} + +const NORMALIZER = 1.0 / 0xffffffff; + +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. +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)). +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; +} + +function assign(clusterUnit: string, periodIndex: Int64, seedHi: number, seedLo: number, armCount: number) { + const { quotient, modulo } = floorDivMod(periodIndex, armCount); + return fisherYatesPermutation(armCount, baseHash(clusterUnit, int64ToDecimal(quotient), seedHi, seedLo))[modulo]; +} + +// The balanced-block draw for a period at or after the anchor (periodIndex a non-negative safe +// integer) under the experiment seed (seedHi << 32) | (seedLo & 0xffffffff). +export function assignSwitchbackPeriod( + clusterKey: string, + periodIndex: number, + seedHi: number, + seedLo: number, + armCount: number +): number { + requireValidArmCount(armCount); + return assign(clusterKey, int64FromNonNegative(periodIndex), seedHi, seedLo, armCount); +} + +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) over the full signed 64-bit range; +// periodIndex and seed are decimal strings. Pinned by the platform golden vectors. +export function assignSwitchback(clusterUnit: string, periodIndex: string, seed: string, armCount: number): number { + requireValidArmCount(armCount); + const { hi, lo } = int64Words(requireInt64("seed", seed)); + return assign(clusterUnit, requireInt64("periodIndex", periodIndex), hi, lo, armCount); +} + +// 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)); +} + +// 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; + return allowedValues.length === 0 || allowedValues.indexOf(key) >= 0; +} + +// 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. +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; + const elapsed = now - startAt; + // A rounded quotient can land on the next integer; the remainder check corrects it. + let index = Math.floor(elapsed / periodMs); + if (index * periodMs > elapsed) --index; + return index; +} + +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]; } From 0ea0924453d73bd5c6d0f7ed81c4c8eec2e962d1 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 12:48:11 +0000 Subject: [PATCH 02/48] test(switchback): port the java-sdk context suites and close mutation gaps (FT-2537) Ports ContextSwitchbackTest and ContextSwitchbackClusterRuleTest (with the Collector's wire-rule parity grid). Moves the full 64-bit assigner to switchback-long.ts so the browser bundle only carries the period draw, drops two floor corrections the double arithmetic never needs, and adds tests that each kill a measured surviving mutant. README section, Migration Guide note and CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 + README.md | 29 + .../context-switchback-cluster.test.js | 530 ++++++ src/__tests__/context-switchback.test.js | 1604 +++++++++++++++++ src/__tests__/switchback.test.js | 6 +- src/context.ts | 14 +- src/switchback-long.ts | 119 ++ src/switchback.ts | 154 +- 8 files changed, 2318 insertions(+), 152 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 src/__tests__/context-switchback-cluster.test.js create mode 100644 src/__tests__/context-switchback.test.js create mode 100644 src/switchback-long.ts diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7999bd5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# 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. + +### Changed + +- 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 variant for the current period, and exposures are recorded once per period under the serving unit. Who moves: customers who run switchback experiments. Unit experiments and context data without switchbacks are unchanged. diff --git a/README.md b/README.md index 2b47e7d..77cca44 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,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 as its decimal text (`17` and `"17"` are the same cluster). 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. +- **Paths.** `/` separates segments (`profile/region`, `items/0/region`), a quoted segment is a literal key (`'a/b'`), and a number indexes an array. 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). **Ineligible cluster** (no value, units disagree, or a value outside the experiment's allowed values): variant 0 and no exposure. +- **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, under the serving unit's type, with the same fields as any other exposure. Its `exposedAt` is the time at which the call chose the period. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. + +The schedule follows the device clock (`Date.now()`), so a device whose clock is wrong is served another period's variant. + ## Advanced ### Context Attributes @@ -554,6 +577,12 @@ 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 under the serving unit. Unit experiments, and context data without switchback experiments, are not affected. + ## 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..604e484 --- /dev/null +++ b/src/__tests__/context-switchback-cluster.test.js @@ -0,0 +1,530 @@ +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 slots = Object.keys(context._assignments).filter((key) => key === "sbc" || key.indexOf("sbc\u001f") === 0); + expect(slots.length).toEqual(1); + return context._assignments[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.test.js b/src/__tests__/context-switchback.test.js new file mode 100644 index 0000000..9a8152a --- /dev/null +++ b/src/__tests__/context-switchback.test.js @@ -0,0 +1,1604 @@ +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); + // Like a unit experiment on the key, the strict-mismatched switchback visited first is exposed too. + expect(await publishExposures(context)).toEqual([ + strictMismatchExposure(ANCHOR + HOUR + 3), + exposure(2, "exp_unit", 1, ANCHOR + HOUR + 3, true, true, { fullOn: true }), + ]); + }); + + 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"); + } + expect(Object.keys(context._assignments).length).toEqual(4); + 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(1, "exp_first", 0, ANCHOR + HOUR - 1, false, true, { audienceMismatch: true }), + 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); + }); + + // The unit path reads the bare-name slot, so the pre-anchor switchback slot must not survive the + // switch to a unit experiment, and no period slot outlives its epoch. + 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).sort()).toEqual([ + "exp_periods\u001f0", + "exp_periods\u001f1", + "exp_sb", + ]); + + 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((await publishExposures(context)).map((e) => [e.name, e.variant, e.assigned])).toEqual([ + ["exp_sb", expected, true], + ["exp_periods", expect.any(Number), true], + ]); + }); + + 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" }, + ]); + }); + + // 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__/switchback.test.js b/src/__tests__/switchback.test.js index 5812099..7dcf297 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -1,14 +1,12 @@ +import { assignSwitchback, parseInt64, switchbackPermutation } from "../switchback-long"; import { - assignSwitchback, assignSwitchbackPeriod, - parseInt64, parseSwitchbackPath, resolveSwitchbackPath, resolveSwitchbackServing, sameSwitchbackIdentity, switchbackClusterKey, switchbackPeriodIndex, - switchbackPermutation, switchbackSources, tryParseInt, SWITCHBACK_ABSENT, @@ -460,7 +458,7 @@ describe("switchback schedule", () => { expect( switchbackPeriodIndex(schedule(1704067200000, 1440000000000), 1704067200000 + 1440000000000 - 1) ).toEqual(0); - // An exact division that rounds up as a double is corrected down. + // 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); diff --git a/src/context.ts b/src/context.ts index e925808..f0e51cc 100644 --- a/src/context.ts +++ b/src/context.ts @@ -950,12 +950,9 @@ export default class Context { const hasOverride = experimentName in this._overrides; const custom = experimentName in this._cassignments ? this._cassignments[experimentName] : undefined; + // `_assign` already dropped the slots of an earlier generation (see `_dropStaleSwitchbackEpoch`). const cached: Assignment | undefined = this._assignments[cacheKey]; - if ( - cached !== undefined && - cached.switchbackGeneration === switchback.generation && - this._isSwitchbackAssignmentCurrent(experiment, cached, hasOverride, custom) - ) { + if (cached !== undefined && this._isSwitchbackAssignmentCurrent(experiment, cached, hasOverride, custom)) { return cached; } @@ -981,7 +978,7 @@ export default class Context { // 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 = cached?.switchbackGeneration === switchback.generation ? cached.switchbackServing : undefined; + const cachedServing = cached?.switchbackServing; const serving = cachedServing !== undefined && cachedServing.status !== SWITCHBACK_ABSENT ? cachedServing @@ -1223,7 +1220,8 @@ export default class Context { } // 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. + // 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): void { if (assignment.switchbackGeneration !== undefined) { if (!assignment.switchbackSilent) { @@ -1875,8 +1873,6 @@ export default class Context { }; if (experiment.randomizationType === "switchback") { - // Holdouts never apply to a switchback. - entry.holdouts = null; const sources = switchbackSources(experiment.switchbackClusters); const previous = this._index?.[experiment.name]?.switchback; const keepsGeneration = 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 index 97a4746..43276e1 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -3,110 +3,12 @@ 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. - -// 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 }; -} - -// A non-negative safe integer as an Int64. -function int64FromNonNegative(value: number): Int64 { - const hi = Math.floor(value / 0x100000000); - const lo = value - hi * 0x100000000; - return { negative: false, limbs: [lo & 0xffff, lo >>> 16, hi & 0xffff, hi >>> 16] }; -} - -// 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 }; -} +// 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; -function requireValidArmCount(armCount: number) { +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}`); } @@ -114,7 +16,7 @@ function requireValidArmCount(armCount: number) { // 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. -function baseHash(clusterUnit: string, cycleIndex: string, seedHi: number, seedLo: number): number { +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); @@ -127,7 +29,7 @@ function baseHash(clusterUnit: string, cycleIndex: string, seedHi: number, seedL } // Fisher-Yates over [0, armCount), each swap drawn from murmur3_32(le32(baseHash) ++ le32(i)). -function fisherYatesPermutation(armCount: number, hash: number): number[] { +export function fisherYatesPermutation(armCount: number, hash: number): number[] { const permutation: number[] = []; for (let i = 0; i < armCount; ++i) { permutation[i] = i; @@ -150,13 +52,9 @@ function fisherYatesPermutation(armCount: number, hash: number): number[] { return permutation; } -function assign(clusterUnit: string, periodIndex: Int64, seedHi: number, seedLo: number, armCount: number) { - const { quotient, modulo } = floorDivMod(periodIndex, armCount); - return fisherYatesPermutation(armCount, baseHash(clusterUnit, int64ToDecimal(quotient), seedHi, seedLo))[modulo]; -} - -// The balanced-block draw for a period at or after the anchor (periodIndex a non-negative safe -// integer) under the experiment seed (seedHi << 32) | (seedLo & 0xffffffff). +// 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, @@ -165,29 +63,10 @@ export function assignSwitchbackPeriod( armCount: number ): number { requireValidArmCount(armCount); - return assign(clusterKey, int64FromNonNegative(periodIndex), seedHi, seedLo, armCount); -} - -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) over the full signed 64-bit range; -// periodIndex and seed are decimal strings. Pinned by the platform golden vectors. -export function assignSwitchback(clusterUnit: string, periodIndex: string, seed: string, armCount: number): number { - requireValidArmCount(armCount); - const { hi, lo } = int64Words(requireInt64("seed", seed)); - return assign(clusterUnit, requireInt64("periodIndex", periodIndex), hi, lo, armCount); -} - -// 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)); + 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 @@ -384,7 +263,8 @@ function isWholeNumber(value: unknown): value is number { // 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. +// 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; @@ -394,11 +274,7 @@ export function switchbackPeriodIndex(experiment: ExperimentSchedule, now: numbe if (!isWholeNumber(periodMs) || periodMs <= 0) return null; if (!Array.isArray(experiment.split) || experiment.split.length < 2) return null; if (now < startAt) return null; - const elapsed = now - startAt; - // A rounded quotient can land on the next integer; the remainder check corrects it. - let index = Math.floor(elapsed / periodMs); - if (index * periodMs > elapsed) --index; - return index; + return Math.floor((now - startAt) / periodMs); } type ExperimentSchedule = { From 68768333e245b78c0254a8febfc4e95e1d2b10ef Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 14:26:33 +0000 Subject: [PATCH 03/48] fix(switchback): never serve a unit assignment cached before the experiment became a switchback (FT-2537) The bare-name slot is shared by unit experiments and the pre-anchor, unservable and legacy switchback slots, so only a slot of the current switchback generation is reused. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 24 ++++++++++++++++++++++++ src/context.ts | 10 ++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 9a8152a..aff4db6 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1216,6 +1216,30 @@ describe("switchback serving through Context", () => { ]); }); + // A unit experiment's cached assignment shares the bare-name key with the pre-anchor, unservable and + // legacy switchback slots, so it must not be served once a refresh makes the experiment a switchback. + 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]); + } + }); + 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; diff --git a/src/context.ts b/src/context.ts index f0e51cc..05b7778 100644 --- a/src/context.ts +++ b/src/context.ts @@ -950,10 +950,12 @@ export default class Context { const hasOverride = experimentName in this._overrides; const custom = experimentName in this._cassignments ? this._cassignments[experimentName] : undefined; - // `_assign` already dropped the slots of an earlier generation (see `_dropStaleSwitchbackEpoch`). + // The bare-name slot can still hold a unit assignment from before a refresh made the experiment a + // switchback, so only a slot of this generation is reused; `_assign` drops older switchback slots. const cached: Assignment | undefined = this._assignments[cacheKey]; - if (cached !== undefined && this._isSwitchbackAssignmentCurrent(experiment, cached, hasOverride, custom)) { - return cached; + const current = cached?.switchbackGeneration === switchback.generation ? cached : undefined; + if (current !== undefined && this._isSwitchbackAssignmentCurrent(experiment, current, hasOverride, custom)) { + return current; } const assignment: Assignment = { @@ -978,7 +980,7 @@ export default class Context { // 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 = cached?.switchbackServing; + const cachedServing = current?.switchbackServing; const serving = cachedServing !== undefined && cachedServing.status !== SWITCHBACK_ABSENT ? cachedServing From 68168ff463d0390eae57ba677a8c71accc0cf5e7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 15:33:02 +0000 Subject: [PATCH 04/48] test(switchback): port java-sdk's ContextSwitchbackClusterTest; compare allow-list entries as text (FT-2537) Ports the 21 cluster-key tests and adds a split-rule revalidation counter test, which kill the four mutants the independent review found surviving. Allow-list entries now compare as text, as Java reads a JSON number in the string list. Documents that a multi-type cluster map with an array-index unit type name is served as an ineligible control. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- src/__tests__/context-switchback-keys.test.js | 591 ++++++++++++++++++ src/__tests__/switchback.test.js | 7 + src/switchback.ts | 7 +- 5 files changed, 606 insertions(+), 3 deletions(-) create mode 100644 src/__tests__/context-switchback-keys.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7999bd5..d0980a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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. +- 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 diff --git a/README.md b/README.md index 77cca44..3bf5b15 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ const variant = context.treatment("exp_delivery_fee"); // the "lisbon" cluster's 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 as its decimal text (`17` and `"17"` are the same cluster). 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. +- **Values.** A non-empty string is used as-is, and a whole number as its decimal text (`17` and `"17"` are the same cluster). 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 a number indexes an array. 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). **Ineligible cluster** (no value, units disagree, or a value outside the experiment's allowed values): variant 0 and no exposure. - **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.** diff --git a/src/__tests__/context-switchback-keys.test.js b/src/__tests__/context-switchback-keys.test.js new file mode 100644 index 0000000..51adc62 --- /dev/null +++ b/src/__tests__/context-switchback-keys.test.js @@ -0,0 +1,591 @@ +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"}]}', + }; + for (let u = 0; u < 8; ++u) { + 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(experiment.split, 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__/switchback.test.js b/src/__tests__/switchback.test.js index 7dcf297..f3bde20 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -395,6 +395,13 @@ describe("switchback serving", () => { 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, [17], both, reader({ session_store: "17" })).status).toEqual( + SWITCHBACK_ELIGIBLE + ); + expect(resolveSwitchbackServing(types, p, [null], both, reader({ session_store: "null" })).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 diff --git a/src/switchback.ts b/src/switchback.ts index 43276e1..4d7f622 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -213,7 +213,12 @@ export function resolveSwitchbackServing( function isAllowed(allowedValues: unknown, key: string) { if (allowedValues == null) return true; if (!Array.isArray(allowedValues)) return false; - return allowedValues.length === 0 || allowedValues.indexOf(key) >= 0; + if (allowedValues.length === 0) return true; + // Compared as text, as Java reads a JSON number in this string list. + for (const allowed of allowedValues) { + if (allowed != null && String(allowed) === key) return true; + } + return false; } // The Collector's path for a missing, empty or unreadable cluster map: the declared unitType only From dec9bed35e6fd3a49b329d8efc4c04d51ca73797 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 16:02:17 +0000 Subject: [PATCH 05/48] fix(switchback): admit only scalar allow-list entries; indexed loop (FT-2537) An object or array entry admits nothing. The indexed loop avoids the iterator helper Babel adds for IE 10 (+1185 bytes). Pins that a 2^32 - 1 unit type name keeps its declared position. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/switchback.test.js | 10 ++++++++++ src/switchback.ts | 9 ++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js index f3bde20..14672a2 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -402,6 +402,11 @@ describe("switchback serving", () => { 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 @@ -441,6 +446,11 @@ describe("switchback serving", () => { // 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"), + }); }); }); diff --git a/src/switchback.ts b/src/switchback.ts index 4d7f622..5a84154 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -214,9 +214,12 @@ function isAllowed(allowedValues: unknown, key: string) { if (allowedValues == null) return true; if (!Array.isArray(allowedValues)) return false; if (allowedValues.length === 0) return true; - // Compared as text, as Java reads a JSON number in this string list. - for (const allowed of allowedValues) { - if (allowed != null && String(allowed) === key) 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; } From 32ff869b1f291e4340a138b23b45ecc037e94f6d Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 16:17:07 +0000 Subject: [PATCH 06/48] test(switchback): pin epoch slot cleanup and boolean allow-list entries (FT-2537) Kills the two remaining survivors: an epoch change that left the old epoch's other period slots cached, and the boolean branch of the allow-list text comparison. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 14 ++++++++++++++ src/__tests__/switchback.test.js | 3 +++ 2 files changed, 17 insertions(+) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index aff4db6..9b5e7ad 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1240,6 +1240,20 @@ describe("switchback serving through Context", () => { } }); + // 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._assignments).sort()).toEqual(["exp_sb\u001f0", "exp_sb\u001f1"]); + + await refreshTo(context, { ...sb(2, HOUR), switchbackDesignType: "other" }); + context.treatment("exp_sb"); + expect(Object.keys(context._assignments)).toEqual(["exp_sb\u001f1"]); + }); + 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; diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js index 14672a2..1b9b1bf 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -396,6 +396,9 @@ describe("switchback serving", () => { 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 ); From c7f8f2fa49f7f35df1582704fafcc316593390d7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 16:57:12 +0000 Subject: [PATCH 07/48] fix(switchback): keep period slots apart from unit assignments; address review (FT-2537) Period slots now live in each experiment's switchback epoch instead of under a separator key in the assignment cache, so an experiment named like a slot key cannot replace one. Tests: the split-rule revalidation checks the rule's own weights with a uid where they matter; the combining-mark case has independent expected values. README/CHANGELOG state the numeric key bounds, the index rules, the unreadable-map and no-linked-unit outcomes, and that dedup holds while a period's assignment stays cached. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 10 +-- .../context-switchback-cluster.test.js | 5 +- src/__tests__/context-switchback-keys.test.js | 10 +-- src/__tests__/context-switchback.test.js | 29 +++++--- src/__tests__/switchback.test.js | 4 +- src/context.ts | 66 +++++++++++++------ 7 files changed, 84 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0980a6..f3e8e48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,4 +11,4 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### Changed -- 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 variant for the current period, and exposures are recorded once per period under the serving unit. Who moves: customers who run switchback experiments. Unit experiments and context data without switchbacks are unchanged. +- 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 variant for the current period, 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. Unit experiments and context data without switchbacks are unchanged. diff --git a/README.md b/README.md index 3bf5b15..e5075e6 100644 --- a/README.md +++ b/README.md @@ -267,11 +267,11 @@ const variant = context.treatment("exp_delivery_fee"); // the "lisbon" cluster's 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 as its decimal text (`17` and `"17"` are the same cluster). 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 a number indexes an array. 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). **Ineligible cluster** (no value, units disagree, or a value outside the experiment's allowed values): variant 0 and no exposure. +- **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. **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, under the serving unit's type, with the same fields as any other exposure. Its `exposedAt` is the time at which the call chose the period. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. +- **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. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. The schedule follows the device clock (`Date.now()`), so a device whose clock is wrong is served another period's variant. @@ -581,7 +581,7 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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 under the serving unit. Unit experiments, and context data without switchback experiments, are not affected. +**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. Unit experiments, and context data without switchback experiments, are not affected. ## About A/B Smartly diff --git a/src/__tests__/context-switchback-cluster.test.js b/src/__tests__/context-switchback-cluster.test.js index 604e484..d25dc12 100644 --- a/src/__tests__/context-switchback-cluster.test.js +++ b/src/__tests__/context-switchback-cluster.test.js @@ -136,9 +136,10 @@ function createContext(attributes, experiments, units) { // The cached "sbc" resolution at the clock's current reading (Java's switchbackResolutionForTest). function resolution(context) { - const slots = Object.keys(context._assignments).filter((key) => key === "sbc" || key.indexOf("sbc\u001f") === 0); + const periods = Object.values(context._switchbackEpochs?.sbc?.slots ?? {}); + const slots = "sbc" in context._assignments ? [context._assignments.sbc, ...periods] : periods; expect(slots.length).toEqual(1); - return context._assignments[slots[0]]; + return slots[0]; } // The Collector's ExperimentAssignment for "sbc", or null when it lists none (not applicable). Every diff --git a/src/__tests__/context-switchback-keys.test.js b/src/__tests__/context-switchback-keys.test.js index 51adc62..1375e40 100644 --- a/src/__tests__/context-switchback-keys.test.js +++ b/src/__tests__/context-switchback-keys.test.js @@ -534,13 +534,15 @@ describe("switchback cluster keys in Context", () => { unitType: "user_id", assignmentRules: '{"rules":[{"type":"split","environments":[],"percentages":"34/33/33"}]}', }; - for (let u = 0; u < 8; ++u) { + // 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(experiment.split, SEED_HI, SEED_LO) - ); + 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); diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 9b5e7ad..de4a05f 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -898,7 +898,9 @@ describe("switchback serving through Context", () => { context.treatment("exp_sb"); context.peek("exp_other"); } - expect(Object.keys(context._assignments).length).toEqual(4); + 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); }); @@ -1196,11 +1198,8 @@ describe("switchback serving through Context", () => { 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).sort()).toEqual([ - "exp_periods\u001f0", - "exp_periods\u001f1", - "exp_sb", - ]); + expect(Object.keys(context._assignments)).toEqual(["exp_sb"]); + 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)); @@ -1210,6 +1209,7 @@ describe("switchback serving through Context", () => { 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], @@ -1247,11 +1247,24 @@ describe("switchback serving through Context", () => { context.treatment("exp_sb"); clock = ANCHOR + HOUR; context.treatment("exp_sb"); - expect(Object.keys(context._assignments).sort()).toEqual(["exp_sb\u001f0", "exp_sb\u001f1"]); + 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._assignments)).toEqual(["exp_sb\u001f1"]); + 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"]); }); it("drops the slots of an earlier epoch when the same period is resolved again", async () => { diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js index 1b9b1bf..064a2a2 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -175,7 +175,9 @@ describe("switchback assigner", () => { // 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", () => { - expect(assignSwitchback("café", "0", "0", 10)).toEqual(assignSwitchback("café", "0", "0", 10)); + // 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), diff --git a/src/context.ts b/src/context.ts index 05b7778..dd76a73 100644 --- a/src/context.ts +++ b/src/context.ts @@ -118,6 +118,8 @@ type Assignment = { type SwitchbackEpoch = { generation: number; periods: number[]; + // Period index -> slot, kept apart from `_assignments` so no experiment name can collide with it. + slots: Record; }; const SWITCHBACK_RETAINED_PERIODS = 2; @@ -415,15 +417,20 @@ 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; + for (const period in slots) { + if (this._isSwitchbackSlotWithoutUnit(slots[period])) delete slots[period]; + } + } + } + for (const experimentName in this._assignments) { const assignment = this._assignments[experimentName]; - const serving = assignment.switchbackServing; - if (serving !== undefined) { - // A switchback resolved with no linked unit set is resolved again now that one may be. Unless - // overridden it published nothing, so it is dropped even when exposed. - if (serving.status === SWITCHBACK_ABSENT && (!assignment.overridden || !assignment.exposed)) { - delete this._assignments[experimentName]; - } + if (assignment.switchbackServing !== undefined) { + if (this._isSwitchbackSlotWithoutUnit(assignment)) delete this._assignments[experimentName]; continue; } if (assignment.unitType !== unitType || assignment.exposed) continue; @@ -438,6 +445,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 }; } @@ -946,13 +961,15 @@ export default class Context { const switchback = experiment.switchback as { generation: number; sources: SwitchbackSources | null }; const data = experiment.data; const periodIndex = switchback.sources !== null ? switchbackPeriodIndex(data, now) : null; - const cacheKey = periodIndex === null ? experimentName : `${experimentName}\u001f${periodIndex}`; const hasOverride = experimentName in this._overrides; const custom = experimentName in this._cassignments ? this._cassignments[experimentName] : undefined; // The bare-name slot can still hold a unit assignment from before a refresh made the experiment a // switchback, so only a slot of this generation is reused; `_assign` drops older switchback slots. - const cached: Assignment | undefined = this._assignments[cacheKey]; + const cached: Assignment | undefined = + periodIndex === null + ? this._assignments[experimentName] + : this._switchbackEpochs?.[experimentName]?.slots[periodIndex]; const current = cached?.switchbackGeneration === switchback.generation ? cached : undefined; if (current !== undefined && this._isSwitchbackAssignmentCurrent(experiment, current, hasOverride, custom)) { return current; @@ -1000,8 +1017,7 @@ export default class Context { assignment.variables = experiment.variables[assignment.variant]; } - this._assignments[cacheKey] = assignment; - this._retainSwitchbackPeriod(experimentName, switchback.generation, periodIndex); + this._retainSwitchbackSlot(experimentName, switchback.generation, periodIndex, assignment); return assignment; } @@ -1172,21 +1188,29 @@ export default class Context { const epoch = epochs[experimentName]; if (epoch === undefined || experiment?.switchback?.generation === epoch.generation) return; - for (const period of epoch.periods) { - delete this._assignments[`${experimentName}\u001f${period}`]; - } delete this._assignments[experimentName]; delete epochs[experimentName]; } - // Keeps at most SWITCHBACK_RETAINED_PERIODS period slots 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 _retainSwitchbackPeriod(experimentName: string, generation: number, periodIndex: number | null) { + // Installs a slot: the bare-name slot in `_assignments`, a period slot in its 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 + ) { const epochs = this._switchbackEpochs ?? (this._switchbackEpochs = {}); - const epoch = epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [] }); - if (periodIndex === null || epoch.periods.indexOf(periodIndex) >= 0) return; + const epoch = epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [], slots: {} }); + if (periodIndex === null) { + this._assignments[experimentName] = 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; @@ -1195,7 +1219,7 @@ export default class Context { evicted = i; } } - delete this._assignments[`${experimentName}\u001f${epoch.periods[evicted]}`]; + delete epoch.slots[epoch.periods[evicted]]; epoch.periods.splice(evicted, 1); } } From 3a78022ea14e7b73beec3f27f0b5bc91e36f44b3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 17:52:26 +0000 Subject: [PATCH 08/48] fix(switchback): serve switchbacks named like Object members (FT-2537) The epoch and slot maps have no prototype, and the switchback path reads overrides, custom assignments and the bare-name slot as own properties, so a switchback named constructor or toString no longer reads Object.prototype and throws. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 15 +++++++++++++++ src/context.ts | 18 +++++++++++++----- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index de4a05f..f98c99c 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1267,6 +1267,21 @@ describe("switchback serving through Context", () => { expect((await publishExposures(context)).map((e) => e.name)).toEqual(["exp_sb", "exp_sb\u001f0"]); }); + // The epoch map has no prototype: before it held this experiment's epoch, a switchback named like an + // Object member found Object.prototype's member and threw. + it("keeps the epoch of a switchback named like an Object member", () => { + const names = ["constructor", "toString", "hasOwnProperty", "valueOf"]; + const context = createContext(dataOf(sb(2, HOUR), ...names.map((n, i) => switchback(i + 2, n, 2, HOUR)))); + clock = ANCHOR + 10; + context.treatment("exp_sb"); + const now = clock; + for (const n of names) { + expect(() => context._assignSwitchback(n, context._index[n], now)).not.toThrow(); + expect(context._assignSwitchback(n, context._index[n], now).variant).toEqual(EXPECTED_2_ARMS[0]); + expect(Object.keys(context._switchbackEpochs[n].slots)).toEqual(["0"]); + } + }); + 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; diff --git a/src/context.ts b/src/context.ts index dd76a73..6ea3e9b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -961,14 +961,19 @@ export default class Context { const switchback = experiment.switchback as { generation: number; sources: SwitchbackSources | null }; const data = experiment.data; const periodIndex = switchback.sources !== null ? switchbackPeriodIndex(data, now) : null; - const hasOverride = experimentName in this._overrides; - const custom = experimentName in this._cassignments ? this._cassignments[experimentName] : undefined; + // 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; // The bare-name slot can still hold a unit assignment from before a refresh made the experiment a // switchback, so only a slot of this generation is reused; `_assign` drops older switchback slots. const cached: Assignment | undefined = periodIndex === null - ? this._assignments[experimentName] + ? Object.prototype.hasOwnProperty.call(this._assignments, experimentName) + ? this._assignments[experimentName] + : undefined : this._switchbackEpochs?.[experimentName]?.slots[periodIndex]; const current = cached?.switchbackGeneration === switchback.generation ? cached : undefined; if (current !== undefined && this._isSwitchbackAssignmentCurrent(experiment, current, hasOverride, custom)) { @@ -1202,8 +1207,11 @@ export default class Context { periodIndex: number | null, assignment: Assignment ) { - const epochs = this._switchbackEpochs ?? (this._switchbackEpochs = {}); - const epoch = epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [], slots: {} }); + // 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) { this._assignments[experimentName] = assignment; return; From 2cfdca097789620e86cc94a91580965cafc3fcdb Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 18:34:13 +0000 Subject: [PATCH 09/48] fix(switchback): keep the period-less slot in the epoch record too (FT-2537) The assignment cache no longer holds any switchback slot, so a switchback named __proto__ before its anchor is cached, exposes once and does not break a later unit(). The Object-member test now goes through the public API, before the anchor and in a period. Co-Authored-By: Claude Opus 5.5 --- .../context-switchback-cluster.test.js | 3 +- src/__tests__/context-switchback.test.js | 41 +++++++++++++------ src/context.ts | 36 +++++++--------- 3 files changed, 45 insertions(+), 35 deletions(-) diff --git a/src/__tests__/context-switchback-cluster.test.js b/src/__tests__/context-switchback-cluster.test.js index d25dc12..1675464 100644 --- a/src/__tests__/context-switchback-cluster.test.js +++ b/src/__tests__/context-switchback-cluster.test.js @@ -137,7 +137,8 @@ function createContext(attributes, experiments, units) { // 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 slots = "sbc" in context._assignments ? [context._assignments.sbc, ...periods] : periods; + const periodless = context._switchbackEpochs?.sbc?.periodless; + const slots = periodless !== undefined ? [periodless, ...periods] : periods; expect(slots.length).toEqual(1); return slots[0]; } diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index f98c99c..c43def6 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1198,7 +1198,8 @@ describe("switchback serving through Context", () => { 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(["exp_sb"]); + 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)); @@ -1267,18 +1268,32 @@ describe("switchback serving through Context", () => { expect((await publishExposures(context)).map((e) => e.name)).toEqual(["exp_sb", "exp_sb\u001f0"]); }); - // The epoch map has no prototype: before it held this experiment's epoch, a switchback named like an - // Object member found Object.prototype's member and threw. - it("keeps the epoch of a switchback named like an Object member", () => { - const names = ["constructor", "toString", "hasOwnProperty", "valueOf"]; - const context = createContext(dataOf(sb(2, HOUR), ...names.map((n, i) => switchback(i + 2, n, 2, HOUR)))); - clock = ANCHOR + 10; - context.treatment("exp_sb"); - const now = clock; - for (const n of names) { - expect(() => context._assignSwitchback(n, context._index[n], now)).not.toThrow(); - expect(context._assignSwitchback(n, context._index[n], now).variant).toEqual(EXPECTED_2_ARMS[0]); - expect(Object.keys(context._switchbackEpochs[n].slots)).toEqual(["0"]); + // 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"]]); } }); diff --git a/src/context.ts b/src/context.ts index 6ea3e9b..033dc5f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -113,13 +113,14 @@ type Assignment = { switchbackSilent?: boolean; }; -// The cache slots of one switchback experiment: the bare-name slot (before the anchor or with an -// unservable schedule) and at most SWITCHBACK_RETAINED_PERIODS period slots, all of one generation. +// 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[]; - // Period index -> slot, kept apart from `_assignments` so no experiment name can collide with it. slots: Record; + periodless?: Assignment; }; const SWITCHBACK_RETAINED_PERIODS = 2; @@ -424,15 +425,15 @@ export default class Context { 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.switchbackServing !== undefined) { - if (this._isSwitchbackSlotWithoutUnit(assignment)) delete this._assignments[experimentName]; - continue; - } if (assignment.unitType !== unitType || assignment.exposed) continue; const hasMissingHoldoutEntry = assignment.holdoutAssignments?.some( @@ -967,15 +968,9 @@ export default class Context { ? this._cassignments[experimentName] : undefined; - // The bare-name slot can still hold a unit assignment from before a refresh made the experiment a - // switchback, so only a slot of this generation is reused; `_assign` drops older switchback slots. - const cached: Assignment | undefined = - periodIndex === null - ? Object.prototype.hasOwnProperty.call(this._assignments, experimentName) - ? this._assignments[experimentName] - : undefined - : this._switchbackEpochs?.[experimentName]?.slots[periodIndex]; - const current = cached?.switchbackGeneration === switchback.generation ? cached : 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; } @@ -1186,18 +1181,17 @@ export default class Context { ); } - // Drops every slot of an experiment's switchback epoch (its period slots and its bare-name slot) - // once the installed definition is gone, is not a switchback or carries another generation. + // 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; - delete this._assignments[experimentName]; delete epochs[experimentName]; } - // Installs a slot: the bare-name slot in `_assignments`, a period slot in its epoch. At most + // 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. @@ -1213,7 +1207,7 @@ export default class Context { const epoch = epochs[experimentName] ?? (epochs[experimentName] = { generation, periods: [], slots: Object.create(null) }); if (periodIndex === null) { - this._assignments[experimentName] = assignment; + epoch.periodless = assignment; return; } From 1b07e095bc383ba09a44915e5bbfee11e713235f Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 18:59:15 +0000 Subject: [PATCH 10/48] fix(switchback): drop a pre-switchback unit assignment with the epoch (FT-2537) Restores the cache drop removed in 2cfdca0: a unit assignment cached before a switchback stint must not be served again, unexposed-as-new, when the experiment returns to a unit experiment or is removed while overridden (Java's dropSwitchbackEpoch clears it too). Adds the transition tests and tests for the period-less slot on unit(), the pre-anchor clock and an exposed override. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 83 ++++++++++++++++++++++++ src/context.ts | 2 + 2 files changed, 85 insertions(+) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index c43def6..20a0210 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1297,6 +1297,89 @@ describe("switchback serving through Context", () => { } }); + // 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(); + }); + 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; diff --git a/src/context.ts b/src/context.ts index 033dc5f..9c887db 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1188,6 +1188,8 @@ export default class Context { 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]; } From c6be7f7f666e798861d868085339e044f3ce4060 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 19:23:16 +0000 Subject: [PATCH 11/48] test(switchback): describe where switchback slots live in two test comments (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 20a0210..a197347 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1187,8 +1187,8 @@ describe("switchback serving through Context", () => { expect(context.pending()).toEqual(1); }); - // The unit path reads the bare-name slot, so the pre-anchor switchback slot must not survive the - // switch to a unit experiment, and no period slot outlives its epoch. + // 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; @@ -1217,8 +1217,8 @@ describe("switchback serving through Context", () => { ]); }); - // A unit experiment's cached assignment shares the bare-name key with the pre-anchor, unservable and - // legacy switchback slots, so it must not be served once a refresh makes the experiment a switchback. + // 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 }, From 4f054c4a9bf581277ca61d9c7b63ee28c0421c75 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 20:11:59 +0000 Subject: [PATCH 12/48] fix(switchback): remove invalidated period indices on late unit installation (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 16 ++++++++++++++++ src/context.ts | 9 +++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index a197347..6ce34da 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1380,6 +1380,22 @@ describe("switchback serving through Context", () => { expect(peeked._switchbackEpochs.exp_sb.periodless).toBeUndefined(); }); + it("removes invalidated period indices when a linked unit arrives", () => { + 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([]); + for (const period of [0, 1, 0]) { + clock = ANCHOR + period * HOUR; + context.treatment("exp_sb"); + } + expect(context.pending()).toEqual(2); + expect(context._switchbackEpochs.exp_sb.periods).toEqual([0, 1]); + }); + 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; diff --git a/src/context.ts b/src/context.ts index 9c887db..4ca2584 100644 --- a/src/context.ts +++ b/src/context.ts @@ -422,8 +422,13 @@ export default class Context { if (epochs !== undefined) { for (const experimentName in epochs) { const slots = epochs[experimentName].slots; - for (const period in slots) { - if (this._isSwitchbackSlotWithoutUnit(slots[period])) delete slots[period]; + const epoch = epochs[experimentName]; + for (let i = epoch.periods.length - 1; i >= 0; --i) { + const period = epoch.periods[i]; + if (slots[period] !== undefined && this._isSwitchbackSlotWithoutUnit(slots[period])) { + delete slots[period]; + epoch.periods.splice(i, 1); + } } const periodless = epochs[experimentName].periodless; if (periodless !== undefined && this._isSwitchbackSlotWithoutUnit(periodless)) { From 808516af8a326a75e3de0cf00f248e5e11f391c3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 20:55:52 +0000 Subject: [PATCH 13/48] test(switchback): pin the large-seed boundary result directly (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/switchback.test.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js index 064a2a2..a4497cc 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -140,6 +140,9 @@ describe("switchback assigner", () => { // 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; From 2dec9f667305f72c212bc8234152f4d613a7f0e8 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 00:27:11 +0000 Subject: [PATCH 14/48] fix(switchback): keep invalidated period indices retained, as Java does; port SwitchbackServerParityTest (FT-2537) Reverts 4f054c4: java-sdk's invalidateAssignmentsPinnedWithMissingUnit keeps a dropped slot's period index, so a late unit followed by a rollback re-exposes as in Java. Ports the 15 applicable cases of SwitchbackServerParityTest through the public API (killing three serving mutants) and Java's staleRuleTransitionEvaluatesTheRulesTwice. README notes that variableValue exposes a strict-mismatched switchback it visits, as for unit experiments. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../context-switchback-parity.test.js | 371 ++++++++++++++++++ src/__tests__/context-switchback.test.js | 31 +- src/context.ts | 10 +- 4 files changed, 402 insertions(+), 12 deletions(-) create mode 100644 src/__tests__/context-switchback-parity.test.js diff --git a/README.md b/README.md index e5075e6..48273a5 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,7 @@ How a switchback is served (the contract the A/B Smartly collector serves; java- - **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. **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. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. +- **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. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. As for unit experiments in this SDK, `variableValue()` exposes every experiment it reads on the key, so a strict-mismatched switchback visited before the experiment that serves the value records its control exposure too. The schedule follows the device clock (`Date.now()`), so a device whose clock is wrong is served another period's variant. diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js new file mode 100644 index 0000000..8203d29 --- /dev/null +++ b/src/__tests__/context-switchback-parity.test.js @@ -0,0 +1,371 @@ +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 is the assigner over that raw key, pinned by the golden +// vectors, and a few schedules are pinned to an independent murmur3 reference. +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 }; +} + +const collectorVariant = (key, period) => assignSwitchbackPeriod(key, period, SEED_HI, SEED_LO, ARMS); + +// 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" + ); + for (let p = 0; p < PERIODS; ++p) { + expect(collectorVariant("Lisboa", p)).toEqual([0, 1, 2, 2][p]); + expect(collectorVariant("Porto", p)).toEqual([2, 1, 0, 1][p]); + expect(collectorVariant("42", p)).toEqual([0, 2, 1, 2][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" + ); + }); + + 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 index 6ce34da..0bc451a 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -1380,20 +1380,22 @@ describe("switchback serving through Context", () => { expect(peeked._switchbackEpochs.exp_sb.periodless).toBeUndefined(); }); - it("removes invalidated period indices when a linked unit arrives", () => { + // 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([]); + 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(2); - expect(context._switchbackEpochs.exp_sb.periods).toEqual([0, 1]); + expect(context.pending()).toEqual(3); }); it("drops the slots of an earlier epoch when the same period is resolved again", async () => { @@ -1468,6 +1470,27 @@ describe("switchback serving through Context", () => { ]); }); + // 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 () => { diff --git a/src/context.ts b/src/context.ts index 4ca2584..0d85d34 100644 --- a/src/context.ts +++ b/src/context.ts @@ -422,13 +422,9 @@ export default class Context { if (epochs !== undefined) { for (const experimentName in epochs) { const slots = epochs[experimentName].slots; - const epoch = epochs[experimentName]; - for (let i = epoch.periods.length - 1; i >= 0; --i) { - const period = epoch.periods[i]; - if (slots[period] !== undefined && this._isSwitchbackSlotWithoutUnit(slots[period])) { - delete slots[period]; - epoch.periods.splice(i, 1); - } + // 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)) { From 3fdeb0ef596a96e052441b7c55e3ebdd17ec8058 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 00:44:21 +0000 Subject: [PATCH 15/48] test(switchback): an override on an ineligible cluster is recorded under the first linked unit (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback-parity.test.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js index 8203d29..b77339c 100644 --- a/src/__tests__/context-switchback-parity.test.js +++ b/src/__tests__/context-switchback-parity.test.js @@ -221,6 +221,18 @@ describe("switchback server parity", () => { ); }); + // 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."); From e7de3f273b0a7964bbb1fdd4e8dca3036190d1dc Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 08:57:42 +0000 Subject: [PATCH 16/48] docs(switchback): qualify the once-per-period cluster read with the retention condition (FT-2537) Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 48273a5..ade74d9 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,7 @@ How a switchback is served (the contract the A/B Smartly collector serves; java- - **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. **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. The cluster is read once per period: setting the attribute again later in the same period does not move the unit to another cluster, and the next period reads it again. Attributes are published as usual; the collector reads the cluster from them. As for unit experiments in this SDK, `variableValue()` exposes every experiment it reads on the key, so a strict-mismatched switchback visited before the experiment that serves the value records its control exposure too. +- **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. As for unit experiments in this SDK, `variableValue()` exposes every experiment it reads on the key, so a strict-mismatched switchback visited before the experiment that serves the value records its control exposure too. The schedule follows the device clock (`Date.now()`), so a device whose clock is wrong is served another period's variant. From c24d8286e9ab274c7302f6343f237841ee7620be Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 09:46:35 +0000 Subject: [PATCH 17/48] test(switchback): use independent reference schedules as the parity oracle (FT-2537) The parity suite derived expected variants from the SDK's own period draw; it now compares against checked-in schedules from the independent Python murmur3 reference, so a wrong draw fails 12 of its 16 tests. Co-Authored-By: Claude Opus 5.5 --- .../context-switchback-parity.test.js | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js index b77339c..d3eb35f 100644 --- a/src/__tests__/context-switchback-parity.test.js +++ b/src/__tests__/context-switchback-parity.test.js @@ -105,7 +105,22 @@ function serve(exp, units, attributes) { return { variants, exposures }; } -const collectorVariant = (key, period) => assignSwitchbackPeriod(key, period, SEED_HI, SEED_LO, ARMS); +// 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. @@ -144,10 +159,15 @@ describe("switchback server parity", () => { "Lisboa", "Lisboa" ); - for (let p = 0; p < PERIODS; ++p) { - expect(collectorVariant("Lisboa", p)).toEqual([0, 1, 2, 2][p]); - expect(collectorVariant("Porto", p)).toEqual([2, 1, 0, 1][p]); - expect(collectorVariant("42", p)).toEqual([0, 2, 1, 2][p]); + // 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), + ]); + } } }); From 3c721bc22b8fc9646a1c275743945014e3a405f3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 10:02:37 +0000 Subject: [PATCH 18/48] test(switchback): describe the parity suite's reference schedules (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback-parity.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js index d3eb35f..81fc956 100644 --- a/src/__tests__/context-switchback-parity.test.js +++ b/src/__tests__/context-switchback-parity.test.js @@ -16,8 +16,8 @@ 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 is the assigner over that raw key, pinned by the golden -// vectors, and a few schedules are pinned to an independent murmur3 reference. +// it records nothing; the expected variant comes from REFERENCE_SCHEDULES, computed by an independent +// murmur3 reference, never by the SDK. const HOUR = 3600000; const ANCHOR = 1767225600000; const PERIODS = 4; From 52448cf30f8d1af2dd1df0c335b96cba0f975c14 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 10:11:38 +0000 Subject: [PATCH 19/48] docs(switchback): note that an override still applies to an ineligible cluster (FT-2537) Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ade74d9..d0dd63e 100644 --- a/README.md +++ b/README.md @@ -269,7 +269,7 @@ How a switchback is served (the contract the A/B Smartly collector serves; java- - **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. **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. +- **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. As for unit experiments in this SDK, `variableValue()` exposes every experiment it reads on the key, so a strict-mismatched switchback visited before the experiment that serves the value records its control exposure too. From a3f511971fbd9f238d102b26d67018209b58c8da Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 10:38:36 +0000 Subject: [PATCH 20/48] test(switchback): drop the repeated reference explanation from the parity header (FT-2537) Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback-parity.test.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/__tests__/context-switchback-parity.test.js b/src/__tests__/context-switchback-parity.test.js index 81fc956..e36a6aa 100644 --- a/src/__tests__/context-switchback-parity.test.js +++ b/src/__tests__/context-switchback-parity.test.js @@ -16,8 +16,7 @@ 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, computed by an independent -// murmur3 reference, never by the SDK. +// it records nothing; the expected variant comes from REFERENCE_SCHEDULES. const HOUR = 3600000; const ANCHOR = 1767225600000; const PERIODS = 4; From 9558ec55b0fc9da0647dc7ae7a7baf1591510e68 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 17:07:13 +0000 Subject: [PATCH 21/48] fix(context): keep shared variable winner independent of switchback arm Version-neutral counterpart of release PR #70 for switchbacks PR #69. Preserve clock and exposure behavior; a missing key on the first winning candidate returns the caller default instead of falling through by arm. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 98 ++++++++++++++++++++++++++++++----- src/context.ts | 6 ++- 2 files changed, 90 insertions(+), 14 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7497958..ffd1544 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6140,13 +6140,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 +6157,7 @@ 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. + // The override wins outright, even though variant 0 omits the key. { name: "A", config: null }, { name: "B", config: JSON.stringify({ "button.color": "OVERRIDE_SIBLING" }) }, ], @@ -6204,13 +6199,14 @@ 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", () => { + 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 +6262,90 @@ 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); + }); + + it("retains ordinary unassigned fallthrough and no-winner defaults", () => { + const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); + const second = shared(2, [1, 0], { shared: "SECOND" }); + const context = new Context(sdk, contextOptions, contextParams, { experiments: [first, second] }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + // Existing exposure behavior for visited unassigned candidates is preserved. + expect(context.pending()).toBe(2); + const noWinner = new Context(sdk, contextOptions, contextParams, { experiments: [first] }); + expect(noWinner.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(noWinner.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(noWinner.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + }); + }); + describe("variableValue()", () => { it("should not return variable values when unassigned", (done) => { const context = new Context(sdk, contextOptions, contextParams, audienceStrictContextResponse); diff --git a/src/context.ts b/src/context.ts index 0d85d34..46f7161 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1421,8 +1421,10 @@ export default class Context { this._triggerExposures(experimentName, assignment, now); } - if (key in assignment.variables && (assignment.assigned || assignment.overridden || assignment.ruleOverride)) { - return assignment.variables[key] as string; + // Select the experiment independently of its arm: a missing key uses the caller's + // default, never a later experiment (which would bias exposure by variant). + if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { + return key in assignment.variables ? (assignment.variables[key] as string) : defaultValue; } if ( From 3617447144fac4d52047684629b5ff24d00599cb Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 01:25:43 +0000 Subject: [PATCH 22/48] fix(context): expose only the winning experiment for shared variable keys Match java-sdk Context.getVariableAssignment for unit and switchback experiments alike: pick the first candidate (by experiment id) the unit is in, whatever its arm, falling back to the first held-out candidate; expose only that one at the single resolution instant, firing each checked candidate's applicable holdouts as Java does. A strict-mismatched switchback that is checked but loses is no longer exposed. Version-neutral counterpart of release PR #70 (gated at 2ceac72). Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 6 +- src/__tests__/context.test.js | 169 ++++++++++++++++------- src/context.ts | 60 ++++---- 3 files changed, 158 insertions(+), 77 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 0bc451a..8211211 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -777,9 +777,8 @@ describe("switchback serving through Context", () => { expect(context.peekVariableValue("sb.arm", -1)).toEqual(11); expect(context.pending()).toEqual(0); expect(context.variableValue("sb.arm", -1)).toEqual(11); - // Like a unit experiment on the key, the strict-mismatched switchback visited first is exposed too. + // Only the winner is exposed: the strict-mismatched switchback checked first is not. expect(await publishExposures(context)).toEqual([ - strictMismatchExposure(ANCHOR + HOUR + 3), exposure(2, "exp_unit", 1, ANCHOR + HOUR + 3, true, true, { fullOn: true }), ]); }); @@ -998,8 +997,9 @@ describe("switchback serving through Context", () => { nextRead = ANCHOR + HOUR - 1; expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[0]); + // The strict-mismatched first experiment is resolved at the same instant but, not being + // the winner, is not exposed. expect(await publishExposures(context)).toEqual([ - exposure(1, "exp_first", 0, ANCHOR + HOUR - 1, false, true, { audienceMismatch: true }), exposure(2, "exp_second", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true), ]); }); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index ffd1544..c645267 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6330,19 +6330,124 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); - it("retains ordinary unassigned fallthrough and no-winner defaults", () => { - const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); - const second = shared(2, [1, 0], { shared: "SECOND" }); - const context = new Context(sdk, contextOptions, contextParams, { experiments: [first, second] }); - expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + 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(); + const first = shared(1, [1, 0], {}, 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("SECOND"); - // Existing exposure behavior for visited unassigned candidates is preserved. - expect(context.pending()).toBe(2); - const noWinner = new Context(sdk, contextOptions, contextParams, { experiments: [first] }); - expect(noWinner.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(noWinner.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(noWinner.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_1", variant: 7 })]); }); }); @@ -6719,46 +6824,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/context.ts b/src/context.ts index 46f7161..371b574 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1404,45 +1404,53 @@ 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 indexed = this._indexVariables[key]; + // Own lists only: a key such as "toString" must not resolve an Object.prototype member. + const candidates = Array.isArray(indexed) ? indexed : []; + + // 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; - for (const experiment of this._indexVariables[key] ?? []) { + for (const experiment of candidates) { const experimentName = experiment.data.name; now = this._switchbackClock(experimentName, now); const assignment = this._assign(experimentName, now); - if (assignment.variables !== undefined) { - if (shouldQueueExposure && !assignment.exposed) { - assignment.exposed = true; - - this._triggerExposures(experimentName, assignment, now); - } + if (shouldQueueExposure) this._triggerApplicableHoldoutExposures(assignment); - // Select the experiment independently of its arm: a missing key uses the caller's - // default, never a later experiment (which would bias exposure by variant). - if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { - return key in assignment.variables ? (assignment.variables[key] as string) : defaultValue; - } + if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { + selectedName = experimentName; + selected = assignment; + break; + } - if ( - assignment.suppressed && - !assignment.overridden && - !assignment.ruleOverride && - suppressedFallback === undefined - ) { - suppressedFallback = assignment.variables; - } + // A winner breaks out above, so `selected` here can only be an earlier suppressed one. + if (assignment.suppressed && selected === undefined) { + selectedName = experimentName; + selected = assignment; } } - if (suppressedFallback !== undefined && key in suppressedFallback) { - return suppressedFallback[key] as string; + if (selected === undefined) return defaultValue; + + if (shouldQueueExposure && !selected.exposed) { + selected.exposed = true; + + this._triggerExposures(selectedName, selected, now); } - return defaultValue; + // 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; } private _variableValue(key: string, defaultValue: string): string { From 8135d2a2e03ae2f24423dc7b64043a5e43d61af6 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 04:48:36 +0000 Subject: [PATCH 23/48] docs: document shared variable key winner and exposure rule Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3e8e48..d274a7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,4 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. Keys named like `Object.prototype` members (`toString`, ...) return the default. 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 variant for the current period, 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. Unit experiments and context data without switchbacks are unchanged. diff --git a/README.md b/README.md index d0dd63e..6f3ce18 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,18 @@ 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, that +experiment's control value is returned. Only that experiment gets an exposure +(plus any holdouts covering the experiments checked). An experiment the user is +not in, such as a strict audience mismatch, gets none; call `treatment()` to +record it. `peekVariableValue()` never queues one. + ### 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. From 4e745c45226381037ab0d3d061c845bc8e1beb5c Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 06:05:50 +0000 Subject: [PATCH 24/48] test,docs: pin a silent switchback winner; align docs with winner-only exposure Address the independent review of 8135d2a: a silent (pre-schedule) switchback that wins a shared key serves control with no exposure and no fallthrough; README switchback text and Migration Guide describe the new rule; CHANGELOG narrows the prototype-key claim; stale test comments updated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 13 ++++++++++--- src/__tests__/context-switchback.test.js | 18 ++++++++++++++++++ src/__tests__/context.test.js | 18 ++++++++---------- 4 files changed, 37 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d274a7e..d4a92af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. Keys named like `Object.prototype` members (`toString`, ...) return the default. 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). +- 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. Keys no experiment defines return the default, including names like `toString` or `__proto__`, which threw before. 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 variant for the current period, 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. Unit experiments and context data without switchbacks are unchanged. diff --git a/README.md b/README.md index 6f3ce18..5764bb3 100644 --- a/README.md +++ b/README.md @@ -228,8 +228,9 @@ 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, that -experiment's control value is returned. Only that experiment gets an exposure -(plus any holdouts covering the experiments checked). An experiment the user is +experiment's control value is returned. 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. `peekVariableValue()` never queues one. @@ -283,7 +284,7 @@ How a switchback is served (the contract the A/B Smartly collector serves; java- - **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. As for unit experiments in this SDK, `variableValue()` exposes every experiment it reads on the key, so a strict-mismatched switchback visited before the experiment that serves the value records its control exposure too. +- **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. @@ -595,6 +596,12 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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. Unit experiments, and context data without switchback experiments, are not affected. +### 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 (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.test.js b/src/__tests__/context-switchback.test.js index 8211211..fad37c1 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -783,6 +783,24 @@ describe("switchback serving through Context", () => { ]); }); + // 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; diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index c645267..0b3cfa1 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6025,10 +6025,10 @@ 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", () => { + // A throwing eventLogger for one candidate's holdout exposure is isolated by _logEvent (it + // never propagates), so it must not stop the loop from visiting the remaining candidates + // sharing the key or exposing the winner. + it("a throwing eventLogger for one candidate does not stop the loop from reaching and exposing the winner", () => { const firstExperiment = holdoutVarExperiment({ id: 1, name: "exp_holdout_var_throw_first", @@ -6063,9 +6063,8 @@ describe("Context", () => { ); }); - // 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. + // 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, @@ -6203,9 +6202,8 @@ describe("Context", () => { 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. + // 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, From e4f5d5c4024dce22af0efb21c1e42a1f1555f0d5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 06:36:42 +0000 Subject: [PATCH 25/48] fix(context): accept variables named like Object.prototype members A variant config defining "toString", "constructor" or "__proto__" crashed context initialization. Index variables and parse configs into null-prototype maps, build variableKeys() with own properties, and pin an out-of-range winner returning the default even when control defines the key. Also correct the CHANGELOG prototype-key claim and rewrap the README note. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 6 ++-- src/__tests__/context.test.js | 52 ++++++++++++++++++++++++++++++++++- src/context.ts | 24 +++++++++------- 4 files changed, 69 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4a92af..f64e898 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. Keys no experiment defines return the default, including names like `toString` or `__proto__`, which threw before. 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). +- 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. 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 variant for the current period, 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. Unit experiments and context data without switchbacks are unchanged. diff --git a/README.md b/README.md index 5764bb3..fc33461 100644 --- a/README.md +++ b/README.md @@ -230,9 +230,9 @@ default if that variant does not define the key; later experiments are never use instead. If the user is in none of them but one is held out by a holdout, that experiment's control value is returned. 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. `peekVariableValue()` never queues one. +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. `peekVariableValue()` never queues one. ### Peek at Treatment Variants diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 0b3cfa1..8045016 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6328,6 +6328,55 @@ describe("Context", () => { 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("returns the default when the winner's variant does not define the key", () => { + // Variant A has a parsed config without these keys, so inherited members must not match. + const winner = { ...protoKeyed(config), split: [1, 0] }; + winner.variants = [{ name: "A", config: '{"other":1}' }, 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("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) => { @@ -6436,7 +6485,8 @@ describe("Context", () => { it.each(["override", "custom", "fullOn"])("exposes an out-of-range %s winner like Java", (mode) => { const eventLogger = jest.fn(); - const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); + // 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" })], }); diff --git a/src/context.ts b/src/context.ts index 371b574..43783f3 100644 --- a/src/context.ts +++ b/src/context.ts @@ -538,11 +538,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; @@ -1411,9 +1414,8 @@ export default class Context { // 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 { - const indexed = this._indexVariables[key]; - // Own lists only: a key such as "toString" must not resolve an Object.prototype member. - const candidates = Array.isArray(indexed) ? indexed : []; + // The index has no prototype, so a key such as "toString" only finds a real entry. + const candidates = this._indexVariables[key] ?? []; // Plain locals rather than tuples: this is a hot path and must not allocate per read. let selectedName = ""; @@ -1858,7 +1860,9 @@ export default class Context { this._environmentName = this._sdk.getClient().getEnvironment() ?? null; const index: Record = {}; - const indexVariables: Record = {}; + // Null-prototype maps: variable keys come from customer configs and may be named like + // Object.prototype members ("toString", "__proto__"). + const indexVariables: Record = Object.create(null); const holdoutsById: Record = {}; @@ -1935,13 +1939,13 @@ export default class Context { for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; - let parsed = {}; + let parsed: Record = Object.create(null); if (config != null && config.length > 0) { try { const value = JSON.parse(config); if (isObject(value)) { - parsed = value; + parsed = Object.assign(Object.create(null), value); } } catch (error) { this._logError( From 3800b663134b030c4fc5150b5b38a0b228280185 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 07:17:25 +0000 Subject: [PATCH 26/48] test(context): cover empty and non-object configs with prototype-named variables Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 8045016..4cc08e6 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6353,17 +6353,20 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); - it("returns the default when the winner's variant does not define the key", () => { - // Variant A has a parsed config without these keys, so inherited members must not match. - const winner = { ...protoKeyed(config), split: [1, 0] }; - winner.variants = [{ name: "A", config: '{"other":1}' }, 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"); + it.each([null, "", "[]", "0", "false", '"string"', "null", '{"other":1}'])( + "returns the default when the winner config %p does not define the key", + (selectedConfig) => { + // No selected config shape may leak inherited Object.prototype members. + 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); } - expect(context.pending()).toBe(1); - }); + ); it("lists each key as an own entry of variableKeys()", () => { const context = new Context(sdk, contextOptions, contextParams, { From bd0ba5ad5686c6a77162b4ee90d197052b893057 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 07:23:04 +0000 Subject: [PATCH 27/48] perf(context): retain ordinary object layouts with safe own-key lookup Define index entries as own properties, including __proto__, and require an own variant config key on reads. Avoid dictionary-mode maps for all ordinary reads. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/context.ts b/src/context.ts index 43783f3..466a582 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1414,8 +1414,8 @@ export default class Context { // 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 { - // The index has no prototype, so a key such as "toString" only finds a real entry. - const candidates = this._indexVariables[key] ?? []; + const indexed = this._indexVariables[key]; + const candidates = Array.isArray(indexed) ? indexed : []; // Plain locals rather than tuples: this is a hot path and must not allocate per read. let selectedName = ""; @@ -1452,7 +1452,9 @@ export default class Context { // 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; + return variables !== undefined && Object.prototype.hasOwnProperty.call(variables, key) + ? (variables[key] as string) + : defaultValue; } private _variableValue(key: string, defaultValue: string): string { @@ -1860,9 +1862,7 @@ export default class Context { this._environmentName = this._sdk.getClient().getEnvironment() ?? null; const index: Record = {}; - // Null-prototype maps: variable keys come from customer configs and may be named like - // Object.prototype members ("toString", "__proto__"). - const indexVariables: Record = Object.create(null); + const indexVariables: Record = {}; const holdoutsById: Record = {}; @@ -1939,13 +1939,13 @@ export default class Context { for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; - let parsed: Record = Object.create(null); + let parsed: Record = {}; if (config != null && config.length > 0) { try { const value = JSON.parse(config); if (isObject(value)) { - parsed = Object.assign(Object.create(null), value); + parsed = value; } } catch (error) { this._logError( @@ -1958,13 +1958,20 @@ export default class Context { for (const key of Object.keys(parsed)) { 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; From e60fe39064a1dd850f6e9c7fa2563ec850111a23 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 09:12:51 +0000 Subject: [PATCH 28/48] perf(context): restrict own-key checks to prototype-named variables Ordinary keys retain the fast membership path; prototype-named keys must be own config properties. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/context.ts b/src/context.ts index 466a582..b258347 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1452,7 +1452,9 @@ export default class Context { // 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 && Object.prototype.hasOwnProperty.call(variables, key) + return variables !== undefined && + key in variables && + (!(key in Object.prototype) || Object.prototype.hasOwnProperty.call(variables, key)) ? (variables[key] as string) : defaultValue; } From 2aa9a2df4a3b636375edae8df077bd10fd5a6b32 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 09:44:52 +0000 Subject: [PATCH 29/48] docs: qualify switchback-only unchanged-unit claim P3-only follow-up on top of gated e60fe39064a1dd850f6e9c7fa2563ec850111a23. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f64e898..67084dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,4 +12,4 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. 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 variant for the current period, 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. Unit experiments and context data without switchbacks are unchanged. +- 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 variant for the current period, 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 fc33461..a94c611 100644 --- a/README.md +++ b/README.md @@ -594,7 +594,7 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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. Unit experiments, and context data without switchback experiments, are not affected. +**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 From 1f1363ffeced9327ae221b286ad39b4d5d55a7e7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 10:00:31 +0000 Subject: [PATCH 30/48] perf(context): classify prototype-key configs at indexing time Keep ordinary variable reads on the fast membership path; only experiments defining prototype-named keys require null-prototype variant maps. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/context.ts b/src/context.ts index b258347..5453dde 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1452,11 +1452,7 @@ export default class Context { // 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 && - (!(key in Object.prototype) || Object.prototype.hasOwnProperty.call(variables, key)) - ? (variables[key] as string) - : defaultValue; + return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } private _variableValue(key: string, defaultValue: string): string { @@ -1938,6 +1934,7 @@ export default class Context { 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; @@ -1959,6 +1956,7 @@ export default class Context { } for (const key of Object.keys(parsed)) { + if (key in Object.prototype) hasPrototypeVariable = true; const value = entry; if (Array.isArray(indexVariables[key])) { insertUniqueSorted( @@ -1978,6 +1976,14 @@ export default class Context { 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]); + } + } }); this._index = index; From 8508df6dd89fb2e3254c45aa48bbe900b13719b7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 10:12:47 +0000 Subject: [PATCH 31/48] fix(context): queue every exposure of a variable read before user callbacks run A holdout exposure callback that called finalize() sealed the context with the winner still pending. Queue the read's exposures first and run eventLogger callbacks afterwards. Make the throwing-logger test reach and expose a real winner, return the default early for an unindexed key, and document silent switchback winners and the cluster-variant serving order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +-- README.md | 7 ++-- src/__tests__/context.test.js | 68 +++++++++++++++++++++++------------ src/context.ts | 31 ++++++++++++++-- 4 files changed, 81 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67084dd..56dc384 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. 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 variant for the current period, 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. +- 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. 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, once an override, assignment rule, strict audience, full-on setting or traffic check has not decided the variant, each unit gets its cluster's scheduled variant for the current period, 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 a94c611..bee4564 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,10 @@ experiment's control value is returned. 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. `peekVariableValue()` never queues one. +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 @@ -600,7 +603,7 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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 (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. +**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 diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 4cc08e6..4a6fd4b 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6025,24 +6025,23 @@ describe("Context", () => { expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); }); - // A throwing eventLogger for one candidate's holdout exposure is isolated by _logEvent (it - // never propagates), so it must not stop the loop from visiting the remaining candidates - // sharing the key or exposing the winner. - it("a throwing eventLogger for one candidate does not stop the loop from reaching and exposing the winner", () => { - const firstExperiment = holdoutVarExperiment({ - id: 1, - name: "exp_holdout_var_throw_first", - holdoutIds: [11], - }); - - const secondExperiment = holdoutVarExperiment({ - id: 2, - name: "exp_holdout_var_throw_second", - holdoutIds: [12], - }); - - const secondHoldout = alwaysHoldsOut({ id: 12, name: "holdout_var_second" }); + 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"); @@ -6050,17 +6049,42 @@ describe("Context", () => { }); const response = buildHoldoutResponse( - [firstExperiment, secondExperiment], - [alwaysHoldsOut({}), secondHoldout] + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] ); const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); - expect(() => context.variableValue("button.color", "APP_FALLBACK")).not.toThrow(); + 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).sort()).toEqual( - ["holdout_var", "holdout_var_second"].sort() + 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 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"]); }); // peekVariableValue() picks the same first held-out fallback as variableValue() but never diff --git a/src/context.ts b/src/context.ts index 5453dde..66fdf30 100644 --- a/src/context.ts +++ b/src/context.ts @@ -239,6 +239,8 @@ export default class Context { private _holdoutAssignments: Record; private _overrides: Record; private _pending: number; + // Set while a variable read queues its exposures, so user callbacks run only after all are queued. + private _deferredExposureLogs?: Exposure[]; private _attrsSeq: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; @@ -1310,6 +1312,11 @@ export default class Context { this._exposures.push(exposureEvent); this._pending++; + if (this._deferredExposureLogs !== undefined) { + this._deferredExposureLogs.push(exposureEvent); + return; + } + try { this._logEvent("exposure", exposureEvent); } finally { @@ -1414,8 +1421,8 @@ export default class Context { // 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 { - const indexed = this._indexVariables[key]; - const candidates = Array.isArray(indexed) ? indexed : []; + 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 = ""; @@ -1455,8 +1462,26 @@ export default class Context { return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } + // A user eventLogger may call finalize() or publish(). Every exposure this read produces (the + // candidates' holdouts and the winner) is queued before any logger runs, so such a call sees + // and sends all of them instead of sealing the context with the winner still pending. private _variableValue(key: string, defaultValue: string): string { - return this._resolveVariableValue(key, defaultValue, true); + if (this._deferredExposureLogs !== undefined) return this._resolveVariableValue(key, defaultValue, true); + + const deferred: Exposure[] = []; + this._deferredExposureLogs = deferred; + try { + return this._resolveVariableValue(key, defaultValue, true); + } finally { + this._deferredExposureLogs = undefined; + if (deferred.length > 0) { + try { + for (const exposure of deferred) this._logEvent("exposure", exposure); + } finally { + this._setTimeout(); + } + } + } } private _peekVariable(key: string, defaultValue: string): string { From 37be5be762ee37591d19d270b288749285670d9d Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 11:58:19 +0000 Subject: [PATCH 32/48] fix(context): defer variable-read callbacks without per-read cost; reclassify after refresh Create the deferred callback list only when a read queues an exposure or error, and defer error callbacks too, so finalize() from either still sends the winner without slowing warmed reads. After a refresh, a reused assignment of a newly prototype-keyed experiment gets a null-prototype copy of its variables. Pin toString-only classification, ordinary configs keeping Object.prototype, the publish timer, nested re-entrant reads and error-callback finalize. Complete the switchback precedence list in the CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/__tests__/context.test.js | 151 ++++++++++++++++++++++++++++++++++ src/context.ts | 52 +++++++++--- 3 files changed, 191 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56dc384..fe97592 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,4 +12,4 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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. 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, once an override, assignment rule, strict audience, full-on setting or traffic check has not decided the variant, each unit gets its cluster's scheduled variant for the current period, 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. +- 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/src/__tests__/context.test.js b/src/__tests__/context.test.js index 4a6fd4b..79bae94 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,6 +6087,116 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); + it("reports nested variable reads from a callback after the outer read's exposures, in queue order", () => { + 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("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); + }); + + 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", () => { @@ -6392,6 +6502,47 @@ describe("Context", () => { } ); + 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("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" }], diff --git a/src/context.ts b/src/context.ts index 66fdf30..e6a526b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -239,8 +239,10 @@ export default class Context { private _holdoutAssignments: Record; private _overrides: Record; private _pending: number; - // Set while a variable read queues its exposures, so user callbacks run only after all are queued. - private _deferredExposureLogs?: Exposure[]; + // 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 _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; @@ -1312,8 +1314,8 @@ export default class Context { this._exposures.push(exposureEvent); this._pending++; - if (this._deferredExposureLogs !== undefined) { - this._deferredExposureLogs.push(exposureEvent); + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["exposure", exposureEvent]); return; } @@ -1462,21 +1464,25 @@ export default class Context { return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } - // A user eventLogger may call finalize() or publish(). Every exposure this read produces (the - // candidates' holdouts and the winner) is queued before any logger runs, so such a call sees - // and sends all of them instead of sealing the context with the winner still pending. + // 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. private _variableValue(key: string, defaultValue: string): string { - if (this._deferredExposureLogs !== undefined) return this._resolveVariableValue(key, defaultValue, true); + if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); - const deferred: Exposure[] = []; - this._deferredExposureLogs = deferred; + this._deferringLogs = true; try { return this._resolveVariableValue(key, defaultValue, true); } finally { - this._deferredExposureLogs = undefined; - if (deferred.length > 0) { + this._deferringLogs = false; + const deferred = this._deferredLogs; + if (deferred !== undefined) { + this._deferredLogs = undefined; try { - for (const exposure of deferred) this._logEvent("exposure", exposure); + for (const [eventName, data] of deferred) { + if (eventName === "error") this._logError(data as Error); + else this._logEvent(eventName, data as Record); + } } finally { this._setTimeout(); } @@ -1812,6 +1818,10 @@ export default class Context { } private _logError(error: Error) { + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["error", error]); + return; + } if (this._eventLogger) { try { this._eventLogger(this, "error", error); @@ -2011,6 +2021,22 @@ export default class Context { } }); + // A reused assignment still points at the previous parse of its configs; if a refresh made + // the experiment prototype-keyed, its cached variables must not resolve inherited members. + for (const experimentName of Object.keys(assignments)) { + const assignment = assignments[experimentName]; + const variables = assignment.variables; + const experiment = index[experimentName]; + if ( + variables !== undefined && + Object.getPrototypeOf(variables) !== null && + experiment !== undefined && + Object.getPrototypeOf(experiment.variables[0] ?? {}) === null + ) { + assignment.variables = Object.assign(Object.create(null), variables); + } + } + this._index = index; this._indexVariables = indexVariables; this._assignments = assignments; From c4f73b841a46081baeff666e2ff95885ea9e30b2 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 13:37:03 +0000 Subject: [PATCH 33/48] perf(context): outline the deferred-callback replay; fix refresh and treatment edge cases Move the replay of a read's held callbacks into its own method with an indexed loop, and arm the publish timer only when an exposure was replayed. treatment() also queues its holdout exposures before callbacks run. The refresh reclassification looks experiments up as own properties and also covers cached switchback period slots. Document callback timing and cost. Pin the lazy list, replay order, error-only reads, retained values, ordinary snapshots, prototype-named experiments and switchback slots across refresh. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/__tests__/context-switchback.test.js | 18 ++++ src/__tests__/context.test.js | 124 +++++++++++++++++++++++ src/context.ts | 82 ++++++++++----- 4 files changed, 202 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe97592..9438676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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. 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). +- 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 (and a `treatment()` with holdouts) queues all its exposures before its `exposure` and `error` callbacks run, so a callback that calls `finalize()` or `publish()` sends every one of them; such a callback now sees them already pending. A cached `variableValue()` costs about 5 ns more than before for that. 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/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index fad37c1..e4daf21 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -785,6 +785,24 @@ describe("switchback serving through Context", () => { // 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. + // 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); + } + }); + 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)); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 79bae94..e9f1c61 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6156,6 +6156,93 @@ describe("Context", () => { ]); }); + 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 flush = jest.spyOn(context, "_flushDeferredLogs"); + for (let i = 0; i < 5; i++) context.variableValue("button.color", "APP_FALLBACK"); + expect(flush).not.toHaveBeenCalled(); + 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_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"]); + }); + + 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("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); @@ -6513,6 +6600,43 @@ describe("Context", () => { expect(context.variableValue("toString", "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" }], diff --git a/src/context.ts b/src/context.ts index e6a526b..06d497b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1243,7 +1243,19 @@ export default class Context { if (!assignment.exposed) { assignment.exposed = true; - this._triggerExposures(experimentName, assignment, now); + // 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._deferringLogs = false; + if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + } + } } return assignment; @@ -1467,6 +1479,7 @@ export default class Context { // 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); @@ -1475,18 +1488,28 @@ export default class Context { return this._resolveVariableValue(key, defaultValue, true); } finally { this._deferringLogs = false; - const deferred = this._deferredLogs; - if (deferred !== undefined) { - this._deferredLogs = undefined; - try { - for (const [eventName, data] of deferred) { - if (eventName === "error") this._logError(data as Error); - else this._logEvent(eventName, data as Record); - } - } finally { - this._setTimeout(); + if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + } + } + + private _flushDeferredLogs() { + const deferred = this._deferredLogs as [EventName, Record | Error][]; + this._deferredLogs = undefined; + + let exposed = false; + try { + for (let i = 0; i < deferred.length; i++) { + const entry = deferred[i]; + if (entry[0] === "error") { + this._logError(entry[1] as Error); + } else { + exposed = true; + this._logEvent(entry[0], entry[1] as Record); } } + } finally { + // Only exposures need publishing; an error alone must not arm the timer. + if (exposed) this._setTimeout(); } } @@ -2021,20 +2044,33 @@ export default class Context { } }); - // A reused assignment still points at the previous parse of its configs; if a refresh made - // the experiment prototype-keyed, its cached variables must not resolve inherited members. - for (const experimentName of Object.keys(assignments)) { - const assignment = assignments[experimentName]; - const variables = assignment.variables; - const experiment = index[experimentName]; - if ( - variables !== undefined && - Object.getPrototypeOf(variables) !== null && - experiment !== undefined && - Object.getPrototypeOf(experiment.variables[0] ?? {}) === null - ) { + // 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]); + } } this._index = index; From 20cc4c76fbe94b01b798d1fef8e47e1328bb7071 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 13:54:22 +0000 Subject: [PATCH 34/48] refactor(context): skip the winner's second holdout walk; tidy shared-key docs The resolver loop already fires every visited candidate's holdouts, including the winner's, so its exposure no longer walks the snapshot again. Drop comments that restated nearby assertions or control flow and reflow the README note. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +++++++------- src/__tests__/context-switchback.test.js | 3 --- src/__tests__/context.test.js | 1 - src/context.ts | 8 ++++---- 4 files changed, 11 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index bee4564..9009759 100644 --- a/README.md +++ b/README.md @@ -226,16 +226,16 @@ const buttonColor = context.variableValue("button.color", defaultButtonColor); 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, that -experiment's control value is returned. Only the winning experiment gets an +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, +that experiment's control value is returned. 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. +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 diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index e4daf21..fc92ab0 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -777,7 +777,6 @@ describe("switchback serving through Context", () => { expect(context.peekVariableValue("sb.arm", -1)).toEqual(11); expect(context.pending()).toEqual(0); expect(context.variableValue("sb.arm", -1)).toEqual(11); - // Only the winner is exposed: the strict-mismatched switchback checked first is not. expect(await publishExposures(context)).toEqual([ exposure(2, "exp_unit", 1, ANCHOR + HOUR + 3, true, true, { fullOn: true }), ]); @@ -1033,8 +1032,6 @@ describe("switchback serving through Context", () => { nextRead = ANCHOR + HOUR - 1; expect(context.variableValue("sb.arm", -1)).toEqual(EXPECTED_2_ARMS[0]); - // The strict-mismatched first experiment is resolved at the same instant but, not being - // the winner, is not exposed. expect(await publishExposures(context)).toEqual([ exposure(2, "exp_second", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true), ]); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index e9f1c61..ca07bef 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6377,7 +6377,6 @@ describe("Context", () => { fullOnVariant: 0, applications: [{ name: "website" }], variants: [ - // The override wins outright, even though variant 0 omits the key. { name: "A", config: null }, { name: "B", config: JSON.stringify({ "button.color": "OVERRIDE_SIBLING" }) }, ], diff --git a/src/context.ts b/src/context.ts index 06d497b..b5b0909 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1272,7 +1272,7 @@ export default class Context { // 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): void { + private _triggerExposures(experimentName: string, assignment: Assignment, now?: number, withHoldouts = true): void { if (assignment.switchbackGeneration !== undefined) { if (!assignment.switchbackSilent) { this._queueExposure(experimentName, assignment, now); @@ -1284,7 +1284,7 @@ export default class Context { 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 @@ -1455,7 +1455,6 @@ export default class Context { break; } - // A winner breaks out above, so `selected` here can only be an earlier suppressed one. if (assignment.suppressed && selected === undefined) { selectedName = experimentName; selected = assignment; @@ -1467,7 +1466,8 @@ export default class Context { if (shouldQueueExposure && !selected.exposed) { selected.exposed = true; - this._triggerExposures(selectedName, selected, now); + // The loop above already fired this candidate's holdouts. + this._triggerExposures(selectedName, selected, now, false); } // A missing key (or out-of-range arm) returns the caller's default, never a later From 91a389268a383093680b0fde6b5286467746eb43 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:10:58 +0000 Subject: [PATCH 35/48] fix(context): replay deferred callbacks in queue order under one deferral owner Keep deferral on while replaying so callbacks raised by a nested read or treatment() follow the ones already queued, and let _endDeferral own the flag for both variableValue() and treatment(). Pin treatment() re-entered from an attribute getter mid-read, nested treatment() from an exposure callback, nested-read queue order and the lazy list via a setter spy. State the cached variableValue()/peekVariableValue() cost against 1.13.4 and unreleased main. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 113 +++++++++++++++++++++++++++++++++- src/context.ts | 42 ++++++++----- 2 files changed, 138 insertions(+), 17 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index ca07bef..e7baf24 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6163,9 +6163,18 @@ describe("Context", () => { clearTimeout(context._publishTimeout); context._publishTimeout = undefined; const schedule = jest.spyOn(context, "_setTimeout"); - const flush = jest.spyOn(context, "_flushDeferredLogs"); + 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(flush).not.toHaveBeenCalled(); + expect(lists).toEqual([]); expect(schedule).not.toHaveBeenCalled(); }); @@ -6243,6 +6252,106 @@ describe("Context", () => { ); }); + 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") 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("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); diff --git a/src/context.ts b/src/context.ts index b5b0909..53da867 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1252,8 +1252,7 @@ export default class Context { try { this._triggerExposures(experimentName, assignment, now); } finally { - this._deferringLogs = false; - if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + this._endDeferral(); } } } @@ -1487,27 +1486,36 @@ export default class Context { try { return this._resolveVariableValue(key, defaultValue, true); } finally { - this._deferringLogs = false; - if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + this._endDeferral(); } } - private _flushDeferredLogs() { - const deferred = this._deferredLogs as [EventName, Record | Error][]; - this._deferredLogs = undefined; - + // 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; + return; + } let exposed = false; try { - for (let i = 0; i < deferred.length; i++) { - const entry = deferred[i]; - if (entry[0] === "error") { - this._logError(entry[1] as Error); - } else { - exposed = true; - this._logEvent(entry[0], entry[1] as Record); + let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; + while (deferred !== undefined) { + this._deferredLogs = undefined; + for (let i = 0; i < deferred.length; i++) { + const entry = deferred[i]; + if (entry[0] === "error") { + this._emitError(entry[1] as Error); + } else { + exposed = true; + this._logEvent(entry[0], entry[1] as Record); + } } + deferred = this._deferredLogs; } } finally { + this._deferringLogs = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } @@ -1845,6 +1853,10 @@ export default class Context { (this._deferredLogs ??= []).push(["error", error]); return; } + this._emitError(error); + } + + private _emitError(error: Error) { if (this._eventLogger) { try { this._eventLogger(this, "error", error); From 22dd636e4b6a58fb9021f251e39cfe25dc5158db Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:14:26 +0000 Subject: [PATCH 36/48] test(context): pin single holdout walk, nested treatment() deferral and unindexed reads Add tests for the once-per-candidate holdout walk, an unindexed key that assigns nothing, and the CHANGELOG note that treatment() audience errors are still reported first. Rename a nested-read test whose title overstated callback ordering. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index e7baf24..403f503 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,7 +6087,7 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); - it("reports nested variable reads from a callback after the outer read's exposures, in queue order", () => { + it("reports a nested read's callbacks after the outer read's exposures", () => { const names = []; let nested = false; const eventLogger = jest.fn((ctx, eventName, data) => { @@ -6352,6 +6352,27 @@ describe("Context", () => { 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("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); From 50e38b0c3b87651f8f5c64e50625c9ac7e692d43 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:17:47 +0000 Subject: [PATCH 37/48] test(switchback): pin period-less slot reclassification; tidy docs A refresh that makes a switchback prototype-keyed must not let its cached period-less slot resolve inherited members. Move the silent-winner comment back above its test and narrow the CHANGELOG callback-timing and cost wording. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/__tests__/context-switchback.test.js | 26 ++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9438676..b36a807 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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 (and a `treatment()` with holdouts) queues all its exposures before its `exposure` and `error` callbacks run, so a callback that calls `finalize()` or `publish()` sends every one of them; such a callback now sees them already pending. A cached `variableValue()` costs about 5 ns more than before for that. 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). +- 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. A cached `variableValue()` costs about 4–6 ns more than the previous unreleased build for that (it remains far faster than 1.13.4). 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/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index fc92ab0..51da187 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -782,8 +782,6 @@ describe("switchback serving through Context", () => { ]); }); - // 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. // 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 () => { @@ -802,6 +800,30 @@ describe("switchback serving through Context", () => { } }); + 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)); From 9e0dc3f538275a202f0f6eac930d3d1f0c329218 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 17:40:50 +0000 Subject: [PATCH 38/48] fix(context): bound observer feedback while retaining ordered replay Suppress recursive error-observer calls and duplicate exposure callbacks within one drain, while retaining exposure events for publishing. Outline cold replay; pin nested error/exposure feedback and the timer for exposures queued from an error callback. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 130 +++++++++++++++++++++++++++++++++- src/context.ts | 30 ++++++-- 2 files changed, 152 insertions(+), 8 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 403f503..6b2e9c3 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6367,12 +6367,138 @@ describe("Context", () => { 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"); + const iterator = Array.prototype[Symbol.iterator]; + let emptyWalks = 0; + try { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = function () { + if (this.length === 0) emptyWalks++; + return iterator.call(this); + }; + const value = context.variableValue("not.indexed", "APP_FALLBACK"); + const peeked = context.peekVariableValue("not.indexed", "APP_FALLBACK"); + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = iterator; + expect(value).toEqual("APP_FALLBACK"); + expect(peeked).toEqual("APP_FALLBACK"); + expect(emptyWalks).toBe(0); + } finally { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = iterator; + } expect(assign).not.toHaveBeenCalled(); expect(context._deferredLogs).toBeUndefined(); }); + 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 < 20000) { + 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(10); + expect(context._deferredLogs).toBeUndefined(); + } finally { + consoleError.mockRestore(); + } + }); + + it("does not feed repeated exposure callbacks into the drain forever", () => { + 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(1); + expect(context.pending()).toBe(2); + expect(context._deferredLogs).toBeUndefined(); + }); + 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); diff --git a/src/context.ts b/src/context.ts index 53da867..4d2e250 100644 --- a/src/context.ts +++ b/src/context.ts @@ -242,6 +242,7 @@ export default class Context { // 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 _emittingError = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -1494,11 +1495,13 @@ export default class Context { // 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; - return; - } + if (this._deferredLogs === undefined) this._deferringLogs = false; + else this._replayDeferredLogs(); + } + + private _replayDeferredLogs() { let exposed = false; + const reported = new Set(); try { let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { @@ -1509,7 +1512,14 @@ export default class Context { this._emitError(entry[1] as Error); } else { exposed = true; - this._logEvent(entry[0], entry[1] as Record); + const exposure = entry[1] as Exposure; + const identity = JSON.stringify([exposure.id, exposure.name, exposure.variant, exposure.exposedAt]); + // An observer that reads a repeatedly re-assigned experiment must not feed + // identical callbacks into this drain forever. Events remain queued for publish. + if (!reported.has(identity)) { + reported.add(identity); + this._logEvent(entry[0], entry[1] as Record); + } } } deferred = this._deferredLogs; @@ -1849,7 +1859,7 @@ export default class Context { } private _logError(error: Error) { - if (this._deferringLogs) { + if (this._deferringLogs && !this._emittingError) { (this._deferredLogs ??= []).push(["error", error]); return; } @@ -1857,11 +1867,19 @@ export default class Context { } private _emitError(error: Error) { + // Do not call an error observer recursively when its own reporting raises another error. + if (this._emittingError) return; if (this._eventLogger) { + // Errors raised by an error observer run inline under the existing observer guard, + // rather than feeding the deferred replay forever. Preserve a nesting caller's flag. + const wasEmitting = this._emittingError; + this._emittingError = true; try { this._eventLogger(this, "error", error); } catch (observerError) { console.error(observerError); + } finally { + this._emittingError = wasEmitting; } } } From 513ce45cdaa0a19c0b944c7364c2e491ec02bc6d Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 18:21:23 +0000 Subject: [PATCH 39/48] fix(context): bound callback replay by rounds instead of dropping callbacks Every held callback is delivered once in queue order, including errors raised by an error callback and repeated exposures. A replay that keeps receiving new events stops deferring after DEFERRED_REPLAY_ROUNDS rounds, so later callbacks run inline and stay bounded by the call stack as before deferral; reads always return, even when the clock advances. Removes the Set-based dedup (not available in all browser targets) and the error-observer suppression. Remeasure and document the read cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/__tests__/context.test.js | 102 ++++++++++++++++++++++++++++++++-- src/context.ts | 29 ++++------ 3 files changed, 108 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b36a807..892903e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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. A cached `variableValue()` costs about 4–6 ns more than the previous unreleased build for that (it remains far faster than 1.13.4). 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). +- 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs about 5–9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), and `peekVariableValue()` about 2–7 ns more. 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/src/__tests__/context.test.js b/src/__tests__/context.test.js index 6b2e9c3..7eb55b5 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6432,7 +6432,7 @@ describe("Context", () => { try { const eventLogger = jest.fn((ctx, eventName) => { if (eventName === "exposure" || eventName === "error") { - if (++count < 20000) { + if (++count < 50000) { ctx.attribute("observer.seq", count); ctx.variableValue("error.key", "D"); } @@ -6474,14 +6474,14 @@ describe("Context", () => { }); context.attribute("user", user); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(10); + expect(count).toBeLessThan(50000); expect(context._deferredLogs).toBeUndefined(); } finally { consoleError.mockRestore(); } }); - it("does not feed repeated exposure callbacks into the drain forever", () => { + it("delivers every callback of finite exposure feedback in queue order", () => { let count = 0; const eventLogger = jest.fn((ctx, eventName) => { if (eventName === "exposure" && ++count < 100) ctx.variableValue("button.color", "D"); @@ -6494,9 +6494,101 @@ describe("Context", () => { ); context.customAssignment("exp_holdout_var_later_winner", 0); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBe(1); - expect(context.pending()).toBe(2); + 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(50000); + 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); }); it("schedules the publish timer after a variable read's deferred exposures", () => { diff --git a/src/context.ts b/src/context.ts index 4d2e250..be8904a 100644 --- a/src/context.ts +++ b/src/context.ts @@ -35,6 +35,8 @@ type CustomFieldValue = { type: CustomFieldValueType; }; +// Feedback rounds a deferred-callback replay drains before later callbacks run inline. +const DEFERRED_REPLAY_ROUNDS = 32; export type ExperimentData = { id: number; name: string; @@ -242,7 +244,6 @@ export default class Context { // 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 _emittingError = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -1499,27 +1500,25 @@ export default class Context { else this._replayDeferredLogs(); } + // Replays held callbacks in queue order, keeping deferral on so callbacks a callback raises join + // the queue behind the ones already held. A callback that keeps feeding new events would drain + // forever, so after DEFERRED_REPLAY_ROUNDS rounds deferral stops and later callbacks run inline, + // bounded by the call stack as before deferral existed. private _replayDeferredLogs() { let exposed = false; - const reported = new Set(); try { + let rounds = 0; let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; + if (++rounds >= DEFERRED_REPLAY_ROUNDS) this._deferringLogs = false; for (let i = 0; i < deferred.length; i++) { const entry = deferred[i]; if (entry[0] === "error") { this._emitError(entry[1] as Error); } else { exposed = true; - const exposure = entry[1] as Exposure; - const identity = JSON.stringify([exposure.id, exposure.name, exposure.variant, exposure.exposedAt]); - // An observer that reads a repeatedly re-assigned experiment must not feed - // identical callbacks into this drain forever. Events remain queued for publish. - if (!reported.has(identity)) { - reported.add(identity); - this._logEvent(entry[0], entry[1] as Record); - } + this._logEvent(entry[0], entry[1] as Record); } } deferred = this._deferredLogs; @@ -1859,7 +1858,7 @@ export default class Context { } private _logError(error: Error) { - if (this._deferringLogs && !this._emittingError) { + if (this._deferringLogs) { (this._deferredLogs ??= []).push(["error", error]); return; } @@ -1867,19 +1866,11 @@ export default class Context { } private _emitError(error: Error) { - // Do not call an error observer recursively when its own reporting raises another error. - if (this._emittingError) return; if (this._eventLogger) { - // Errors raised by an error observer run inline under the existing observer guard, - // rather than feeding the deferred replay forever. Preserve a nesting caller's flag. - const wasEmitting = this._emittingError; - this._emittingError = true; try { this._eventLogger(this, "error", error); } catch (observerError) { console.error(observerError); - } finally { - this._emittingError = wasEmitting; } } } From 7ab3c8e89810d657964e20d28a244c784a08060a Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 19:40:39 +0000 Subject: [PATCH 40/48] fix(context): keep replay exhaustion sticky until the outer replay ends Once a replay spends DEFERRED_REPLAY_ROUNDS, nested variableValue()/treatment() calls made from callbacks run inline instead of opening a fresh deferral with a new budget, so runaway observer feedback stays stack-bounded as before deferral. Pin depth 1 within the budget and inline nesting after it; tighten feedback bounds. Document eventLogger delivery order in the README and per-API read cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 6 ++++++ src/__tests__/context.test.js | 35 +++++++++++++++++++++++++++++++++-- src/context.ts | 14 ++++++++++---- 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 892903e..428fd85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs about 5–9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), and `peekVariableValue()` about 2–7 ns more. 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). +- 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs up to about 9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), `peekVariableValue()` about 2–15 ns more; `treatment()` and `peek()` are unchanged (shared-host measurements, approximate). 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 9009759..0679060 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,12 @@ 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. Events a logger +triggers itself are delivered after the ones already waiting. + ### 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. diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7eb55b5..53fe2e9 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6474,7 +6474,7 @@ describe("Context", () => { }); context.attribute("user", user); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(50000); + expect(count).toBeLessThan(2000); expect(context._deferredLogs).toBeUndefined(); } finally { consoleError.mockRestore(); @@ -6519,7 +6519,7 @@ describe("Context", () => { ); context.customAssignment("exp_holdout_var_later_winner", 0); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(50000); + expect(count).toBeLessThan(2000); expect(context._deferringLogs).toBe(false); } finally { consoleError.mockRestore(); @@ -6591,6 +6591,37 @@ describe("Context", () => { 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 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); diff --git a/src/context.ts b/src/context.ts index be8904a..415b68a 100644 --- a/src/context.ts +++ b/src/context.ts @@ -244,6 +244,8 @@ export default class Context { // 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; + // Set once a replay spends its rounds, until that replay ends: nested calls then run inline. + private _replayExhausted = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -1247,7 +1249,7 @@ export default class Context { // 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) { + if (this._deferringLogs || this._replayExhausted) { this._triggerExposures(experimentName, assignment, now); } else { this._deferringLogs = true; @@ -1482,7 +1484,7 @@ export default class Context { // 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); + if (this._deferringLogs || this._replayExhausted) return this._resolveVariableValue(key, defaultValue, true); this._deferringLogs = true; try { @@ -1506,12 +1508,15 @@ export default class Context { // bounded by the call stack as before deferral existed. private _replayDeferredLogs() { let exposed = false; + let rounds = 0; try { - let rounds = 0; let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; - if (++rounds >= DEFERRED_REPLAY_ROUNDS) this._deferringLogs = false; + if (++rounds >= DEFERRED_REPLAY_ROUNDS) { + this._deferringLogs = false; + this._replayExhausted = true; + } for (let i = 0; i < deferred.length; i++) { const entry = deferred[i]; if (entry[0] === "error") { @@ -1525,6 +1530,7 @@ export default class Context { } } finally { this._deferringLogs = false; + if (rounds >= DEFERRED_REPLAY_ROUNDS) this._replayExhausted = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } From 7b6bbbf542b6075dfadaf783d31b773f8d1f05fc Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 21:07:58 +0000 Subject: [PATCH 41/48] test(context): pin treatment() exhaustion and its reset; tighten docs Cover nested treatment() feedback after the replay rounds are spent, deferral returning on a later read (also when its logger finalizes), and finite feedback staying at depth 1. Clear the exhaustion flag unconditionally when the replay ends, use an indexed candidate loop on the hot read path, and narrow the README delivery-order note to exposure/error events and its bounded-round fallback. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 333 ++++++++++++++++++---------------- src/__tests__/context.test.js | 91 ++++++++++ src/context.ts | 7 +- 4 files changed, 272 insertions(+), 161 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 428fd85..171bf46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs up to about 9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), `peekVariableValue()` about 2–15 ns more; `treatment()` and `peek()` are unchanged (shared-host measurements, approximate). 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). +- 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs up to about 9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), `peekVariableValue()` about 2–15 ns more; a cached `treatment()` or `peek()` costs about 1–2 ns more; no added allocation (shared-host measurements, approximate). 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 0679060..9270b68 100644 --- a/README.md +++ b/README.md @@ -48,52 +48,54 @@ This example assumes an API Key, an Application, and an Environment have been cr ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, }); ``` The `application` option can also be an object with `name` and `version` to track which version of your application is generating events. The version can be a number or a semver string: + ```javascript const sdk = new absmartly.SDK({ - endpoint: 'https://sandbox.absmartly.io/v1', - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: { name: 'website', version: '1.2.3' }, + endpoint: "https://sandbox.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: { name: "website", version: "1.2.3" }, }); ``` **SDK Options** -| Option | Type | Required? | Default | Description | -| :----------- | :--------- | :-------: | :-----: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | -| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | -| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | -| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running.| -| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | -| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | -| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | +| Option | Type | Required? | Default | Description | +| :---------- | :--------- | :-------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | +| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | +| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | +| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. | +| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | +| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | +| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | #### Creating a new Context with raw promises + ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); context.ready().then(() => { - console.log("ABsmartly Context ready!"); - if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); - } + console.log("ABsmartly Context ready!"); + if (context.isFailed()) { + console.error("ABsmartly Context failed:", context.readyError()); + } - const treatment = context.treatment("exp_test"); + const treatment = context.treatment("exp_test"); }); ``` @@ -101,16 +103,16 @@ context.ready().then(() => { ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); await context.ready(); if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); + console.error("ABsmartly Context failed:", context.readyError()); } const treatment = context.treatment("exp_test"); @@ -122,15 +124,15 @@ When doing full-stack experimentation with A/B Smartly, we recommend creating a ```html - + ``` @@ -140,13 +142,13 @@ For long-running single-page-applications (SPA), the context is usually created ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000, // 5 minutes + refreshPeriod: 5 * 60 * 1000, // 5 minutes }); ``` @@ -154,11 +156,11 @@ Alternatively, the `refresh()` method can be called manually. The `refresh()` me ```javascript setTimeout(async () => { - try { - await context.refresh(); - } catch (error) { - console.error(error); - } + try { + await context.refresh(); + } catch (error) { + console.error(error); + } }, 5 * 60 * 1000); ``` @@ -174,7 +176,7 @@ The `unit()` and `units()` methods can be called before the context is ready. context.unit("db_user_id", 1000013); context.units({ - db_user_id: 1000013, + db_user_id: 1000013, }); ``` @@ -183,32 +185,35 @@ context.units({ ### Selecting a Treatment #### Including system attributes + You can opt in to also send the SDK name and version with every publish. These are sent as context attributes and can be useful for debugging and filtering in the Web Console. To enable this, set the `includeSystemAttributes` option to `true` when creating the context: + ```javascript const context = sdk.createContext(request, { - includeSystemAttributes: true, + includeSystemAttributes: true, }); ``` When enabled, the following attributes are prepended to the publish request payload: -| Attribute | Description | -|:--- |---| -| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk"`) | -| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | +| Attribute | Description | +| :------------ | ------------------------------------------------------ | +| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk"`) | +| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | Their `setAt` is the time of the earliest exposure or goal in the publish, so they apply to every event in it. A system attribute is not sent when you set an attribute with the same name yourself, so your value is kept. The application and environment names are not part of this option: the collector already adds them to every event, and the SDK always uses them for audiences (see [Context Attributes](#context-attributes)). #### Selecting a treatment + ```javascript if (context.treatment("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -243,9 +248,9 @@ Although generally not recommended, it is sometimes necessary to peek at a treat ```javascript if (context.peek("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -263,14 +268,14 @@ During development, it is useful to force a treatment for an experiment. This ca context.override("exp_test_experiment", 1); // force variant 1 context.overrides({ - exp_test_experiment: 1, - exp_another_experiment: 0, + exp_test_experiment: 1, + exp_another_experiment: 0, }); ``` ### 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. +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" }); @@ -301,7 +306,7 @@ Attributes are used to pass meta-data about the user and/or the request. They ca context.attribute("user_agent", navigator.userAgent); context.attributes({ - customer_age: "new_customer", + customer_age: "new_customer", }); ``` @@ -319,7 +324,7 @@ Sometimes it may be necessary to override the automatic selection of a variant. context.customAssignment("exp_test_experiment", 1); context.customAssignments({ - exp_test_experiment: 1, + exp_test_experiment: 1, }); ``` @@ -336,34 +341,38 @@ context.track("payment", { item_count: 1, total_amount: 1999.99 }); Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. One such case is when the user is about to navigate away right before being exposed to a treatment. You can explicitly call the `publish()` method, which returns a promise, before navigating away. + ```javascript await context.publish().then(() => { - window.location = "https://www.absmartly.com" -}) + window.location = "https://www.absmartly.com"; +}); ``` #### Finalizing + The `finalize()` method will ensure all events have been published to the A/B Smartly collector, like `publish()`, and will also "seal" the context, throwing an error if any method that could generate an event is called. + ```javascript await context.finalize().then(() => { - window.location = "https://www.absmartly.com" -}) + window.location = "https://www.absmartly.com"; +}); ``` #### Refreshing the context with fresh experiment data + For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the `refreshPeriod` option when creating the context. ```javascript const request = { - units: { - session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 + refreshPeriod: 5 * 60 * 1000, }); ``` @@ -373,15 +382,15 @@ The A/B Smartly SDK can be instantiated with an event logger used for all contex ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, - eventLogger: (context, eventName, data) => { - if (eventName === "error") { - console.error(data); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, + eventLogger: (context, eventName, data) => { + if (eventName === "error") { + console.error(data); + } + }, }); ``` @@ -389,21 +398,25 @@ const sdk = new absmartly.SDK({ The data parameter depends on the type of event. Currently, the SDK logs the following events: -| Event | When | Data | -| :----------- | :------------------------------------------------ | :-------------------------------------------- | -| `"error"` | Context receives an error | Error object thrown | -| `"ready"` | Context turns ready | Data used to initialize the context | -| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | -| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | -| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | -| `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | -| `"finalize"` | `finalize()` method succeeds the first time | undefined | +| Event | When | Data | +| :----------- | :---------------------------------------------- | :------------------------------------------- | +| `"error"` | Context receives an error | Error object thrown | +| `"ready"` | Context turns ready | Data used to initialize the context | +| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | +| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | +| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | +| `"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. Events a logger -triggers itself are delivered after the ones already waiting. +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); a logger that keeps triggering new events is switched to inline +delivery after a bounded number of rounds, so its later events arrive as they +are raised. ### HTTP Request Timeout @@ -412,11 +425,15 @@ It is possible to set a timeout per individual HTTP request, overriding the glob Here is an example of setting a timeout only for the `createContext` request. ```javascript -const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 -}, { - timeout: 1500, -}); +const context = sdk.createContext( + request, + { + refreshPeriod: 5 * 60 * 1000, + }, + { + timeout: 1500, + } +); ``` ### HTTP Request Cancellation @@ -427,11 +444,15 @@ Here is an example of a cancellation scenario. ```javascript const controller = new absmartly.AbortController(); -const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 -}, { - signal: controller.signal, -}); +const context = sdk.createContext( + request, + { + refreshPeriod: 5 * 60 * 1000, + }, + { + signal: controller.signal, + } +); // abort request if not ready after 1500ms const timeoutId = setTimeout(() => controller.abort(), 1500); @@ -449,36 +470,36 @@ clearTimeout(timeoutId); const absmartly = require("@absmartly/javascript-sdk"); const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: "production", - application: "website", + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: "production", + application: "website", }); app.use(async (req, res, next) => { - const context = sdk.createContext({ - units: { - session_id: req.cookies.session_id, - }, - }); - - await context.ready(); - if (context.isFailed()) { - console.error("ABsmartly context failed:", context.readyError()); - } - req.absmartly = context; - next(); + const context = sdk.createContext({ + units: { + session_id: req.cookies.session_id, + }, + }); + + await context.ready(); + if (context.isFailed()) { + console.error("ABsmartly context failed:", context.readyError()); + } + req.absmartly = context; + next(); }); app.get("/landing", (req, res) => { - const context = req.absmartly; - const treatment = context.treatment("exp_landing_page"); - - if (treatment === 0) { - res.render("landing-control"); - } else { - res.render("landing-treatment"); - } + const context = req.absmartly; + const treatment = context.treatment("exp_landing_page"); + + if (treatment === 0) { + res.render("landing-control"); + } else { + res.render("landing-treatment"); + } }); ``` @@ -488,29 +509,26 @@ Create the context on the server and pass the data to the client to avoid a seco ```javascript app.get("/", async (req, res) => { - const context = sdk.createContext({ - units: { session_id: req.cookies.session_id }, - }); + const context = sdk.createContext({ + units: { session_id: req.cookies.session_id }, + }); - await context.ready(); + await context.ready(); - const contextData = context.data(); - const treatment = context.treatment("exp_homepage"); + const contextData = context.data(); + const treatment = context.treatment("exp_homepage"); - res.render("index", { - treatment, - absmartlyData: JSON.stringify(contextData), - }); + res.render("index", { + treatment, + absmartlyData: JSON.stringify(contextData), + }); }); ``` On the client side, initialize the context with the pre-fetched data: ```javascript -const context = sdk.createContextWith( - { units: { session_id: sessionId } }, - JSON.parse(window.__ABSMARTLY_DATA__) -); +const context = sdk.createContextWith({ units: { session_id: sessionId } }, JSON.parse(window.__ABSMARTLY_DATA__)); // context is immediately ready, no round-trip needed ``` @@ -522,24 +540,24 @@ const context = sdk.createContextWith( import absmartly from "@absmartly/javascript-sdk"; const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: "YOUR_API_KEY", - environment: "production", - application: "website", - eventLogger: (context, eventName, data) => { - if (eventName === "exposure") { - analytics.track("Experiment Viewed", { - experiment: data.name, - variant: data.variant, - }); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: "YOUR_API_KEY", + environment: "production", + application: "website", + eventLogger: (context, eventName, data) => { + if (eventName === "exposure") { + analytics.track("Experiment Viewed", { + experiment: data.name, + variant: data.variant, + }); + } + }, }); const context = sdk.createContext({ - units: { - session_id: getUserSessionId(), - }, + units: { + session_id: getUserSessionId(), + }, }); await context.ready(); @@ -547,13 +565,13 @@ await context.ready(); const showNewFeature = context.treatment("exp_new_feature") !== 0; if (showNewFeature) { - renderNewFeature(); + renderNewFeature(); } else { - renderOldFeature(); + renderOldFeature(); } document.getElementById("checkout-btn").addEventListener("click", () => { - context.track("checkout", { total: getCartTotal() }); + context.track("checkout", { total: getCartTotal() }); }); ``` @@ -570,7 +588,7 @@ Version 1.14.0 contains a few breaking changes. Most applications will not need ```javascript await context.ready(); if (context.isFailed()) { - console.error("Context failed:", context.readyError()); + console.error("Context failed:", context.readyError()); } const variant = context.treatment("exp_test"); // returns 0 (control) on failure ``` @@ -616,6 +634,7 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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. ### Have a look at our growing list of clients and SDKs: + - [JavaScript SDK](https://www.github.com/absmartly/javascript-sdk) (this package) - [React SDK](https://www.github.com/absmartly/react-sdk) - [Vue2 SDK](https://www.github.com/absmartly/vue2-sdk) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 53fe2e9..66c57c6 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6618,6 +6618,97 @@ describe("Context", () => { 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( + [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("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]); }); diff --git a/src/context.ts b/src/context.ts index 415b68a..381cb5f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1446,8 +1446,9 @@ export default class Context { let selected: Assignment | undefined; let now: number | undefined; - for (const experiment of candidates) { - const experimentName = experiment.data.name; + // 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); @@ -1530,7 +1531,7 @@ export default class Context { } } finally { this._deferringLogs = false; - if (rounds >= DEFERRED_REPLAY_ROUNDS) this._replayExhausted = false; + this._replayExhausted = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } From c7b42410ed06e121a73367327b31cbcf83d8764d Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:10:33 +0000 Subject: [PATCH 42/48] test(context): pin the iterator-free candidate walk; docs cleanup Pin that a warmed shared-key read starts no array iterator and replace a vacuous check. Revert the unrelated README reformat so the README delta is only the shared-key and eventLogger-order text. Correct the CHANGELOG read-cost note to the measured direction. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 337 ++++++++++++++++------------------ src/__tests__/context.test.js | 29 +-- 3 files changed, 180 insertions(+), 188 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 171bf46..39b0ecd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. A cached `variableValue()` costs up to about 9 ns more than the previous unreleased build for that (it remains far faster than 1.13.4), `peekVariableValue()` about 2–15 ns more; a cached `treatment()` or `peek()` costs about 1–2 ns more; no added allocation (shared-host measurements, approximate). 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). +- 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. 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). 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 9270b68..9671411 100644 --- a/README.md +++ b/README.md @@ -48,54 +48,52 @@ This example assumes an API Key, an Application, and an Environment have been cr ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, }); ``` The `application` option can also be an object with `name` and `version` to track which version of your application is generating events. The version can be a number or a semver string: - ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://sandbox.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: { name: "website", version: "1.2.3" }, + endpoint: 'https://sandbox.absmartly.io/v1', + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: { name: 'website', version: '1.2.3' }, }); ``` **SDK Options** -| Option | Type | Required? | Default | Description | -| :---------- | :--------- | :-------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | -| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | -| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | -| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. | -| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | -| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | -| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | +| Option | Type | Required? | Default | Description | +| :----------- | :--------- | :-------: | :-----: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | +| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | +| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | +| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running.| +| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | +| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | +| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | #### Creating a new Context with raw promises - ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); context.ready().then(() => { - console.log("ABsmartly Context ready!"); - if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); - } + console.log("ABsmartly Context ready!"); + if (context.isFailed()) { + console.error("ABsmartly Context failed:", context.readyError()); + } - const treatment = context.treatment("exp_test"); + const treatment = context.treatment("exp_test"); }); ``` @@ -103,16 +101,16 @@ context.ready().then(() => { ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); await context.ready(); if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); + console.error("ABsmartly Context failed:", context.readyError()); } const treatment = context.treatment("exp_test"); @@ -124,15 +122,15 @@ When doing full-stack experimentation with A/B Smartly, we recommend creating a ```html - + ``` @@ -142,13 +140,13 @@ For long-running single-page-applications (SPA), the context is usually created ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000, // 5 minutes + refreshPeriod: 5 * 60 * 1000, // 5 minutes }); ``` @@ -156,11 +154,11 @@ Alternatively, the `refresh()` method can be called manually. The `refresh()` me ```javascript setTimeout(async () => { - try { - await context.refresh(); - } catch (error) { - console.error(error); - } + try { + await context.refresh(); + } catch (error) { + console.error(error); + } }, 5 * 60 * 1000); ``` @@ -176,7 +174,7 @@ The `unit()` and `units()` methods can be called before the context is ready. context.unit("db_user_id", 1000013); context.units({ - db_user_id: 1000013, + db_user_id: 1000013, }); ``` @@ -185,35 +183,32 @@ context.units({ ### Selecting a Treatment #### Including system attributes - You can opt in to also send the SDK name and version with every publish. These are sent as context attributes and can be useful for debugging and filtering in the Web Console. To enable this, set the `includeSystemAttributes` option to `true` when creating the context: - ```javascript const context = sdk.createContext(request, { - includeSystemAttributes: true, + includeSystemAttributes: true, }); ``` When enabled, the following attributes are prepended to the publish request payload: -| Attribute | Description | -| :------------ | ------------------------------------------------------ | -| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk"`) | -| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | +| Attribute | Description | +|:--- |---| +| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk"`) | +| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | Their `setAt` is the time of the earliest exposure or goal in the publish, so they apply to every event in it. A system attribute is not sent when you set an attribute with the same name yourself, so your value is kept. The application and environment names are not part of this option: the collector already adds them to every event, and the SDK always uses them for audiences (see [Context Attributes](#context-attributes)). #### Selecting a treatment - ```javascript if (context.treatment("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -231,9 +226,9 @@ const buttonColor = context.variableValue("button.color", defaultButtonColor); 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, -that experiment's control value is returned. Only the winning experiment gets an +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, that +experiment's control value is returned. 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; @@ -248,9 +243,9 @@ Although generally not recommended, it is sometimes necessary to peek at a treat ```javascript if (context.peek("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -268,14 +263,14 @@ During development, it is useful to force a treatment for an experiment. This ca context.override("exp_test_experiment", 1); // force variant 1 context.overrides({ - exp_test_experiment: 1, - exp_another_experiment: 0, + exp_test_experiment: 1, + exp_another_experiment: 0, }); ``` ### 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. +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" }); @@ -306,7 +301,7 @@ Attributes are used to pass meta-data about the user and/or the request. They ca context.attribute("user_agent", navigator.userAgent); context.attributes({ - customer_age: "new_customer", + customer_age: "new_customer", }); ``` @@ -324,7 +319,7 @@ Sometimes it may be necessary to override the automatic selection of a variant. context.customAssignment("exp_test_experiment", 1); context.customAssignments({ - exp_test_experiment: 1, + exp_test_experiment: 1, }); ``` @@ -341,38 +336,34 @@ context.track("payment", { item_count: 1, total_amount: 1999.99 }); Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. One such case is when the user is about to navigate away right before being exposed to a treatment. You can explicitly call the `publish()` method, which returns a promise, before navigating away. - ```javascript await context.publish().then(() => { - window.location = "https://www.absmartly.com"; -}); + window.location = "https://www.absmartly.com" +}) ``` #### Finalizing - The `finalize()` method will ensure all events have been published to the A/B Smartly collector, like `publish()`, and will also "seal" the context, throwing an error if any method that could generate an event is called. - ```javascript await context.finalize().then(() => { - window.location = "https://www.absmartly.com"; -}); + window.location = "https://www.absmartly.com" +}) ``` #### Refreshing the context with fresh experiment data - For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the `refreshPeriod` option when creating the context. ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000, + refreshPeriod: 5 * 60 * 1000 }); ``` @@ -382,15 +373,15 @@ The A/B Smartly SDK can be instantiated with an event logger used for all contex ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, - eventLogger: (context, eventName, data) => { - if (eventName === "error") { - console.error(data); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, + eventLogger: (context, eventName, data) => { + if (eventName === "error") { + console.error(data); + } + }, }); ``` @@ -398,22 +389,22 @@ const sdk = new absmartly.SDK({ The data parameter depends on the type of event. Currently, the SDK logs the following events: -| Event | When | Data | -| :----------- | :---------------------------------------------- | :------------------------------------------- | -| `"error"` | Context receives an error | Error object thrown | -| `"ready"` | Context turns ready | Data used to initialize the context | -| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | -| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | -| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | -| `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | -| `"finalize"` | `finalize()` method succeeds the first time | undefined | +| Event | When | Data | +| :----------- | :------------------------------------------------ | :-------------------------------------------- | +| `"error"` | Context receives an error | Error object thrown | +| `"ready"` | Context turns ready | Data used to initialize the context | +| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | +| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | +| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | +| `"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 +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); a logger that keeps triggering new events is switched to inline delivery after a bounded number of rounds, so its later events arrive as they are raised. @@ -425,15 +416,11 @@ It is possible to set a timeout per individual HTTP request, overriding the glob Here is an example of setting a timeout only for the `createContext` request. ```javascript -const context = sdk.createContext( - request, - { - refreshPeriod: 5 * 60 * 1000, - }, - { - timeout: 1500, - } -); +const context = sdk.createContext(request, { + refreshPeriod: 5 * 60 * 1000 +}, { + timeout: 1500, +}); ``` ### HTTP Request Cancellation @@ -444,15 +431,11 @@ Here is an example of a cancellation scenario. ```javascript const controller = new absmartly.AbortController(); -const context = sdk.createContext( - request, - { - refreshPeriod: 5 * 60 * 1000, - }, - { - signal: controller.signal, - } -); +const context = sdk.createContext(request, { + refreshPeriod: 5 * 60 * 1000 +}, { + signal: controller.signal, +}); // abort request if not ready after 1500ms const timeoutId = setTimeout(() => controller.abort(), 1500); @@ -470,36 +453,36 @@ clearTimeout(timeoutId); const absmartly = require("@absmartly/javascript-sdk"); const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: "production", - application: "website", + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: "production", + application: "website", }); app.use(async (req, res, next) => { - const context = sdk.createContext({ - units: { - session_id: req.cookies.session_id, - }, - }); - - await context.ready(); - if (context.isFailed()) { - console.error("ABsmartly context failed:", context.readyError()); - } - req.absmartly = context; - next(); + const context = sdk.createContext({ + units: { + session_id: req.cookies.session_id, + }, + }); + + await context.ready(); + if (context.isFailed()) { + console.error("ABsmartly context failed:", context.readyError()); + } + req.absmartly = context; + next(); }); app.get("/landing", (req, res) => { - const context = req.absmartly; - const treatment = context.treatment("exp_landing_page"); - - if (treatment === 0) { - res.render("landing-control"); - } else { - res.render("landing-treatment"); - } + const context = req.absmartly; + const treatment = context.treatment("exp_landing_page"); + + if (treatment === 0) { + res.render("landing-control"); + } else { + res.render("landing-treatment"); + } }); ``` @@ -509,26 +492,29 @@ Create the context on the server and pass the data to the client to avoid a seco ```javascript app.get("/", async (req, res) => { - const context = sdk.createContext({ - units: { session_id: req.cookies.session_id }, - }); + const context = sdk.createContext({ + units: { session_id: req.cookies.session_id }, + }); - await context.ready(); + await context.ready(); - const contextData = context.data(); - const treatment = context.treatment("exp_homepage"); + const contextData = context.data(); + const treatment = context.treatment("exp_homepage"); - res.render("index", { - treatment, - absmartlyData: JSON.stringify(contextData), - }); + res.render("index", { + treatment, + absmartlyData: JSON.stringify(contextData), + }); }); ``` On the client side, initialize the context with the pre-fetched data: ```javascript -const context = sdk.createContextWith({ units: { session_id: sessionId } }, JSON.parse(window.__ABSMARTLY_DATA__)); +const context = sdk.createContextWith( + { units: { session_id: sessionId } }, + JSON.parse(window.__ABSMARTLY_DATA__) +); // context is immediately ready, no round-trip needed ``` @@ -540,24 +526,24 @@ const context = sdk.createContextWith({ units: { session_id: sessionId } }, JSON import absmartly from "@absmartly/javascript-sdk"; const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: "YOUR_API_KEY", - environment: "production", - application: "website", - eventLogger: (context, eventName, data) => { - if (eventName === "exposure") { - analytics.track("Experiment Viewed", { - experiment: data.name, - variant: data.variant, - }); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: "YOUR_API_KEY", + environment: "production", + application: "website", + eventLogger: (context, eventName, data) => { + if (eventName === "exposure") { + analytics.track("Experiment Viewed", { + experiment: data.name, + variant: data.variant, + }); + } + }, }); const context = sdk.createContext({ - units: { - session_id: getUserSessionId(), - }, + units: { + session_id: getUserSessionId(), + }, }); await context.ready(); @@ -565,13 +551,13 @@ await context.ready(); const showNewFeature = context.treatment("exp_new_feature") !== 0; if (showNewFeature) { - renderNewFeature(); + renderNewFeature(); } else { - renderOldFeature(); + renderOldFeature(); } document.getElementById("checkout-btn").addEventListener("click", () => { - context.track("checkout", { total: getCartTotal() }); + context.track("checkout", { total: getCartTotal() }); }); ``` @@ -588,7 +574,7 @@ Version 1.14.0 contains a few breaking changes. Most applications will not need ```javascript await context.ready(); if (context.isFailed()) { - console.error("Context failed:", context.readyError()); + console.error("Context failed:", context.readyError()); } const variant = context.treatment("exp_test"); // returns 0 (control) on failure ``` @@ -634,7 +620,6 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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. ### Have a look at our growing list of clients and SDKs: - - [JavaScript SDK](https://www.github.com/absmartly/javascript-sdk) (this package) - [React SDK](https://www.github.com/absmartly/react-sdk) - [Vue2 SDK](https://www.github.com/absmartly/vue2-sdk) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 66c57c6..fcd2fa2 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6367,27 +6367,34 @@ describe("Context", () => { 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 emptyWalks = 0; + let walks = 0; + let value; + let peeked; try { // eslint-disable-next-line no-extend-native Array.prototype[Symbol.iterator] = function () { - if (this.length === 0) emptyWalks++; + walks++; return iterator.call(this); }; - const value = context.variableValue("not.indexed", "APP_FALLBACK"); - const peeked = context.peekVariableValue("not.indexed", "APP_FALLBACK"); - // eslint-disable-next-line no-extend-native - Array.prototype[Symbol.iterator] = iterator; - expect(value).toEqual("APP_FALLBACK"); - expect(peeked).toEqual("APP_FALLBACK"); - expect(emptyWalks).toBe(0); + 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(assign).not.toHaveBeenCalled(); - expect(context._deferredLogs).toBeUndefined(); + expect([value, peeked, walks]).toEqual([first, first, 0]); }); it("arms the timer for an exposure first queued from a replayed error callback", () => { From aabe26c7c646bcfe5342deea4c42a01010b9fd46 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:46:33 +0000 Subject: [PATCH 43/48] fix(context): keep each call's exposure batch intact at the replay limit After a replay spends its rounds, later calls still hold their own callbacks until all of their exposures are queued and then deliver that batch, so a logger finalizing at the cutoff sends the winner too. Also bound a replay by delivered callbacks (DEFERRED_REPLAY_CALLBACKS) so a callback that raises several events per callback cannot grow the queue before round 32; fold _emitError into _logEvent; clear the variables of a cached assignment whose arm a refresh removed. Tests: whole batch at chain lengths 30-40, retained-callback bound, removed override arm; narrow two test titles to what they assert. README: the held-out fallback returns the default when its control arm lacks the key. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 100 +++++++++++++++++++++++++++++++++- src/context.ts | 69 +++++++++++++---------- 2 files changed, 138 insertions(+), 31 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index fcd2fa2..27de707 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,7 +6087,7 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); - it("reports a nested read's callbacks after the outer read's exposures", () => { + 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) => { @@ -6488,7 +6488,7 @@ describe("Context", () => { } }); - it("delivers every callback of finite exposure feedback in queue order", () => { + 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"); @@ -6716,6 +6716,81 @@ describe("Context", () => { ]); }); + 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", + ]); + } + ); + + it("bounds the callbacks a replay retains when each callback raises two more", () => { + let count = 0; + let maxRetained = 0; + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const experiment = winnerAfterHoldout({ + customFieldValues: [ + { name: "a", type: "json", value: "{bad" }, + { name: "b", type: "json", value: "{bad" }, + ], + }); + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure" && eventName !== "error") return; + maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); + if (++count > 20000) return; + ctx.customFieldValue("exp_holdout_var_later_winner", "a"); + ctx.customFieldValue("exp_holdout_var_later_winner", "b"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([experiment], []) + ); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + // Without the callback budget each round doubles the retained list until round 32. + expect(maxRetained).toBeLessThanOrEqual(2048); + expect(context._deferredLogs).toBeUndefined(); + } finally { + consoleError.mockRestore(); + } + }); + 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]); }); @@ -7053,7 +7128,6 @@ describe("Context", () => { it.each([null, "", "[]", "0", "false", '"string"', "null", '{"other":1}'])( "returns the default when the winner config %p does not define the key", (selectedConfig) => { - // No selected config shape may leak inherited Object.prototype members. 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] }); @@ -7076,6 +7150,26 @@ describe("Context", () => { expect(context.variableValue("toString", "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], {}), diff --git a/src/context.ts b/src/context.ts index 381cb5f..b30bcbd 100644 --- a/src/context.ts +++ b/src/context.ts @@ -35,8 +35,8 @@ type CustomFieldValue = { type: CustomFieldValueType; }; -// Feedback rounds a deferred-callback replay drains before later callbacks run inline. const DEFERRED_REPLAY_ROUNDS = 32; +const DEFERRED_REPLAY_CALLBACKS = 1024; export type ExperimentData = { id: number; name: string; @@ -244,7 +244,6 @@ export default class Context { // 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; - // Set once a replay spends its rounds, until that replay ends: nested calls then run inline. private _replayExhausted = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; @@ -1249,7 +1248,7 @@ export default class Context { // 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._replayExhausted) { + if (this._deferringLogs) { this._triggerExposures(experimentName, assignment, now); } else { this._deferringLogs = true; @@ -1470,7 +1469,6 @@ export default class Context { if (shouldQueueExposure && !selected.exposed) { selected.exposed = true; - // The loop above already fired this candidate's holdouts. this._triggerExposures(selectedName, selected, now, false); } @@ -1485,7 +1483,7 @@ export default class Context { // 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 || this._replayExhausted) return this._resolveVariableValue(key, defaultValue, true); + if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); this._deferringLogs = true; try { @@ -1500,32 +1498,31 @@ export default class Context { // behind the ones already queued. private _endDeferral() { if (this._deferredLogs === undefined) this._deferringLogs = false; + else if (this._replayExhausted) this._deliverDeferredLogs(); else this._replayDeferredLogs(); } - // Replays held callbacks in queue order, keeping deferral on so callbacks a callback raises join - // the queue behind the ones already held. A callback that keeps feeding new events would drain - // forever, so after DEFERRED_REPLAY_ROUNDS rounds deferral stops and later callbacks run inline, + // 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; - if (++rounds >= DEFERRED_REPLAY_ROUNDS) { + 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++) { - const entry = deferred[i]; - if (entry[0] === "error") { - this._emitError(entry[1] as Error); - } else { - exposed = true; - this._logEvent(entry[0], entry[1] as Record); - } + if (deferred[i][0] === "exposure") exposed = true; + this._logEvent(deferred[i][0], deferred[i][1]); } deferred = this._deferredLogs; } @@ -1537,6 +1534,21 @@ export default class Context { } } + 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 { return this._resolveVariableValue(key, defaultValue, false); } @@ -1847,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 @@ -1869,17 +1881,7 @@ export default class Context { (this._deferredLogs ??= []).push(["error", error]); return; } - this._emitError(error); - } - - private _emitError(error: Error) { - if (this._eventLogger) { - try { - this._eventLogger(this, "error", error); - } catch (observerError) { - console.error(observerError); - } - } + this._logEvent("error", error); } private _unitHash(unitType: string) { @@ -2101,6 +2103,17 @@ export default class Context { } } + // A reused assignment whose arm a refresh removed has no variables any more. + for (const experimentName of Object.keys(assignments)) { + const assignment = assignments[experimentName]; + const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) + ? index[experimentName] + : undefined; + if (experiment !== undefined && assignment.variant >= experiment.data.variants.length) { + assignment.variables = undefined; + } + } + this._index = index; this._indexVariables = indexVariables; this._assignments = assignments; From 65cb7a878b8ce9d9e342133d52126c0e0bd857c8 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:49:31 +0000 Subject: [PATCH 44/48] docs: describe the replay limit batch rule and held-out default Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39b0ecd..6ed1a20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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; an observer that keeps feeding new events stops being deferred after a bounded number of rounds, so a read always returns. 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). 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). +- 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 a read always returns and 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). 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 9671411..e65b27e 100644 --- a/README.md +++ b/README.md @@ -227,8 +227,9 @@ 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, that -experiment's control value is returned. Only the winning experiment gets an +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; @@ -405,9 +406,8 @@ 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); a logger that keeps triggering new events is switched to inline -delivery after a bounded number of rounds, so its later events arrive as they -are raised. +immediately); after a bounded number of rounds or callbacks, each later call delivers its own +events as soon as all of that call's exposures are queued. ### HTTP Request Timeout From e546a77dd5daaec16e5a33ef0717212dcb31d859 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 02:45:31 +0000 Subject: [PATCH 45/48] fix(context): restore a refreshed arm's variables; pin post-limit delivery A reused assignment whose arm a refresh removed gets the arm's current variables back once a later refresh restores it. Pin the post-limit path: treatment() keeps its holdout in the batch, every callback of a post-limit batch is delivered once in queue order, a post-limit error/exposure batch arms the publish timer, and a real two-way fan-out stays within the callback budget. Cover assigned and custom arms as well as overrides. README: later events arrive as one batch per call; rewrap the shared-key note. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 237 ++++++++++++++++++++++++++++++---- src/context.ts | 8 +- 2 files changed, 218 insertions(+), 27 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 27de707..51627fb 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6759,35 +6759,196 @@ describe("Context", () => { ); 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 consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + 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 > 6000) 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 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("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 { - const experiment = winnerAfterHoldout({ - customFieldValues: [ - { name: "a", type: "json", value: "{bad" }, - { name: "b", type: "json", value: "{bad" }, - ], - }); - const eventLogger = jest.fn((ctx, eventName) => { - if (eventName !== "exposure" && eventName !== "error") return; - maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); - if (++count > 20000) return; - ctx.customFieldValue("exp_holdout_var_later_winner", "a"); - ctx.customFieldValue("exp_holdout_var_later_winner", "b"); - }); - const context = new Context( - sdk, - { ...contextOptions, eventLogger }, - contextParams, - buildHoldoutResponse([experiment], []) - ); - expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - // Without the callback budget each round doubles the retained list until round 32. - expect(maxRetained).toBeLessThanOrEqual(2048); - expect(context._deferredLogs).toBeUndefined(); + expect(events).toEqual(["error", "exposure:exp_holdout_var_later_winner"]); + expect(context.pending()).toBe(1); + expect(context._publishTimeout).toBeDefined(); } finally { - consoleError.mockRestore(); + clearTimeout(context._publishTimeout); } }); @@ -7150,6 +7311,32 @@ describe("Context", () => { 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("returns the default when a refresh removes a cached override's arm", async () => { const before = { ...shared(1, [1, 0], {}), diff --git a/src/context.ts b/src/context.ts index b30bcbd..53f7060 100644 --- a/src/context.ts +++ b/src/context.ts @@ -2103,14 +2103,18 @@ export default class Context { } } - // A reused assignment whose arm a refresh removed has no variables any more. + // A reused assignment 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. for (const experimentName of Object.keys(assignments)) { const assignment = assignments[experimentName]; const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) ? index[experimentName] : undefined; - if (experiment !== undefined && assignment.variant >= experiment.data.variants.length) { + if (experiment === undefined) continue; + 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]; } } From 24658b5a63553882cbf2321ef58910e4c5e0ef55 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 03:04:59 +0000 Subject: [PATCH 46/48] fix(switchback): follow a refreshed arm in switchback slots; docs Cached switchback period and period-less slots now follow their arm across refreshes like unit assignments: no variables while a refresh has removed the arm, the arm's values again once a later refresh restores it. CHANGELOG: removed-arm default, and replay feedback described as bounded rather than always returning; README rewrap. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 24 ++++++++++---------- src/__tests__/context-switchback.test.js | 15 +++++++++++++ src/context.ts | 28 +++++++++++++++++------- 4 files changed, 48 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ed1a20..72471d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,5 @@ Earlier release notes are on the [GitHub releases page](https://github.com/absma ### 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 a read always returns and 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). 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). +- 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 e65b27e..e9a586b 100644 --- a/README.md +++ b/README.md @@ -226,17 +226,17 @@ const buttonColor = context.variableValue("button.color", defaultButtonColor); 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. +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 @@ -407,7 +407,7 @@ 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 as soon as all of that call's exposures are queued. +events together, once all of that call's exposures are queued. ### HTTP Request Timeout diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 51da187..17df4f2 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -800,6 +800,21 @@ describe("switchback serving through Context", () => { } }); + 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 twoArms = switchback(1, "exp_sb", 2, HOUR); + await refreshTo(context, twoArms); + 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 = [ diff --git a/src/context.ts b/src/context.ts index 53f7060..86dd339 100644 --- a/src/context.ts +++ b/src/context.ts @@ -2103,19 +2103,31 @@ export default class Context { } } - // A reused assignment 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. - for (const experimentName of Object.keys(assignments)) { - const assignment = assignments[experimentName]; - const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) - ? index[experimentName] - : undefined; - if (experiment === undefined) continue; + // 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; From aa09983c449b1eb6e2f691c90c870dd96d4ec433 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 04:17:16 +0000 Subject: [PATCH 47/48] test(context): pin switchback slot arm-following, post-limit timer and budget boundary Cover the period-less slot and custom/drawn period slots following their arm across refreshes, an error-only batch after the replay limit arming no timer, the callback budget boundary at exactly 1024, and the restore guard not adopting a different experiment id. Shorten the retained-callback test. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 44 +++++++++- src/__tests__/context.test.js | 101 ++++++++++++++++++++++- 2 files changed, 142 insertions(+), 3 deletions(-) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 17df4f2..75ff58e 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -800,14 +800,54 @@ describe("switchback serving through Context", () => { } }); + 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"]); + }); + + 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 twoArms = switchback(1, "exp_sb", 2, HOUR); - await refreshTo(context, twoArms); + 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); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 51627fb..f16a09a 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6779,7 +6779,7 @@ describe("Context", () => { if (eventName !== "exposure" && eventName !== "error") return; if (eventName === "error") errors++; maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); - if (++count > 6000) return; + if (++count > 2500) return; ctx.attribute("a", count); ctx.variableValue("e1.key", "D"); ctx.attribute("b", count); @@ -6891,6 +6891,84 @@ describe("Context", () => { } ); + 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({}), @@ -7337,6 +7415,27 @@ describe("Context", () => { } ); + 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], {}), From acd0951fb783ce566c15033ac58e6f0467f3c8e0 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 11:55:17 +0000 Subject: [PATCH 48/48] test(switchback): pin non-override period-less arm refresh Kill the surviving followArm mutant for full-on and custom period-less assignments. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context-switchback.test.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 75ff58e..4a7c765 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -821,6 +821,22 @@ describe("switchback serving through Context", () => { 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",