We are designing a client-side feature evaluation consistency test.
The test has three components: sticky bucketing, edge cases, and replay probes.
Let's break down:
-
Sticky Bucketing:
- We want to ensure that once a user is bucketed into a variant (control or treatment), they remain in that variant for subsequent visits (sticky).
- We can use a cookie or localStorage to store the assigned variant.
- We need to test:
a. Initial bucketing: when no cookie exists, the user gets assigned to a variant and the cookie is set.
b. Subsequent visits: the same variant is read from the cookie and no reassignment occurs.
c. When the cookie is removed, the user gets reassigned (possibly to the same or different variant).
-
Edge Cases:
- We should test the boundaries and unexpected scenarios. For example:
a. What happens when the user has multiple cookies (e.g., from different paths or subdomains)? We should ensure we read/write the correct cookie.
b. What happens when the cookie is malformed (e.g., non-numeric, out of range, corrupted)? We should handle by resetting.
c. What if the cookie is set for a different path or domain? Our code should read the cookie we expect.
d. Test with different storage mechanisms (localStorage vs cookies) and fallback if one is disabled.
e. Test when the user is in private/incognito mode (where storage might be cleared on exit) or has storage disabled.
f. Test with different user agents (browsers) that might have different storage limits or behaviors.
-
Replay Probes:
- We want to be able to replay a specific user's bucketing scenario. This is useful for debugging.
- We can instrument the bucketing code to log the steps (or at least the assignment and the sources of randomness) and then allow setting a specific state (e.g., by setting the cookie to a specific value) to reproduce.
- We might need:
a. A way to force a specific variant (by setting a cookie or localStorage with a known value).
b. A way to capture the state of the random number generator (if using a seeded random) or the bucketing algorithm's state.
c. Logging of the bucketing decision (with a unique identifier for the test run) so we can correlate.
Implementation Plan:
We'll create a test suite that can be run in a browser environment (or simulated with JSDOM for unit tests). We'll structure:
-
A BucketManager class that handles:
* Reading and writing the sticky cookie (or localStorage).
* Assigning a variant (based on a given bucketing key and configuration, e.g., percentage splits).
* Handling edge cases in storage.
-
The test suite will have:
Part 1: Sticky Bucketing Tests
Test 1.1: Without existing cookie, assignment is made and cookie set.
Test 1.2: With existing cookie (valid), the same variant is returned without reassignment.
Test 1.3: With existing cookie (invalid), reassignment happens and cookie updated.
Part 2: Edge Cases
Test 2.1: Simulate multiple cookies (different paths) and ensure we read the correct one.
Test 2.2: Malformed cookie value (non-numeric, empty, out of range) leads to reset.
Test 2.3: When localStorage is used and full, fallback to cookie or handle appropriately.
Test 2.4: When storage is disabled (throw on access), handle gracefully (maybe assign without sticky?).
Test 2.5: Different domains/subdomains: set cookie for a parent domain and see if child can read? (depends on our cookie path/domain settings)
Part 3: Replay Probes
We'll design a way to force a variant by setting a cookie with a specific key and value (e.g., feature_test_variant=1).
Also, we can log the bucketing events (with a test run id) to the console or a log array.
We can have:
- A method `forceVariant(variant)` that sets the cookie and forces the next assignment to use that variant.
- A method `clearForcedVariant()` to remove the force.
- In the assignment, we check for a forced variant first (for replay).
Then in tests, we can:
- Set a forced variant and verify that the assigned variant is the forced one.
- Then remove the force and see it goes back to normal bucketing.
However, note that in production we might not want the force to be easily accessible. So we can have a separate debug mode or query parameter to set the force? But for testing we can expose.
Alternatively, we can design the bucketing algorithm to be deterministic (using a seeded random) so we can replay by setting the seed. But that might be overkill.
Let's assume we are using a simple hash-based bucketing (like hashing the user key and then modulo). Then we can replay by having the same user key and the same configuration.
But sticky bucketing uses storage, so we need to set the storage to a specific state.
So for replay, we can:
Step 1: Record the storage state (cookie/localStorage) for a given user key and configuration.
Step 2: To replay, set the storage to the recorded state and then run the bucketing again.
We can also record the assignment history (if we log each assignment) but that might be too much.
Let's keep it simple: we can force a variant by setting the storage value directly (to the variant number) and then test.
We'll design:
function assignVariant(userKey, config) {
// Check for forced variant (from query param or a special cookie for debug) -> for replay
// Check storage for existing variant -> sticky
// Otherwise, compute variant based on userKey and config (e.g., hash(userKey) % 100 < config.percentage ? treatment : control)
// Then set storage.
}
For testing, we can:
- Set the forced variant via a query parameter (like `?force_variant=1`) or by setting a cookie (like `force_bucket=1`). But note: we don't want to interfere with the sticky cookie.
We can have two separate cookies:
- Sticky cookie: feature_bucket (or something)
- Force cookie: feature_bucket_force (only in debug mode)
But for the test, we can mock the storage and force the read/write.
Alternatively, we can design the BucketManager to accept an override function for storage (for testing) and for forcing.
Since we are writing tests, we can create a mock storage (like an in-memory object) and then set the forced variant in the BucketManager's options.
Let's define:
class BucketManager {
constructor(options = {}) {
this.storage = options.storage || (typeof window !== 'undefined' ? window.localStorage : null);
this.forceVariant = options.forceVariant || null;
this.cookieName = options.cookieName || 'feature_bucket';
this.forceCookieName = options.forceCookieName || 'feature_bucket_force';
}
getStoredVariant() {
// read from storage (or cookie) and return variant or null.
}
setStoredVariant(variant) {
// write to storage.
}
getForcedVariant() {
// check for force from query param or a special cookie? But in tests we can set via options.
if (this.forceVariant !== null) {
return this.forceVariant;
}
// Alternatively, we can check a cookie for force? But let's keep it simple for tests: we set via options.
return null;
}
assignVariant(userKey, config) {
const forced = this.getForcedVariant();
if (forced !== null) {
// We are forcing, but do we want to set sticky? Maybe we want to force without sticky? Or force and set sticky?
// For replay, we might want to set the sticky to the forced variant so that next time without force, we get the same.
// But if we are forcing, we are overriding. Let's decide:
// Option 1: Force means we assign the forced variant and also set the sticky cookie to that variant.
// Then, even if we remove the force, next time we will get the forced variant because it's sticky.
// Option 2: Force only for this request and do not set sticky. Then next time without force, we get a new assignment.
// For replay, we usually want to reproduce the exact same sequence. So if we force and set sticky, then we are setting the state.
// But note: the force might be used to test a specific assignment without affecting the sticky state?
// Actually, for replay we want to set the state to a known point. So we want to set the sticky to the forced variant.
// Let's do: if forced, we assign the forced variant and then set the stored variant to the forced variant (unless the stored variant is already set and we are not overriding?).
// However, we are forcing because we want to override the stored variant? Or we want to set the state exactly as we force?
// I think for replay, we want to set the state to a specific variant, so we should set the stored variant to the forced variant and then return it.
this.setStoredVariant(forced);
return forced;
}
let stored = this.getStoredVariant();
if (stored !== null) {
return stored;
}
// Compute variant
const variant = this.computeVariant(userKey, config);
this.setStoredVariant(variant);
return variant;
}
computeVariant(userKey, config) {
// hash the userKey and then modulo according to config.
// For example, config: { control: 0, treatment: 1, percentage: 50 } -> if hash < 50 then treatment else control.
// But we can have multiple variants? Let's assume we have a map of variant to percentage.
// Actually, common pattern:
// We have an array of variants with weights (percentages). We compute a hash (0-99) and then pick the variant that covers that number.
// For simplicity, let's assume we have two variants and a split percentage for treatment.
const hash = this.hashString(userKey) % 100;
return hash < config.percentage ? config.treatment : config.control;
}
hashString(str) {
// Simple hash function for testing. In production, we might use a more robust one.
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash);
}
}
Then in tests:
const bucketManager = new BucketManager();
// Test 1.1:
let variant = bucketManager.assignVariant('user123', {control: 0, treatment: 1, percentage: 50});
// variant should be 0 or 1.
// Then check that the storage now has the variant.
// Test 1.2:
let variant2 = bucketManager.assignVariant('user123', {control: 0, treatment: 1, percentage: 50});
// variant2 should equal variant.
// Test 1.3:
bucketManager.setStoredVariant('invalid'); // set an invalid value? Actually, we store as string, so we might store 'abc'.
let variant3 = bucketManager.assignVariant('user123', {control: 0, treatment: 1, percentage: 50});
// Since stored variant is invalid? We should handle in getStoredVariant. Let's design getStoredVariant to return null if not a number.
// So in getStoredVariant, we read and try to parse as integer. If NaN, return null.
For edge cases:
- Test with multiple cookies: we can set a cookie with a different path and see if we read it. But note: our cookie reading function should specify the path and domain?
We are using localStorage? Or cookies? Let's assume we are using localStorage for simplicity in tests, but in production we might use cookies for server-side consistency.
Actually, sticky bucketing is usually done with a cookie that is accessible by the server and client. So we might use a cookie.
We can have a helper to read/write cookies with a specific path and domain.
But for the test, we can mock the cookie reading to return a value set by a previous test? Or we can use a test double for document.cookie.
Alternatively, we can design the storage interface to be pluggable.
Let's change the BucketManager to accept a storage adapter.
class BucketManager {
constructor(storageAdapter, options = {}) {
this.storageAdapter = storageAdapter;
this.forceVariant = options.forceVariant || null;
}
getStoredVariant() {
const value = this.storageAdapter.getItem(this.cookieName);
const parsed = parseInt(value, 10);
return isNaN(parsed) ? null : parsed;
}
setStoredVariant(variant) {
this.storageAdapter.setItem(this.cookieName, variant.toString());
}
}
Then we can create a MockStorageAdapter that uses an in-memory object.
For cookie tests, we can have a CookieStorageAdapter that uses document.cookie.
Then we can test:
- MockStorageAdapter:
test with an existing value -> returns that value.
test with an invalid value (like 'abc') -> returns null.
- CookieStorageAdapter:
we need to set a cookie and then read it. But note: cookies are per path and domain.
We can also test when the cookie is set for a different path: our CookieStorageAdapter should read the cookie for the current path. So if we set a cookie for a different path, it shouldn't be visible.
For that, we can set a cookie with a specific path and then try to read it from a different path? But in a test environment (JSDOM) we might not have full cookie support.
Alternatively, we can simulate by having the CookieStorageAdapter read a specific cookie string that we provide (so we can set the cookie string with multiple cookies and then parse). But then we are not testing the actual browser behavior.
Since this is a client-side test, we might run it in a real browser? Then we can set cookies with different paths and try to read.
But for unit tests, we can mock the document.cookie to return a string with multiple cookies and then parse.
However, note: the browser's document.cookie returns only the cookies for the current path and domain.
So we can test:
// Set a cookie for path '/test' and then navigate to a different path? We can't change the current path in the same test without reloading.
This might be too complex for unit tests. We might need integration tests.
Given the complexity, let's focus on the core logic and then for edge cases we can simulate:
- Multiple cookies: we can set the cookie string (in a mock) to have two cookies with the same name but different paths? Actually, cookies are uniquely identified by name, path, and domain.
So we can have:
name=value; path=/test1
name=value; path=/test2
But when we read document.cookie, we only get the one that matches the current path.
So in our CookieStorageAdapter, we should use the cookie for the current path. We can't change the current path without reloading.
Therefore, for unit tests we might skip this and rely on integration tests.
Alternatively, we can design the CookieStorageAdapter to use a specific path (maybe the root path) so that it's accessible from all paths. Then we don't have to worry about path.
We can set the cookie with path=/.
So in production, we set the cookie with path=/ and domain= (or a specific domain). Then we don't have the issue.
So for the test, we assume we set the cookie with path=/.
But then the edge case of multiple cookies with the same name but different paths is not applicable because we set with path=/.
So we can skip that edge case.
Other edge cases:
- When the user has disabled localStorage (or cookies). We can simulate by having the storage adapter throw an error.
We can have:
class ThrowingStorageAdapter {
getItem() { throw new Error('storage disabled'); }
setItem() { throw new Error('storage disabled'); }
}
Then we test that BucketManager handles it. How should it handle?
We can decide: if storage fails, we don't set sticky and we assign a new variant every time? Or we try to use a fallback?
We can have:
assignVariant() {
try {
const forced = this.getForcedVariant();
if (forced !== null) { ... }
let stored = this.getStoredVariant();
if (stored !== null) {
return stored;
}
} catch (e) {
// storage error, we ignore and proceed to compute.
}
const variant = this.computeVariant(userKey, config);
try {
this.setStoredVariant(variant);
} catch (e) {
// ignore, we can't set sticky.
}
return variant;
}
Then test:
- With ThrowingStorageAdapter, the first call computes and returns a variant, but does not set storage (so next call will compute again).
But note: if we are forcing, we try to set storage? We should also catch when setting.
Now, for replay probes:
We can use the forceVariant option to force a variant.
We can also have a way to set the storage to a specific value (via the storage adapter) to simulate a user who already has a variant.
So we can:
// To replay a user who has variant 1:
storageAdapter.setItem('feature_bucket', '1');
let variant = bucketManager.assignVariant('user123', config);
// should return 1.
And we can also force:
const bucketManager = new BucketManager(storageAdapter, {forceVariant: 1});
let variant = bucketManager.assignVariant('user123', config);
// should return 1, and also set storage to 1 (if we are setting in the force branch).
But note: if we force and set storage, then the next call without force will return 1 (because stored). So we might want to clear the storage between tests.
We can have a clear() method in the storage adapter.
Let's design the storage adapter interface:
interface StorageAdapter {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
clear(): void; // for testing, to reset.
}
Then in tests, we can use a MockStorageAdapter that stores in a plain object and has clear().
Summary:
We'll create:
class BucketManager {
constructor(storageAdapter, options = {}) {
this.storageAdapter = storageAdapter;
this.forceVariant = options.forceVariant || null;
this.cookieName = options.cookieName || 'feature_bucket';
}
getStoredVariant() {
try {
const value = this.storageAdapter.getItem(this.cookieName);
const parsed = parseInt(value, 10);
return isNaN(parsed) ? null : parsed;
} catch (e) {
return null;
}
}
setStoredVariant(variant) {
try {
this.storageAdapter.setItem(this.cookieName, variant.toString());
} catch (e) {
// ignore
}
}
getForcedVariant() {
return this.forceVariant;
}
assignVariant(userKey, config) {
const forced = this.getForcedVariant();
if (forced !== null) {
this.setStoredVariant(forced);
return forced;
}
let stored = this.getStoredVariant();
if (stored !== null) {
return stored;
}
const variant = this.computeVariant(userKey, config);
this.setStoredVariant(variant);
return variant;
}
computeVariant(userKey, config) {
// simple hash and mapping
const hash = this.hashString(userKey) % 100;
return hash < config.percentage ? config.treatment : config.control;
}
hashString(str) {
// same as above
}
}
Then tests:
describe('Sticky Bucketing', () => {
let storageAdapter, bucketManager;
beforeEach(() => {
storageAdapter = new MockStorageAdapter();
bucketManager = new BucketManager(storageAdapter);
});
test('assigns variant when no storage', () => {
const variant = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(0).or(1);
expect(storageAdapter.getItem('feature_bucket')).toBe(variant.toString());
});
test('returns same variant on next call', () => {
const variant1 = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
const variant2 = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant2).toBe(variant1);
});
test('reassigns when storage has invalid value', () => {
storageAdapter.setItem('feature_bucket', 'invalid');
const variant = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(0).or(1);
// The storage should be updated to the new variant (which is a number)
expect(parseInt(storageAdapter.getItem('feature_bucket'), 10)).toBe(variant);
});
});
describe('Edge Cases', () => {
// ... test with ThrowingStorageAdapter, etc.
});
describe('Replay Probes', () => {
test('forceVariant overrides storage and sets storage', () => {
const storageAdapter = new MockStorageAdapter();
// Set an existing variant in storage
storageAdapter.setItem('feature_bucket', '0');
const bucketManager = new BucketManager(storageAdapter, {forceVariant: 1});
const variant = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(1);
// Now storage should be 1 (because we set it in the force branch)
expect(storageAdapter.getItem('feature_bucket')).toBe('1');
});
test('forceVariant without existing storage', () => {
const storageAdapter = new MockStorageAdapter();
const bucketManager = new BucketManager(storageAdapter, {forceVariant: 1});
const variant = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(1);
expect(storageAdapter.getItem('feature_bucket')).toBe('1');
});
test('replay by setting storage directly', () => {
const storageAdapter = new MockStorageAdapter();
// Simulate a user who has variant 1 in storage
storageAdapter.setItem('feature_bucket', '1');
const bucketManager = new BucketManager(storageAdapter);
const variant = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(1);
});
});
Note: The hash function must be consistent. We are using a simple one for example.
But note: the hash function must be the same between client and server if we want server-side bucketing to match. But that's a separate concern.
This design is for client-side sticky bucketing. We assume the server might also set the cookie? Then we have to be cautious about overwriting.
However, for the test, we are only concerned with the client-side behavior.
We can also test the computeVariant function with different userKeys and percentages to ensure the hash is consistent.
But note: the hash function we used is not a robust one for bucketing (it's just an example). In production, we might use a more uniform hash.
This is a basic framework.
Let's write the code accordingly.
However, note: the test for edge cases with multiple cookies and different paths might require a different storage adapter that simulates the browser's cookie behavior.
We can create a CookieStorageAdapter that uses document.cookie, but in unit tests we might not have a document.
Alternatively, we can have a SimulatedCookieStorageAdapter that uses an object with paths.
class SimulatedCookieStorageAdapter {
constructor() {
this.cookies = {}; // key -> {value, path, domain} but for simplicity, we store by key and path?
// Actually, we need to simulate the browser's cookie jar. But for our test, we set with path=/ so we don't need to worry.
// But for testing the edge case of multiple cookies with same name and different paths, we can:
// When we set a cookie, we store it by (name, path, domain). When we get by name, we return the one that matches the current path (and domain) and is the most specific.
// However, we are setting with path=/ so we will always get that one.
// So we can skip this complexity.
// We'll just store by name and assume we set with path=/.
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value;
}
clear() {
this.store = {};
}
}
Then we can test the edge case of multiple cookies by setting two cookies with the same key? That would overwrite. So we can't.
Therefore, we might not be able to test that edge case with a simple storage adapter.
We might need to adjust: the BucketManager should be able to specify the cookie path and domain when setting? And when reading, we read from the current path.
But if we are setting with path=/, then we are safe.
So we assume we set the cookie with path=/ and that we read the same.
Then the edge case of multiple cookies doesn't apply.
So we can skip that test.
Other edge cases:
- What if the user has a cookie for the same name but set by a different application (with a different path) and we set with path=/ so we override? That's intended.
- What if the user has a cookie that is too long? We set a small value (just a number) so it's safe.
So we are good.
Let's code accordingly.
We'll create:
class MockStorageAdapter {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value;
}
clear() {
this.store = {};
}
}
class ThrowingStorageAdapter {
getItem() { throw new Error('storage disabled'); }
setItem() { throw new Error('storage disabled'); }
clear() {}
}
And then the BucketManager as above.
But note: the getStoredVariant and setStoredVariant catch errors and return null or ignore.
So with ThrowingStorageAdapter, getStoredVariant returns null (because catch returns null) and setStoredVariant does nothing.
We test:
test('with throwing storage, computes new variant every time', () => {
const storageAdapter = new ThrowingStorageAdapter();
const bucketManager = new BucketManager(storageAdapter);
const variant1 = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
// variant1 is 0 or 1.
// storageAdapter.store is empty? We didn't set.
const variant2 = bucketManager.assignVariant('user1', {control: 0, treatment: 1, percentage: 50});
// variant2 might be the same as variant1 by chance? But should be independent?
// Actually, because we don't store, we compute again. It could be same or different by chance.
// We can set a fixed hash function to make it deterministic? In test, we can override the hash function?
// But we are using a hash that depends on the string. So for the same userKey, same hash -> same variant.
// So variant1 and variant2 will be the same because we compute the same way.
// But if we want to test that it doesn't use storage, we can change the hash function? Not easy.
// Alternatively, we can test that the storageAdapter.setItem was never called? But we are catching errors and not setting.
// We can spy on the storageAdapter? We are in unit test, we can check that the store remains empty.
expect(storageAdapter.store['feature_bucket']).toBeUndefined();
// But variant1 and variant2 are the same because computeVariant is deterministic.
// So we can't test that it recomputes? Actually, we can test that it doesn't rely on storage by ensuring that even if we set storage to a different value, it doesn't use it because the getItem throws.
// We can set the storageAdapter to throw on getItem but not on setItem? Then we can see that it doesn't use the storage.
// But in our ThrowingStorageAdapter, both get and set throw. We catch on get and return null, so we compute. Then we try to set and it throws and we catch and ignore.
// So the store remains empty.
// So we can test that the store remains empty and that the variant is the same as computed.
// But note: if we want to test that it computes every time, we can change the config (percentage) and see that the variant changes? But the hash is the same, so if percentage changes, the variant might change.
// Example:
// First call: percentage=50 -> variant A.
// Second call: percentage=30 -> if hash < 30 then treatment else control. So it might change.
// But that's not because of storage, it's because of config change.
// So we can't really test that it recomputes every time without changing the config.
// Alternatively, we can mock the computeVariant to return different values? But we are testing the whole flow.
// Maybe we don't need to test that it recomputes every time? The important thing is that it doesn't use storage when storage is broken.
// We can test that when storage is broken, the stored variant is not set (so the store remains empty) and that the variant returned is the computed one.
// And we can test that when storage works, it uses the stored value.
// So we are good.
});
This seems reasonable.
Let's write the code accordingly.
We'll also consider: what if the user key is the same but the config changes? Should the variant change? Typically, the bucketing is based on the user key and the config (percentage and variant mapping).
So if the config changes, the variant might change even if the user key is the same. But then we have a problem: the stored variant is from the old config.
We might want to include the config in the storage key? Or we should not change config for a running experiment? Or we should reset the storage when config changes?
This is an edge case: if the experiment configuration changes (e.g., we change the percentage or the variant names), then the stored variant might be invalid.
We can handle by:
- Including a version or hash of the config in the storage key? So if config changes, we don't read the old stored variant.
- Or we can store the config along with the variant? Then when we read, we check if the stored config matches the current config.
- Or we can just say: if the config changes, we don't use the stored variant? That might be acceptable because the experiment has changed.
But note: the sticky bucketing is for the same experiment. If the experiment changes, we might want to re-bucket.
So we can change the storage key to include an experiment id or version.
Let's assume we have an experimentId in the config.
config: {
experimentId: 'experiment_1',
... other config
}
Then we store the variant under a key that includes the experimentId.
So:
storageKey = `feature_bucket_${config.experimentId}`;
Then if the experimentId changes, we don't read the old one.
So we adjust:
class BucketManager {
constructor(storageAdapter, options = {}) {
this.storageAdapter = storageAdapter;
this.forceVariant = options.forceVariant || null;
this.cookieNamePrefix = options.cookieNamePrefix || 'feature_bucket';
}
getStorageKey(config) {
return `${this.cookieNamePrefix}_${config.experimentId}`;
}
getStoredVariant(config) {
const key = this.getStorageKey(config);
try {
const value = this.storageAdapter.getItem(key);
const parsed = parseInt(value, 10);
return isNaN(parsed) ? null : parsed;
} catch (e) {
return null;
}
}
setStoredVariant(config, variant) {
const key = this.getStorageKey(config);
try {
this.storageAdapter.setItem(key, variant.toString());
} catch (e) {
// ignore
}
}
assignVariant(userKey, config) {
const forced = this.getForcedVariant();
if (forced !== null) {
this.setStoredVariant(config, forced);
return forced;
}
let stored = this.getStoredVariant(config);
if (stored !== null) {
return stored;
}
const variant = this.computeVariant(userKey, config);
this.setStoredVariant(config, variant);
return variant;
}
// ... computeVariant and hashString as before.
}
Then in tests, we must provide a config with experimentId.
This also solves the issue of multiple experiments using the same storage.
Now, the replay probe: we can force a variant for a specific experiment by setting the forceVariant and the experimentId in the config? Actually, the force is global?
We might want to force per experiment? But the forceVariant is set in the BucketManager and applies to any experiment? That might be bad.
We can change the force to be per experiment? Or we can have the force as an option that includes the experimentId?
Alternatively, we can have the forceVariant be an object: {experimentId: variant}? Then we look up by experimentId.
But for simplicity, let's assume we are testing one experiment at a time. And the BucketManager is created per experiment?
Actually, we might have one BucketManager for all experiments? Then we need to handle multiple experiments.
Let's redesign: the BucketManager is for a specific experiment? Then we pass the config (with experimentId) to assignVariant.
But then the forceVariant is for that experiment? We can set the forceVariant in the options when creating the BucketManager for that experiment.
So we create a BucketManager per experiment? That might be heavy? But we can reuse the same storage adapter.
Alternatively, we can have:
assignVariant(experimentConfig) {
// experimentConfig has experimentId, etc.
}
and the forceVariant is set globally? Then if we have multiple experiments, the forceVariant might force the same variant for all? That's not intended.
So we should have forceVariant per experiment.
We can change:
getForcedVariant(config) {
// if this.forceVariant is an object, then return this.forceVariant[config.experimentId] or null.
// if this.forceVariant is a number, then return that number? But then it's global.
// Let's make it an object.
if (this.forceVariant && typeof this.forceVariant === 'object') {
return this.forceVariant[config.experimentId] || null;
}
return null;
}
Then we set:
const bucketManager = new BucketManager(storageAdapter, {forceVariant: {experiment_1: 1}});
But for simplicity in tests, we can create a BucketManager per experiment and set forceVariant as a number.
Since we are testing one experiment at a time, we can do:
const bucketManager = new BucketManager(storageAdapter, {forceVariant: 1});
and then when we call assignVariant, we pass the config for that experiment.
But then if we have multiple experiments, we would need multiple BucketManagers? Or we change the design.
Let's stick to one experiment per BucketManager for simplicity.
So in the test, we create a BucketManager for a specific experiment (with a specific experimentId) and then forceVariant applies to that experiment.
Then we don't need to change getForcedVariant.
But note: the forceVariant is set in the constructor and then used for every call to assignVariant, regardless of the experimentId?
We are not checking the experimentId in the force. So if we use the same BucketManager for multiple experiments, the force will apply to all.
We can change:
assignVariant(userKey, config) {
const forced = this.getForcedVariant(config);
...
}
getForcedVariant(config) {
if (this.forceVariant === null) return null;
// if forceVariant is a function? Or we can have forceVariant be an object keyed by experimentId.
if (typeof this.forceVariant === 'object') {
return this.forceVariant[config.experimentId] || null;
}
// if it's a number, then we assume it's for the current experiment? But we don't know the experimentId?
// So we should not allow number if we have multiple experiments.
// Let's force the user to set an object for multiple experiments.
// But for single experiment, we can set a number and then in getForcedVariant, we return that number.
// However, we don't have the experimentId in the forceVariant? We can't map.
// So we change the design: forceVariant must be an object that maps experimentId to variant.
// Then:
if (this.forceVariant && this.forceVariant[config.experimentId] !== undefined) {
return this.forceVariant[config.experimentId];
}
return null;
}
Then in tests:
const bucketManager = new BucketManager(storageAdapter, {forceVariant: {experiment_1: 1}});
And for a single experiment, we set:
{forceVariant: {experiment_1: 1}}
Then when we call assignVariant with config for experiment_1, we get 1.
But if we call with config for experiment_2, we get no force.
This is better.
Let's update the code accordingly.
Summary of changes:
- Storage key includes experimentId.
- Force variant is an object keyed by experimentId.
Now, the replay probe: we can force a variant for a specific experiment by setting the forceVariant for that experimentId.
We can also set the storage directly for that experiment (by setting the storage key for that experimentId).
So we can replay a scenario by:
storageAdapter.setItem(`feature_bucket_experiment_1`, '1');
const bucketManager = new BucketManager(storageAdapter);
const variant = bucketManager.assignVariant('user1', {experimentId: 'experiment_1', ...});
Or by force:
const bucketManager = new BucketManager(storageAdapter, {forceVariant: {experiment_1: 1}});
const variant = bucketManager.assignVariant('user1', {experimentId: 'experiment_1', ...});
Now, the test for replay probes:
test('replay by forced variant', () => {
const storageAdapter = new MockStorageAdapter();
const bucketManager = new BucketManager(storageAdapter, {forceVariant: {experiment_1: 1}});
const variant = bucketManager.assignVariant('user1', {experimentId: 'experiment_1', control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(1);
// Also check that storage was set for that experiment.
expect(storageAdapter.getItem('feature_bucket_experiment_1')).toBe('1');
});
test('replay by setting storage', () => {
const storageAdapter = new MockStorageAdapter();
storageAdapter.setItem('feature_bucket_experiment_1', '1');
const bucketManager = new BucketManager(storageAdapter);
const variant = bucketManager.assignVariant('user1', {experimentId: 'experiment_1', control: 0, treatment: 1, percentage: 50});
expect(variant).toBe(1);
});
This should work.
Now, we have a plan.
Let's write the code for the BucketManager and the tests.
Note: In production, we might use cookies instead of localStorage. We can create a CookieStorageAdapter that uses document.cookie.
But for the test, we are using a mock.
We'll provide:
class LocalStorageAdapter {
constructor() {
this.store = {};
}
getItem(key) {
return localStorage.getItem(key); // but in test we don't have localStorage? We can use a mock global.
// Actually, in a test environment (like JSDOM) we might have localStorage. But we are writing a unit test that doesn't depend on the environment.
// So we should use the mock.
// We'll change: the BucketManager takes an adapter, so we can pass a LocalStorageAdapter that wraps the real localStorage.
// But for unit tests, we pass a MockStorageAdapter.
// So we don't need to write a LocalStorageAdapter? We can write one for production code.
// Let's write:
class LocalStorageAdapter {
getItem(key) {
return window.localStorage.getItem(key);
}
setItem(key, value) {
window.localStorage.setItem(key, value);
}
clear() {
// we can't clear everything? We can clear only our keys? Or we don't implement clear for production?
// For testing we need clear. So we might not use this in tests.
}
}
// But we are in a test file? We are writing the BucketManager in a separate file and then test it.
// So we can have:
// In production code:
// import { LocalStorageAdapter } from './adapters';
// In test:
// import { MockStorageAdapter } from './test-adapters';
// We'll leave the adapters out of the BucketManager code.
}
}
But we are designing the test, so we can write the BucketManager and the adapters in the same file for simplicity? Or separate.
Since the question is about designing the test, we can assume we have the BucketManager and we are writing tests for it.
We'll write the BucketManager class and then the test suite using MockStorageAdapter.
Let's code accordingly.
However, note: the BucketManager uses the storageAdapter, and we are going to test with a mock.
We'll write:
// bucketManager.js
export class BucketManager {
constructor(storageAdapter, options = {}) {
this.storageAdapter = storageAdapter;
this.forceVariant = options.forceVariant || null; // object mapping experimentId to variant
this.cookieNamePrefix = options.cookieNamePrefix || 'feature_bucket';
}
getStorageKey(config) {
if (!config.experimentId) {
throw new Error('experimentId is required in config');
}
return `${this.cookieNamePrefix}_${config.experimentId}`;
}
getStoredVariant(config) {
const key = this.getStorageKey(config);
try {
const value = this.storageAdapter.getItem(key);
const parsed = parseInt(value, 10);
return isNaN(parsed) ? null : parsed;
} catch (e) {
return null;
}
}
setStoredVariant(config, variant) {
const key = this.getStorageKey(config);
try {
this.storageAdapter.setItem(key, variant.toString());
} catch (e) {
// ignore
}
}
getForcedVariant(config) {
if (!this.forceVariant) return null;
if (typeof this.forceVariant === 'object' && this.forceVariant[config.experimentId] !== undefined) {
return this.forceVariant[config.experimentId];
}
return null;
}
assignVariant(userKey, config) {
const forced = this.getForcedVariant(config);
if (forced !== null) {
this.setStoredVariant(config, forced);
return forced;
}
let stored = this.getStoredVariant(config);
if (stored !== null) {
return stored;
}
const variant = this.computeVariant(userKey, config);
this.setStoredVariant(config, variant);
return variant;
}
computeVariant(userKey, config) {
const hash = this.hashString(userKey) % 100;
return hash < config.percentage ? config.treatment : config.control;
}
hashString(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
}
Then the tests:
// bucketManager.test.js
class MockStorageAdapter {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value;
}
clear() {
this.store = {};
}
}
class ThrowingStorageAdapter {
getItem() { throw new Error('storage disabled'); }
setItem() { throw new Error('storage disabled'); }
clear() {}
}
describe('BucketManager', () => {
let storageAdapter, bucketManager;
const defaultConfig = {
experimentId: 'experiment_1',
control: 0,
treatment: 1,
percentage: 50
};
beforeEach(() => {
storageAdapter = new MockStorageAdapter();
bucketManager = new BucketManager(storageAdapter);
});
describe('Sticky Bucketing', () => {
test('assigns variant when no storage', () => {
const variant = bucketManager.assignVariant('user1', defaultConfig);
expect(variant).toBe(0).or(1);
expect(storageAdapter.store[`feature_bucket_${defaultConfig.experimentId}`]).toBe(variant.toString());
});
test('returns same variant on next call', () => {
const variant1 = bucketManager.assignVariant('user1', defaultConfig);
const variant2 = bucketManager.assignVariant('user1', defaultConfig);
expect(variant2).toBe(variant1);
});
test('reassigns when storage has invalid value', () => {
storageAdapter.setItem(`feature_bucket_${defaultConfig.experimentId}`, 'invalid');
const variant = bucketManager.assignVariant('user1', defaultConfig);
expect(variant).toBe(0).or(1);
expect(parseInt(storageAdapter.store[`feature_bucket_${defaultConfig.experimentId}`], 10)).toBe(variant);
});
});
describe('Edge Cases', () => {
test('throws storage error and recovers', () => {
const throwingAdapter = new ThrowingStorageAdapter();
const bm = new BucketManager(throwingAdapter);
const variant1 = bm.assignVariant('user1', defaultConfig);
// Should compute and return a variant.
expect(variant1).toBe(0).or(1);
// The throwingAdapter.store is empty.
expect(throwingAdapter.store).toEqual({});
// Second call should also compute (because storage is broken) and return the same variant (because same userKey and config)
const variant2 = bm.assignVariant('user1', defaultConfig);
expect(variant2).toBe(variant1);
});
test('handles missing experimentId', () => {
expect(() => bucketManager.assignVariant('user1', {})).toThrow('experimentId is required in config');
});
test('handles when storage adapter returns null for a key that was set by another experiment', () => {
// Set a storage for a different experiment
storageAdapter.setItem('feature_bucket_experiment_2', '1');
const variant = bucketManager.assignVariant('user1', defaultConfig);
// Should not use the storage for experiment_2, so it should compute a new variant.
// We can't predict the variant, but we know it should be either 0 or 1.
expect(variant).toBe(0).or(1);
// And we should have set the storage for experiment_1.
expect(storageAdapter.store[`feature_bucket_${defaultConfig.experimentId}`]).toBe(variant.toString());
});
});
describe('Replay Probes', () => {
test('forceVariant overrides storage and sets storage', () => {
// Set existing storage for experiment_1
storageAdapter.setItem(`feature_bucket_${defaultConfig.experimentId}`, '0');
const bm = new BucketManager(storageAdapter, {forceVariant: {[defaultConfig.experimentId]: 1}});
const variant = bm.assignVariant('user1', defaultConfig);
expect(variant).toBe(1);
expect(storageAdapter.store[`feature_bucket_${defaultConfig.experimentId}`]).toBe('1');
});
test('forceVariant without existing storage', () => {
const bm = new BucketManager(storageAdapter, {forceVariant: {[defaultConfig.experimentId]: 1}});
const variant = bm.assignVariant('user1', defaultConfig);
expect(variant).toBe(1);
expect(storageAdapter.store[`feature_bucket_${defaultConfig.experimentId}`]).toBe('1');
});
test('replay by setting storage directly', () => {
storageAdapter.setItem(`feature_bucket_${defaultConfig.experimentId}`, '1');
const bm = new BucketManager(storageAdapter);
const variant = bm.assignVariant('user1', defaultConfig);
expect(variant).toBe(1);
});
test('forceVariant for one experiment does not affect another', () => {
const config2 = {...defaultConfig, experimentId: 'experiment_2'};
const bm = new BucketManager(storageAdapter, {forceVariant: {[defaultConfig.experimentId]: 1}});
const variant1 = bm.assignVariant('user1', defaultConfig);
expect(variant1).toBe(1);
const variant2 = bm.assignVariant('user1', config2);
// For experiment_2, no force, so it should compute.
expect(variant2).toBe(0).or(1);
// And storage for experiment_2 should be set.
expect(storageAdapter.store[`feature_bucket_${config2.experimentId}`]).toBe(variant2.toString());
});
});
describe('computeVariant', () => {
test('returns correct variant based on hash and percentage', () => {
// We need a fixed hash function to test specific cases.
// We can mock the hashString method.
const bm = new BucketManager(storageAdapter);
// Spy on hashString and return a fixed value.
const hashSpy = jest.spyOn(bm, 'hashString').mockReturnValue(40); // 40% into the range
// With percentage 50, hash 40 < 50 -> treatment.
const variant = bm.computeVariant('any', defaultConfig);
expect(variant).toBe(defaultConfig.treatment);
hashSpy.mockReturnValue(60);
const variant2 = bm.computeVariant('any', defaultConfig);
expect(variant2).toBe(defaultConfig.control);
hashSpy.mockRestore();
});
});
});
This should cover the requirements.
Note: The hashString method is not a uniform hash, but for testing we can mock it.
We are testing the sticky bucketing, edge cases (storage errors, multiple experiments, invalid storage) and replay probes (force and storage set).
We are not testing the actual cookie path/domain because we are using a storage adapter that uses a simple key-value store.
For production, we would have a CookieStorageAdapter that uses document.cookie with path=/ and maybe a domain.
We can write a CookieStorageAdapter for production:
class CookieStorageAdapter {
constructor(options = {}) {
this.path = options.path || '/';
this.domain = options.domain || '';
}
getItem(key) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [name, value] = cookie.split('=').map(c => c.trim());
if (name === key) {
return decodeURIComponent(value);
}
}
return null;
}
setItem(key, value) {
let cookie = `${key}=${encodeURIComponent(value)}; path=${this.path}`;
if (this.domain) {
cookie += `; domain=${this.domain}`;
}
document.cookie = cookie;
}
clear() {
// We can't clear a specific cookie without knowing the path and domain? We can set an empty value with the same path and domain and expiration in the past.
// But we don't have the key? We would need to store the keys we set?
// Actually, we don't need clear for production. We can leave it empty.
}
}
Then in production, we use:
const storageAdapter = new CookieStorageAdapter({path: '/', domain: '.example.com'});
But for the test, we use MockStorageAdapter.
This completes the design.
Let me know if you have any questions.
I'll design a comprehensive client-side feature evaluation consistency test with三個核心组件:sticky bucketing、edge cases、replay probes. This ensures reliable feature flag/routing decisions in production environments.
Architecture Overview
├── Core Engine
├── Sticky Bucketing System
├── Edge Case Handler
├── Replay & Debug System
└── Test Harness
1. STICKY BUCKETING IMPLEMENTATION
A. Storage Strategy
class StickyBucketing {
constructor(config = {}) {
this.storage = config.storage || 'localStorage'; // 'localStorage', 'cookie', 'sessionStorage'
this.cookieDomain = config.cookieDomain || window.location.hostname;
this.cookiePath = config.cookiePath || '/';
this.ttlDays = config.ttlDays || 365;
this.keyPrefix = config.keyPrefix || 'fb_'; // feature bucket prefix
}
// Generate deterministic bucket based on user identifier
hashUser(userId, experimentId, salt = '') {
const str = `${userId}:${experimentId}:${salt}`;
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
// Get or assign sticky bucket
getOrAssignBucket(userId, experimentId, weights, options = {}) {
const storageKey = this.getStorageKey(experimentId);
// 1. Check forced override (debug/replay)
const forced = this.getForcedBucket(experimentId);
if (forced !== null) return forced;
// 2. Check existing sticky assignment
const existing = this.readStorage(storageKey);
if (existing !== null && this.isValidBucket(existing, weights)) {
return existing;
}
// 3. Calculate new bucket
const newBucket = this.calculateBucket(userId, experimentId, weights);
// 4. Persist (with error handling)
try {
this.writeStorage(storageKey, newBucket, options);
} catch (e) {
console.warn('Sticky bucket storage failed:', e);
// Fallback: session-only assignment
return newBucket;
}
return newBucket;
}
calculateBucket(userId, experimentId, weights) {
const hash = this.hashUser(userId, experimentId);
const normalizedHash = hash % 10000; // 0-9999
let cumulative = 0;
for (const [bucket, weight] of Object.entries(weights)) {
cumulative += weight * 100; // Convert percentage to 0-10000 scale
if (normalizedHash < cumulative) {
return bucket;
}
}
return Object.keys(weights)[0]; // Fallback to first bucket
}
}
B. Storage Abstraction
class StorageAdapter {
read(key) {
switch (this.storage) {
case 'localStorage':
return localStorage.getItem(key);
case 'sessionStorage':
return sessionStorage.getItem(key);
case 'cookie':
return this.readCookie(key);
default:
throw new Error(`Unknown storage: ${this.storage}`);
}
}
write(key, value, ttlDays) {
switch (this.storage) {
case 'localStorage':
localStorage.setItem(key, value);
break;
case 'sessionStorage':
sessionStorage.setItem(key, value);
break;
case 'cookie':
this.writeCookie(key, value, ttlDays);
break;
}
}
readCookie(name) {
const match = document.cookie.match(
new RegExp('(^| )' + name + '=([^;]+)')
);
return match ? decodeURIComponent(match[2]) : null;
}
writeCookie(name, value, days) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=${this.cookiePath};domain=${this.cookieDomain};SameSite=Lax`;
}
}
2. EDGE CASE HANDLING
A. Edge Case Detection & Recovery
class EdgeCaseHandler {
constructor(bucketManager) {
this.bucketManager = bucketManager;
this.detectedIssues = new Map();
this.maxRetries = 3;
}
async assignWithEdgeHandling(userId, experimentId, weights) {
const context = {
userId,
experimentId,
weights,
timestamp: Date.now(),
userAgent: navigator.userAgent,
url: window.location.href
};
try {
// 1. Validate inputs
this.validateInputs(context);
// 2. Check storage availability
await this.checkStorageHealth();
// 3. Detect concurrency issues
await this.detectConcurrencyIssues(context);
// 4. Detect tampering
this.detectTampering(context);
// 5. Perform assignment
return await this.bucketManager.getOrAssignBucket(
userId,
experimentId,
weights
);
} catch (error) {
return this.handleFailure(context, error);
}
}
validateInputs(context) {
if (!context.userId || typeof context.userId !== 'string') {
throw new Error('Invalid userId: must be non-empty string');
}
if (!context.experimentId || typeof context.experimentId !== 'string') {
throw new Error('Invalid experimentId');
}
const weightSum = Object.values(context.weights).reduce((a, b) => a + b, 0);
if (Math.abs(weightSum - 1) > 0.001) {
throw new Error(`Weights must sum to 1, got ${weightSum}`);
}
}
async checkStorageHealth() {
const testKey = 'fb_health_check_' + Date.now();
try {
// Test write
this.bucketManager.writeStorage(testKey, 'test');
const read = this.bucketManager.readStorage(testKey);
if (read !== 'test') {
throw new Error('Storage read/write mismatch');
}
// Cleanup
this.bucketManager.deleteStorage(testKey);
// Check quota (for localStorage)
if (this.bucketManager.storage === 'localStorage') {
this.checkStorageQuota();
}
} catch (e) {
this.detectedIssues.set('storage_health', {
error: e.message,
timestamp: Date.now(),
userAgent: navigator.userAgent
});
throw new Error('Storage health check failed: ' + e.message);
}
}
checkStorageQuota() {
try {
const testSize = 5 * 1024 * 1024; // 5MB test
const largeValue = 'x'.repeat(testSize);
localStorage.setItem('fb_quota_test', largeValue);
localStorage.removeItem('fb_quota_test');
} catch (e) {
if (e.name === 'QuotaExceededError') {
this.detectedIssues.set('quota_exceeded', {
timestamp: Date.now(),
approxUsage: this.estimateStorageUsage()
});
}
}
}
detectConcurrencyIssues(context) {
// Use atomic operations where possible
const lockKey = `fb_lock_${context.experimentId}`;
const lockValue = `${Date.now()}_${Math.random()}`;
const lockTtl = 5000; // 5 seconds
try {
// Try to acquire lock
const existing = this.bucketManager.readStorage(lockKey);
if (existing) {
const lockAge = Date.now() - parseInt(existing.split('_')[0]);
if (lockAge < lockTtl) {
throw new Error('Concurrent assignment detected');
}
}
this.bucketManager.writeStorage(lockKey, lockValue, 0.01); // Short TTL
// Release lock after operation (best effort)
setTimeout(() => {
try {
this.bucketManager.deleteStorage(lockKey);
} catch (e) {}
}, 100);
} catch (e) {
this.detectedIssues.set('concurrency', {
experimentId: context.experimentId,
timestamp: Date.now()
});
// Continue - this is non-fatal
}
}
detectTampering(context) {
// Check for signs of manual cookie modification
const storageKey = this.bucketManager.getStorageKey(context.experimentId);
const rawValue = this.bucketManager.readRawStorage(storageKey);
if (rawValue && !/^\d+$/.test(rawValue)) {
this.detectedIssues.set('tampering', {
experimentId: context.experimentId,
rawValue,
timestamp: Date.now()
});
// Invalid value will be treated as no assignment
this.bucketManager.deleteStorage(storageKey);
}
}
handleFailure(context, error) {
// Fallback strategies:
// 1. Session-based assignment (no persistence)
// 2. Global default bucket
// 3. Error reporting
this.detectedIssues.set(`failure_${context.experimentId}`, {
error: error.message,
context,
timestamp: Date.now()
});
// Report to monitoring
this.reportIssue(context, error);
// Return safe default
return this.getFallbackBucket(context.experimentId);
}
getFallbackBucket(experimentId) {
// Return control group as safe default
return 'control';
}
}
B. Specific Edge Cases Covered
- Storage Quota Exceeded → Switch to sessionStorage
- Third-Party Cookie Blocking → Use localStorage fallback
- Incognito/Private Mode → Handle storage API unavailability
- Time Zone/DST Changes → Use UTC timestamps
- Clock Skew → TTL validation with ±5min tolerance
- UserIdentifier Changes → Handle null/undefined/empty IDs
- Multiple Tabs/Windows → Atomic operations with locks
- Browser Back/Forward Cache → Detect pagehide/beforeunload
3. REPLAY PROBES SYSTEM
A. Replay Controller
class ReplayProbes {
constructor(bucketManager) {
this.bucketManager = bucketManager;
this.recording = false;
this.recordedEvents = [];
this.forcedStates = new Map();
this.replayQueue = [];
this.maxRecordSize = 1000; // Limit memory usage
}
// Enable recording for debugging
startRecording() {
this.recording = true;
this.recordedEvents = [];
// Hook into bucketManager
const originalAssign = this.bucketManager.getOrAssignBucket.bind(this.bucketManager);
this.bucketManager.getOrAssignBucket = async (userId, expId, weights, options) => {
const result = await originalAssign(userId, expId, weights, options);
if (this.recording) {
this.recordEvent({
type: 'assignment',
timestamp: Date.now(),
userId,
experimentId: expId,
weights: JSON.parse(JSON.stringify(weights)),
result,
storageKey: this.bucketManager.getStorageKey(expId),
storageValue: this.bucketManager.readStorage(this.bucketManager.getStorageKey(expId)),
userAgent: navigator.userAgent,
url: window.location.href
});
}
return result;
};
}
stopRecording() {
this.recording = false;
return this.recordedEvents.slice(); // Return copy
}
recordEvent(event) {
this.recordedEvents.push(event);
// Trim if too large
if (this.recordedEvents.length > this.maxRecordSize) {
this.recordedEvents = this.recordedEvents.slice(-500);
}
}
// Force specific bucket for replay
forceBucket(experimentId, bucket) {
this.forcedStates.set(experimentId, bucket);
// Set storage immediately
const storageKey = this.bucketManager.getStorageKey(experimentId);
this.bucketManager.writeStorage(storageKey, bucket);
}
clearForce(experimentId) {
this.forcedStates.delete(experimentId);
const storageKey = this.bucketManager.getStorageKey(experimentId);
this.bucketManager.deleteStorage(storageKey);
}
// Generate replay script
generateReplayScript(events, targetUserId) {
const script = [];
script.push(`// Replay generated at ${new Date().toISOString()}`);
script.push(`// Target userId: ${targetUserId}`);
script.push(`// Total events: ${events.length}`);
script.push('');
for (const event of events) {
if (event.userId !== targetUserId) continue;
script.push(`// Event: ${event.type} at ${new Date(event.timestamp).toISOString()}`);
script.push(`// Experiment: ${event.experimentId}`);
script.push(`// Result: ${event.result}`);
script.push(`BucketManager.forceBucket('${event.experimentId}', ${event.result});`);
script.push(`const result = await BucketManager.assign('${event.userId}', '${event.experimentId}', ${JSON.stringify(event.weights)});`);
script.push(`console.assert(result === ${event.result}, 'Mismatch: expected ${event.result}, got', result);`);
script.push('');
}
return script.join('\n');
}
// Analyze consistency
analyzeConsistency(events) {
const analysis = {
totalEvents: events.length,
experiments: new Set(),
bucketsPerExperiment: new Map(),
inconsistencies: [],
storageReads: 0,
storageWrites: 0,
forcedAssignments: 0
};
for (const event of events) {
analysis.experiments.add(event.experimentId);
if (!analysis.bucketsPerExperiment.has(event.experimentId)) {
analysis.bucketsPerExperiment.set(event.experimentId, new Set());
}
analysis.bucketsPerExperiment.get(event.experimentId).add(event.result);
// Count storage operations (inferred from event data)
if (event.storageValue !== null) {
analysis.storageReads++;
}
if (event.type === 'assignment' && event.storageValue === event.result.toString()) {
analysis.storageWrites++;
}
// Check for forced assignments
if (this.forcedStates.has(event.experimentId) &&
this.forcedStates.get(event.experimentId) === event.result) {
analysis.forcedAssignments++;
}
}
// Check for multi-bucket experiments (shouldn't happen with proper bucketing)
for (const [expId, buckets] of analysis.bucketsPerExperiment) {
if (buckets.size > 1) {
analysis.inconsistencies.push({
experimentId: expId,
buckets: Array.from(buckets),
message: 'Multiple buckets assigned for same user'
});
}
}
return analysis;
}
}
B. Replay Debug UI (Optional)
class ReplayDebugUI {
constructor(replayProbes) {
this.replayProbes = replayProbes;
this.uiElement = this.createUI();
}
createUI() {
const div = document.createElement('div');
div.style.cssText = `
position: fixed; bottom: 20px; right: 20px;
background: white; border: 2px solid #333;
padding: 10px; z-index: 999999; font-family: monospace;
max-height: 400px; overflow-y: auto;
`;
div.innerHTML = `
<h4>Feature Replay Debug</h4>
<button onclick="window.replayDebug.toggleRecording()">
Toggle Recording
</button>
<button onclick="window.replayDebug.forceCurrent()">
Force Current Bucket
</button>
<button onclick="window.replayDebug.analyze()">
Analyze Consistency
</button>
<button onclick="window.replayDebug.exportReplay()">
Export Replay Script
</button>
<div id="replay-status"></div>
`;
document.body.appendChild(div);
window.replayDebug = this;
return div;
}
toggleRecording() {
if (this.replayProbes.recording) {
const events = this.replayProbes.stopRecording();
this.showAnalysis(this.replayProbes.analyzeConsistency(events));
} else {
this.replayProbes.startRecording();
this.updateStatus('Recording...');
}
}
forceCurrent() {
const expId = prompt('Experiment ID:');
const bucket = prompt('Bucket to force (e.g., "control", "treatment"):');
if (expId && bucket) {
this.replayProbes.forceBucket(expId, bucket);
this.updateStatus(`Forced ${expId} → ${bucket}`);
}
}
analyze() {
const events = this.replayProbes.recordedEvents;
const analysis = this.replayProbes.analyzeConsistency(events);
this.showAnalysis(analysis);
}
showAnalysis(analysis) {
const status = document.getElementById('replay-status');
status.innerHTML = `
<h5>Analysis Results</h5>
<p>Total events: ${analysis.totalEvents}</p>
<p>Experiments: ${Array.from(analysis.experiments).join(', ')}</p>
<p>Storage reads: ${analysis.storageReads}</p>
<p>Storage writes: ${analysis.storageWrites}</p>
<p>Forced assignments: ${analysis.forcedAssignments}</p>
${analysis.inconsistencies.length > 0 ?
`<p style="color:red">Inconsistencies found:</p>` +
analysis.inconsistencies.map(i =>
`<div style="color:red; margin-left:10px">
${i.experimentId}: ${i.buckets.join(', ')}
</div>`
).join('') :
'<p style="color:green">No inconsistencies detected</p>'
}
`;
}
exportReplay() {
const events = this.replayProbes.recordedEvents;
const userId = prompt('User ID to replay for:');
if (userId) {
const script = this.replayProbes.generateReplayScript(events, userId);
const blob = new Blob([script], {type: 'text/javascript'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `replay_${userId}_${Date.now()}.js`;
a.click();
URL.revokeObjectURL(url);
}
}
updateStatus(msg) {
document.getElementById('replay-status').textContent = msg;
}
}
4. TEST HARNESS & VALIDATION
A. Automated Test Suite
class ConsistencyTestSuite {
constructor() {
this.tests = [];
this.results = [];
}
async runAllTests() {
console.log('Starting feature evaluation consistency tests...');
for (const test of this.tests) {
try {
await test.run();
this.results.push({ name: test.name, passed: true });
} catch (error) {
this.results.push({
name: test.name,
passed: false,
error: error.message
});
}
}
this.printSummary();
return this.results;
}
addTest(name, testFn) {
this.tests.push({ name, run: testFn });
}
printSummary() {
console.log('\n=== TEST SUMMARY ===');
const passed = this.results.filter(r => r.passed).length;
const total = this.results.length;
console.log(`Passed: ${passed}/${total}`);
this.results.forEach(r => {
const status = r.passed ? '✓' : '✗';
console.log(`${status} ${r.name}${r.error ? ': ' + r.error : ''}`);
});
// Generate health score
const healthScore = (passed / total) * 100;
console.log(`\nConsistency Health Score: ${healthScore.toFixed(1)}%`);
if (healthScore < 100) {
console.warn('CONSISTENCY ISSUES DETECTED - Review failed tests');
}
}
}
// Example test implementations
const stickinessTests = [
{
name: 'Sticky assignment persists across sessions',
run: async () => {
const adapter = new MockStorageAdapter();
const bucketManager = new BucketManager(adapter);
const userId = 'test_user_' + Date.now();
const bucket1 = await bucketManager.assign(userId, 'exp1', {control: 0.5, treatment: 0.5});
const bucket2 = await bucketManager.assign(userId, 'exp1', {control: 0.5, treatment: 0.5});
if (bucket1 !== bucket2) {
throw new Error(`Stickiness failed: ${bucket1} !== ${bucket2}`);
}
}
},
{
name: 'Different experiments use independent buckets',
run: async () => {
const adapter = new MockStorageAdapter();
const bucketManager = new BucketManager(adapter);
const userId = 'test_user_' + Date.now();
const bucket1 = await bucketManager.assign(userId, 'exp1', {control: 0.5, treatment: 0.5});
const bucket2 = await bucketManager.assign(userId, 'exp2', {control: 0.5, treatment: 0.5});
// Different experiments should not interfere
if (bucket1 === bucket2) {
throw new Error('Experiments should have independent buckets');
}
}
}
];
const edgeCaseTests = [
{
name: 'Handles storage quota exceeded',
run: async () => {
const adapter = new QuotaExceededAdapter();
const bucketManager = new BucketManager(adapter);
// Should fallback gracefully
const bucket = await bucketManager.assign('user', 'exp', {control: 0.5, treatment: 0.5});
if (bucket === null) {
throw new Error('Should return default bucket on quota exceeded');
}
}
},
{
name: 'Handles malformed storage values',
run: async () => {
const adapter = new MockStorageAdapter();
adapter.setItem('fb_exp1', 'corrupted_value');
const bucketManager = new BucketManager(adapter);
const bucket = await bucketManager.assign('user', 'exp1', {control: 0.5, treatment: 0.5});
// Should recover and assign new bucket
if (bucket === null) {
throw new Error('Should recover from malformed storage');
}
}
}
];
const replayTests = [
{
name: 'Recording captures assignment events',
run: async () => {
const adapter = new MockStorageAdapter();
const bucketManager = new BucketManager(adapter);
const replay = new ReplayProbes(bucketManager);
replay.startRecording();
await bucketManager.assign('user1', 'exp1', {control: 0.5, treatment: 0.5});
const events = replay.stopRecording();
if (events.length === 0) {
throw new Error('No events recorded');
}
if (events[0].userId !== 'user1') {
throw new Error('Incorrect user recorded');
}
}
}
];
B. Mock Storage Adapters for Testing
class MockStorageAdapter {
constructor() {
this.store = {};
this.shouldFail = false;
this.quotaExceeded = false;
}
getItem(key) {
if (this.shouldFail) throw new Error('Storage unavailable');
if (this.quotaExceeded && key.includes('fb_')) {
throw new Error('QuotaExceededError');
}
return this.store[key] || null;
}
setItem(key, value) {
if (this.shouldFail) throw new Error('Storage unavailable');
if (this.quotaExceeded && key.includes('fb_')) {
throw new Error('QuotaExceededError');
}
this.store[key] = value;
}
removeItem(key) {
delete this.store[key];
}
clear() {
this.store = {};
}
}
class UnstableStorageAdapter extends MockStorageAdapter {
constructor(failureRate = 0.3) {
super();
this.failureRate = failureRate;
}
getItem(key) {
if (Math.random() < this.failureRate) {
throw new Error('Random storage failure');
}
return super.getItem(key);
}
}
5. INTEGRATION & MONITORING
A. Health Monitoring
class ConsistencyMonitor {
constructor(bucketManager, edgeHandler, replayProbes) {
this.bucketManager = bucketManager;
this.edgeHandler = edgeHandler;
this.replayProbes = replayProbes;
this.metrics = {
totalAssignments: 0,
stickyHitRate: 0,
edgeCaseCount: 0,
storageFailures: 0,
inconsistentAssignments: 0
};
}
async assignAndMonitor(userId, experimentId, weights) {
this.metrics.totalAssignments++;
try {
const startTime = performance.now();
const bucket = await this.edgeHandler.assignWithEdgeHandling(
userId, experimentId, weights
);
const duration = performance.now() - startTime;
// Record metrics
if (duration > 100) {
this.reportSlowAssignment(duration);
}
// Sample edge cases for monitoring
if (this.edgeHandler.detectedIssues.size > 0) {
this.metrics.edgeCaseCount++;
this.reportEdgeCases(this.edgeHandler.detectedIssues);
}
return bucket;
} catch (error) {
this.metrics.storageFailures++;
this.reportCritical(error);
return 'control'; // Safe fallback
}
}
reportSlowAssignment(duration) {
// Send to monitoring
console.warn(`Slow assignment: ${duration}ms`);
}
reportEdgeCases(issues) {
for (const [type, data] of issues) {
console.warn(`Edge case detected: ${type}`, data);
// Send to analytics
}
}
reportCritical(error) {
console.error('Critical bucketing error:', error);
// Send to error tracking (Sentry, etc.)
}
getHealthReport() {
return {
...this.metrics,
stickyHitRate: this.calculateStickyHitRate(),
edgeCaseRate: this.metrics.edgeCaseCount / this.metrics.totalAssignments,
timestamp: new Date().toISOString()
};
}
}
B. Continuous Validation
// Periodic self-test
class SelfTestScheduler {
constructor(intervalMinutes = 60) {
this.interval = intervalMinutes * 60 * 1000;
this.lastTest = null;
}
start() {
setInterval(() => this.runSelfTest(), this.interval);
this.runSelfTest(); // Run immediately
}
async runSelfTest() {
console.log('Running self-consistency test...');
const testSuite = new ConsistencyTestSuite();
testSuite.addTest(...stickinessTests);
testSuite.addTest(...edgeCaseTests);
const results = await testSuite.runAllTests();
// Alert on failures
const failures = results.filter(r => !r.passed);
if (failures.length > 0) {
this.alertFailures(failures);
}
this.lastTest = {
timestamp: new Date(),
passed: failures.length === 0,
failures: failures.map(f => f.name)
};
}
alertFailures(failures) {
// Send alerts (email, Slack, PagerDuty)
console.error(`Self-test failed: ${failures.length} tests failed`);
failures.forEach(f => console.error(` - ${f.name}: ${f.error}`));
}
}
USAGE EXAMPLE
// Production initialization
const adapter = new StorageAdapter({ storage: 'localStorage' });
const bucketManager = new BucketManager(adapter, {
cookieNamePrefix: 'myapp_exp_',
ttlDays: 365
});
const edgeHandler = new EdgeCaseHandler(bucketManager);
const replayProbes = new ReplayProbes(bucketManager);
const monitor = new ConsistencyMonitor(bucketManager, edgeHandler, replayProbes);
// Feature evaluation with monitoring
async function evaluateFeature(userId, experimentId, weights) {
try {
const bucket = await monitor.assignAndMonitor(
userId,
experimentId,
weights
);
// Optional: expose debug UI in development
if (window.location.hostname === 'localhost') {
new ReplayDebugUI(replayProbes);
}
return bucket;
} catch (error) {
console.error('Feature evaluation failed:', error);
return 'control'; // Safe default
}
}
// Start periodic self-tests
const selfTest = new SelfTestScheduler(60); // Every hour
selfTest.start();
// Manual testing
const testSuite = new ConsistencyTestSuite();
testSuite.addTest(...stickinessTests);
testSuite.addTest(...edgeCaseTests);
await testSuite.runAllTests();
KEY FEATURES SUMMARY
-
Sticky Bucketing
- Deterministic hashing with salt
- Multiple storage backends (localStorage, cookie, sessionStorage)
- Configurable TTL
- Cross-experiment isolation
-
Edge Case Handling
- Storage quota management
- Concurrency control with locking
- Tampering detection
- Graceful degradation
- Input validation
- Browser capability detection
-
Replay Probes
- Event recording with full context
- Forced assignment override
- Replay script generation
- Consistency analysis
- Debug UI for development
-
Monitoring & Testing
- Automated test suite
- Health metrics collection
- Periodic self-tests
- Alerting on failures
- Performance monitoring
This system provides enterprise-grade consistency verification for client-side feature evaluations, ensuring users see consistent experiences while providing full observability and replay capabilities for debugging.