The user wants a design for a "client-side feature evaluation consistency test."
Key components requested:
- Sticky Bucketing: Ensuring a user consistently sees the same variation even if the hashing logic or targeting changes slightly (or if they fall out of a target group and re-enter).
- Edge Cases: Scenarios where logic might break (e.g., offline mode, rapid config updates, user logout/login).
- Replay Probes: Mechanisms to verify that past evaluations remain consistent or are correctly re-evaluated when context changes.
Target Audience: Software Engineers, QA Engineers, or Product Managers working on Feature Flagging/Experimentation platforms. The output should be technical and structured.
Core Concepts:
- Feature Evaluation: The process of determining which variation (A/B/C or On/Off) a user sees.
- Consistency: The "Golden Rule" of A/B testing. If I'm in group A, I should stay in group A unless explicitly moved.
- Sticky Bucketing: Usually implemented by saving the decision to a cookie/local storage and persisting it.
- Client-Side: This happens in the browser (JavaScript SDKs like LaunchDarkly, Optimizely, Statsig, or a custom solution). Constraints include network latency, offline capabilities, and localStorage limits.
Structure of the Response:
- Introduction: Define the goal (ensure user experience stability and data integrity).
- Part 1: Sticky Bucketing Test Design: Focus on the mechanism of "sticking" a user to a bucket.
- Mechanism: Hashing (Murmur/FNV) + Persistance.
- Test Scenarios: Re-evaluating with same context, re-evaluating with changed context (that doesn't warrant a new bucket), clearing storage.
- Part 2: Edge Case Testing: The "weird" stuff.
- Network failures, race conditions (SDK loading vs. App rendering), cache invalidation, Multi-tab issues.
- Part 3: Replay Probes (Time-Travel/Re-evaluation):
- This sounds like checking historical consistency or re-running evaluation logic against a saved context to ensure deterministic outcomes.
- Mechanism: "Replay" the user context against the current ruleset.
- Implementation Plan (The "How-To"): Code snippets or pseudo-code for an automated test harness.
Drafting Content - Section by Section:
-
Sticky Bucketing:
- Concept: If the user ID is
u123 and feature new-button is true, write to localStorage -> { "new-button": { "variation": true, "version": "v1" } }.
- Test 1: Reload page. Verify
localStorage is read before network request.
- Test 2: Change user attribute (e.g., "country" changes) but
userId stays same. If sticky bucketing is on, stick to the bucket.
- Test 3: "Unstick" logic. If the feature version bumps, or explicit reset, does it re-bucket?
-
Edge Cases:
- The "Flicker": Initial state vs. final state.
- The "Ghost User": Anonymous user becomes logged-in user. Aliasing.
- Latency/Offline: SDK boots up offline. Does it use default? Does it use cached? If cached, is it consistent with the last online state?
- Concurrent Tabs: Tab A updates user attribute. Tab B should reflect change via
storage event listener.
-
Replay Probes:
- This is interesting. Usually, "Replay" implies debugging.
- Idea: Create a "probe" that captures the
Evaluation Context at Time T. At Time T+1, take the Evaluation Context from T and run it against the Config at T+1.
- Goal: Ensure deterministic hashing. If I feed the exact same inputs, I must get the exact same outputs.
Refining the "Replay Probe" definition:
The prompt specifically mentions "Replay Probes." In the context of feature flags, this usually refers to the SDK's ability to re-evaluate flags when the user context changes or verifying that a stream of events matches expectations.
Let's interpret "Replay Probes" as: A method to inject specific user contexts into the evaluator at high speed to verify deterministic behavior and rule adherence, essentially "replaying" user journeys to check for regression.
Architecture of the Test Harness:
I should provide a conceptual architecture for the testing tool.
- Driver: Puppeteer/Playwright (headless browser).
- Subject: The Client SDK.
- Mock Server: Controls the flag configurations.
Specific Test Scenarios (The "Meat"):
Let's structure the "Replay Probes" differently:
Maybe it means "Retrying" network requests? No, likely re-evaluating locally.
Let's define it as: Testing the deterministic nature of the evaluation function.
Input: hash(user_id + feature_key) -> Output: variation.
Test: Run 10,000 iterations of the hash function with random IDs. Check for uniform distribution (Chi-square test) and consistency (Input X always equals Output Y).
Plan Summary:
- Test Architecture: Automated browser testing (Playwright) + Mock API.
- Phase 1: Sticky Bucketing Validation: Tests for persistence across reloads, cross-tab, and expiration.
- Phase 2: Edge Cases: Anonymous to Authenticated (aliasing), Offline/Online transitions, Rapid context updates.
- Phase 3: Replay Probes (Consistency): Deterministic hashing checks (Math/Floating point issues across browsers?) and Context Mutation re-evaluation.
Let's refine the "Replay Probes" bit one last time.
"Replay" often refers to "Session Replay."
But "Replay Probes" in a consistency test context likely means: "If I capture the state of the world (User + Config), and I replay that scenario 100 times, is the result identical?"
I will focus on Deterministic Replay.
Self-Correction during drafting:
Make sure to distinguish between Sticky Bucketing (explicit persistence) and Deterministic Hashing (consistent algorithm). Sticky bucketing is the safeguard against hashing changes (e.g., if the SDK updates the hash algorithm). Deterministic hashing is the baseline expectation.
Let's write out the specific test cases.
- Sticky Bucketing:
- Case: User A falls in Bucket 1. Refresh. Still Bucket 1? Yes.
- Case: Targeting rule changes so User A should fall in Bucket 2, but Sticky Bucketing is enabled. Result: Bucket 1 (Sticky wins).
- Case: Sticky bucket cleared. Re-eval. Result: Bucket 2 (Rule wins).
- Edge Cases:
- Case: LocalStorage Full. (QuotaExceededError). Does the app crash or fail gracefully to in-memory?
- Case: Race Condition.
identify() called immediately followed by variation(). Is variation() async or does it return stale data?
- Replay Probes:
- Case: Rapid fire
put (context update) commands. Does the evaluation stream update correctly?
Final Polish: Use a clear, numbered format. Add code snippets where helpful (Pseudo-code). Focus on the Client-Side aspect (Browser APIs: LocalStorage, Cookies, IndexedDB, Window events).
Key Terminology:
- Sticky Bucket: Persisting the assigned variation to local storage.
- Salt/Hash: The math behind the bucket.
- Evaluation Context: The user object (ID, attributes).
- Probe: A test assertion that runs during runtime.
Let's go.
Designing a client-side consistency test suite requires validating that the SDK behaves deterministically in a non-deterministic environment (the browser). The architecture must verify three layers: the Hashing/Assignment Layer (Sticky Bucketing), the State/IO Layer (Edge Cases), and the Temporal Layer (Replay Probes).
Here is a comprehensive design for the test suite.
1. Test Architecture Overview
To run these tests effectively, we need a Deterministic Test Harness. We cannot rely on real network requests or real random number generation.
- Environment: A headless browser (Puppeteer/Playwright) or JSDOM environment.
- Mocking: The Feature Flagging SDK must allow injection of:
- A Mock Time Source (for seeding hashes).
- A Mock Network Layer (to simulate latency, failures, and specific payloads).
- A Mock Storage Driver (to simulate
localStorage quota errors or corruption).
2. Phase 1: Sticky Bucketing (Assignment Integrity)
"Sticky Bucketing" ensures that once a user is assigned a variation, they remain in that variation even if the underlying hashing algorithm changes or they fall out of a targeting rule (unless explicitly unassigned).
Test Case 1.1: The "Salt Rotation" Consistency
- Scenario: The SDK generates a hash based on User ID + Flag Key + Salt. The backend team rotates the salt.
- Procedure:
- Initialize SDK with
Salt_A. Evaluate flag new-ui for User_1.
- Record
Variation_ID: 123.
- Persist the "sticky bucket" to Mock LocalStorage.
- Re-initialize SDK with
Salt_B (simulating a config update).
- Evaluate flag
new-ui for User_1.
- Pass Criteria: The SDK returns
Variation_ID: 123 (retrieved from storage) and does not recalculate the hash.
Test Case 1.2: The "Rule Exit" Persistence
- Scenario: A user qualifies for a rule ("Beta Testers"). Later, they are removed from that group.
- Procedure:
- Seed
User_1 with attribute { group: 'beta' }.
- Evaluate
Feature_X. Record assignment.
- Update
User_1 context to { group: 'prod' } (keeping User ID constant).
- Re-evaluate
Feature_X.
- Pass Criteria:
- If Sticky Bucketing is ON: User sees the old variation (stored locally).
- If Sticky Bucketing is OFF: User falls back to the default variation.
Test Case 1.3: Storage Pollution / "Ghost" Buckets
- Scenario: LocalStorage contains a manually edited, invalid bucket entry (e.g., referring to a deleted variation).
- Procedure:
- Inject into LocalStorage:
{ "flag-key": "variation-deleted-last-week" }.
- Initialize SDK.
- Evaluate flag.
- Pass Criteria: The SDK detects the variation is invalid for the current environment, discards the sticky bucket, and generates a fresh assignment.
3. Phase 2: Edge Cases (State & IO)
This phase tests the robustness of the client-side SDK in hostile browser environments.
Test Case 2.1: The "Offline/Online" Flip
- Scenario: User loads the page, goes offline, interacts, and comes back online.
- Procedure:
- Load SDK. Establish connection.
- Mock Network Failure (go offline).
- Change User Context (call
identify).
- Evaluate Feature Flags.
- Mock Network Restoration (go online) with a new config payload.
- Pass Criteria:
- Offline: Uses cached/defaults. No errors thrown.
- Online: Syncs new state. Re-evaluates context changes immediately.
Test Case 2.2: Race Condition: identify vs. eval
- Scenario: A developer calls
identify(user) and immediately calls getFlag('key') on the next line.
- Procedure:
- Initialize SDK with anonymous user.
- Execute script:
client.identify({ id: 'new-user' });
const flag = client.getFlag('my-feature');
- Pass Criteria:
- Optimistic: The flag returns the value for
new-user immediately (synchronous context update).
- OR Consistent Async: The flag returns the previous user's value, and an event
onUpdate fires shortly after with the new value. The test must enforce that the SDK does not crash or return undefined.
Test Case 2.3: LocalStorage Quota Exceeded
- Scenario: The browser LocalStorage is full (common in mobile webviews).
- Procedure:
- Fill Mock LocalStorage to 100% capacity.
- Initialize SDK.
- Evaluate flags (attempting to write sticky buckets).
- Pass Criteria: The SDK catches the
QuotaExceededError, logs a warning, and continues to function in "memory-only" mode without crashing the UI thread.
Test Case 2.4: Multi-Tab Synchronization
- Scenario: User has two tabs open. Logs out in Tab A.
- Procedure:
- Open Tab A. Login as User X.
- Open Tab B. Verify User X state.
- In Tab A, trigger Logout (reset context).
- Trigger
storage event simulation in Tab B.
- Pass Criteria: Tab B detects the change in shared storage and automatically resets its evaluation context to Anonymous.
4. Phase 3: Replay Probes (Temporal Consistency)
"Replay Probes" refers to verifying that the evaluation logic remains consistent over time and that events generated by the SDK can be "replayed" to verify the logic path.
Test Case 3.1: Deterministic Hashing (Replay Verification)
- Goal: Ensure the hashing algorithm is 100% deterministic across sessions.
- Procedure:
- Input: 10,000 random User IDs + specific Feature Key.
- Run evaluation loop locally.
- Capture output:
Map<UserID, VariationID>.
- (Replay): Run the exact same loop 5 minutes later with the same inputs.
- Pass Criteria: The generated Map is bitwise identical to the first run.
Test Case 3.2: "Time-Travel" Activation
- Goal: Test time-bound features (e.g., "Show banner only in November").
- Procedure:
- Mock System Time:
2023-10-31 23:59:00. Evaluate Flag -> Result: False.
- Mock System Time:
2023-11-01 00:01:00. Evaluate Flag -> Result: True.
- Mock System Time:
2023-12-01 00:01:00. Evaluate Flag -> Result: False.
- Pass Criteria: The SDK respects the internal clock for rule evaluation and does not cache "False" indefinitely if the activation window opens.
Test Case 3.3: The "Probe" Event (Exposure Logging)
- Goal: Ensure that merely checking a flag does not log an impression (exposure), unless the value is actually consumed (Active/Passive probe distinction).
- Procedure:
- Setup a listener for network requests (tracking beacon).
- Call
client.getFlag('secret-feature') but do not access .value (just check if it exists).
- Access
client.getFlag('visible-feature').value.
- Pass Criteria:
- Check 1: No network beacon sent (passive check).
- Check 2: Network beacon sent with correct metadata (exposure event).
5. Implementation Snippet (Pseudo-code)
Here is a structure for the test runner using Jest + Mocks:
describe('Consistency Test Suite', () => {
let mockStorage = {};
let mockClock;
beforeEach(() => {
// Mock Storage
global.localStorage = {
getItem: (key) => mockStorage[key],
setItem: (key, val) => { mockStorage[key] = val; },
clear: () => { mockStorage = {}; }
};
// Mock Time
mockClock = jest.useFakeTimers();
});
// --- STICKY BUCKET TEST ---
test('Sticky Bucket persists despite hash algo change', () => {
const user = { id: 'user_123' };
// 1. Initial Assign (Salt: A)
let sdk = new FeatureClient({ salt: 'A' });
let assignment = sdk.eval('flag_x', user);
const originalVariation = assignment.value;
// Simulate saving to storage
sdk.persistBucket(user, 'flag_x', originalVariation);
// 2. Re-init with new Salt (Salt: B)
sdk = new FeatureClient({ salt: 'B' });
assignment = sdk.eval('flag_x', user);
// Verify: Should ignore new hash, use storage
expect(assignment.value).toBe(originalVariation);
expect(assignment.source).toBe('STICKY_BUCKET');
});
// --- REPLAY PROBE TEST ---
test('Hashing is deterministic over 10k users', () => {
const users = Array.from({length: 10000}, (_, i) => `user_${i}`);
const sdk = new FeatureClient({ salt: 'stable_salt' });
const run1 = users.map(u => sdk.eval('flag_a', {id: u}).value);
const run2 = users.map(u => sdk.eval('flag_a', {id: u}).value);
expect(run1).toEqual(run2);
});
// --- EDGE CASE TEST ---
test('Handles Quota Exceeded gracefully', () => {
const consoleWarn = jest.spyOn(console, 'warn');
// Force setItem to throw
global.localStorage.setItem = () => { throw new Error("QuotaExceededError"); };
const sdk = new FeatureClient();
// This triggers a write attempt
const result = sdk.eval('flag_y', { id: 'test' });
// Should not crash, and should fallback to computed value
expect(result).toBeDefined();
expect(consoleWarn).toHaveBeenCalledWith(expect.stringContaining("Storage full"));
});
});