Page MenuHomePhabricator

[Spike] Design memory mechanism for exposureLogged flags
Closed, ResolvedPublic1 Estimated Story Points

Description

In order to choose how to store flags for exposure logging for SDS 2.2.5, we need to understand what we're storing and other requirements, including:

  • How should the SDK remember which experiments it logged exposure for?
  • Does each Experiment maintain its own exposureLogged flag?
  • Does the SDK maintain a running tab of per-experiment exposureLogged flags?
  • What should we expect to happen when the storage goes away?

The answers to these questions should be added to T414740: [Spike] Determine best storage mechanism to use for storing exposureLogged flags on the web to clarify the AC for that spike.

Event Timeline

KReid-WMF updated the task description. (Show Details)
KReid-WMF moved this task from Incoming to READY TO GROOM on the Test Kitchen board.
KReid-WMF updated the task description. (Show Details)
KReid-WMF set the point value for this task to 1.

@cjming: By the way, the mechanism here doesn't have to be super complicated or "perfect". We just need a way of avoiding unnecessarily logging exposure if/when we can.

The floor is "no more than one exposure per experiment per page visit" – totally doable in-memory – and now we're asking: can we do better than that? Can we send even fewer experiment exposure events? What if we limited it to no more than 1 exposure event per experiment per session – that would be an improvement.

Also it's totally OK (and useful, actually!) to have multiple exposure events per subject over the course of an experiment – it's like little check-ins that the subject is still getting the same variation.

thanks @mpopov for the questions and guidelines - super helpful as I try to wrap my head around this body of work

So given the following requests/constraints/considerations:

  • we want to avoid unnecessary exposure logging when possible
  • guarantee the floor: no more than 1 exposure event / experiment / page visit
    • preferable/optimal: no more than 1 exposure event / experiment / session
  • some multiple exposure events per subject over time is acceptable

What about a 2-tier exposure logging record/ledger?

  1. Tier 1 for the floor - always use memory
    • per-page/request/process memory
    • Set/Map/Array backing store
    • in-memory (page/request/process lifetime)
    • resets when page reloads, on navigation, new request, app session reset (or TTL)
    • guarantees no more than one exposure event per experiment per page/request/process view/render

In Javascript memory:

// For simple boolean:
const exposuresThisPage = new Set();

function hasLogged(key) {
  return exposuresThisPage.has(key);
}

function addLog(key) {
  exposuresThisPage.add(key);
}

// If we want to add timestamps or more metadata:
const exposuresThisPage = new Map();

function hasLogged(key) {
  return exposuresThisPage.has(key);
}

function addLog(key) {
  exposuresThisPage.set(key, Date.now());
}

const key = `${experimentName}:${group}`;

For PHP, we want no more than one exposure log event per experiment per HTTP request which has parity with Javascript's per-page memory.

In PHP memory (request-scoped array):

class ExposureLogTracker {
    private array $loggedExposures = [];

    public function hasLogged(string $key): bool {
        return isset($this->loggedExposures[$key]);
    }

    public function addLog(string $key): void {
        $this->loggedExposures[$key] = true;
    }
}

For Kotlin, we want no more than one exposure log event per experiment per one app process runtime which has parity with both Javascript and PHP.

private val exposuresThisProcess = mutableSetOf<String>()
  1. Tier 2 for more optimal logging - per session
    • Javascript:
      • per-session Set/Map - sessionStorage backing store (or cookie for cross-tab?)
      • survives navigation in a tab
      • clears upon tab closure
      • provides no more than one exposure event per experiment per session (when available) per origin
    • PHP: maybe we skip
    • Kotlin:
      • per app session
      • store exposure keys in memory i.e. SharedPreferences
      • clear when app session ends or persist with timestamp + TTL

We should have both tiers in the Javascript (and presumably Kotlin, but maybe not PHP) case because in-memory alone only deduplicates within a single page load and because if/when session storage disappears (blocked, cleared, etc), we can always fall back to memory. And as noted above, some extra logging is permissible.

In Javascript - sessionStorage:

sessionStorage.setItem("testKitchen.exposureLogged.experimentFoo:groupBar", "1");

In the PHP case, I don't think we want to do Tier 2 if we're ok with multiple exposures across page loads. Server session storage seems more complicated though we could consider it for logged-in users only which would give us no more than one exposure log event per experiment per login session:

$_SESSION['testKitchenExposures'][experimentKey] = true;

We could in theory store exposure flags in a cookie and read them server-side but this is probably a really bad idea because of performance (bloating every request), etc.

In the Kotlin case, we can log an exposure event per experiment per single app session (depending on how a session is defined), and we can persist exposure keys with SharedPreferences to store a timestamp, or apply a TTL, or clear on app session reset.

val exposuresLogStore = mutableMapOf<String, Long>()
exposuresLogStore["testKitchen.exposuresLog.experimentFoo:groupBar"] = System.currentTimeMillis()

To answer the questions in the description specifically:

How should the SDK remember which experiments it logged exposure for?

As proposed above, keep an SDK-level record keyed by experiment name and group assignment and back it with:

  • in-memory Map/Set/array (guaranteed, fallback)
  • session storage (optimal)

Does each Experiment maintain its own exposureLogged flag?

I don't think so - I think this will get messy and complex because of having multiple instances of the same experiment config, or when configs get refetched/refreshed. If we track state on each Experiment instance, I think we'll have more exposure dupes than if we put state at the SDK level.

Does the SDK maintain a running tab of per-experiment exposureLogged flags?

Yes - we can implement a component in the SDKs i.e. an exposureLogTracker or exposureLogStore (bikeshedding opportunity!) that maintains a running tab of per-experiment exposureLogged records:

exposureLogTracker.hasLogged(experimentName, group): boolean
exposureLogTracker.addLog(experimentName, group): void

What are we storing to log exposure for this experiment in this session/page?

  • Key: experiment name and group assignment
  • Value: boolean or timestamp

What should we expect to happen when the storage goes away?

Exposure logging will be less deduplicated. If sessionStorage is cleared, blocked, or unavailable, the SDK will fall back to in-memory only and log exposure again on a later page view or session. As noted above, this is acceptable and maybe even helpful.

I realize that I included Kotlin in my analysis above even though we are excluding it for the time being -- it was helpful though to think about it too in the context of the 2 tier proposal after I realized that maybe we don't want to do tier 2 for PHP. Then I got curious and wondered what it would look like for apps.

So please disregard the Kotlin references. I will leave them in for now though so that when we are ready to think about implementation of exposure logging for apps, it won't be a cold start.

Thanks so much for thinking through it and thank you for including potential code snippets to inform the implementation! I love the 2-tier record/ledger idea.

In the PHP case, I don't think we want to do Tier 2 if we're ok with multiple exposures across page loads. Server session storage seems more complicated though we could consider it for logged-in users only which would give us no more than one exposure log event per experiment per login session:
…
We could in theory store exposure flags in a cookie and read them server-side but this is probably a really bad idea because of performance (bloating every request), caching, etc.

Only logged-in experiments could log exposure server-side anyway, because everyone experiments can only have client-side instrumentation. And since logged-in users' requests aren't cached, we wouldn't have to worry about caching.

Even though that probably changes the performance calculus and while I'd love for us to explore the possibility of storing these flags (or TK-related info in general) in a cookie, I think your conclusion of accepting the floor (tier 1 only) in PHP land seems very reasonable and acceptable.

I agree with the proposed mechanism where the SDKs maintain a record of which experiments' exposures had been logged, using the proposed storage methods to persist the record (where possible), and falling back to in-memory.

doh - sorry you're right re: logged-in experiments logging exposure server-side and caching not being an issue (corrected in original comment) -- but header/cookie size and complexity could still be considerations.

Even though that probably changes the performance calculus and while I'd love for us to explore the possibility of storing these flags (or TK-related info in general) in a cookie

ok challenge accepted -- if we did want to explore the cookie route for PHP logged-in experiments (at least i think this is what you meant - lmk if otherwise), here's a possible path forward for session-level, server-side exposure logging:

Keeping in mind that the total size of all cookies for a single domain is 4KB, we would probably need to figure out a convention to shorten the experiment name + group assignment. Maybe something like exp<id>:A? - where id is the db id of the experiment (would need to pass through this id in the TK api response) and map groups like A, B, C, D, etc (maybe also pass thru?) using a pipe-delimited string? i.e.

exp23:B|exp14:C|exp8:A|...

If the average size of each experiment key is around 20-30 bytes, even if we had say 30 (!) experiments running at any given time, we're looking at ~900 bytes which is well under 4KB.

Since we're no where near 30 concurrent experiments (YET), if we wanted to use full experiment name slugs and group assignments, we'd probably be ok for the near term but would need to be wary about bloating cookies. Probably best to either pass in the experiment id or do some kind of deterministic hashing.

This could easily get dicey depending on how much more TK-related info you want to store. But essentially for logged-in traffic, this seems pretty reasonable if we want to do Tier 2 for PHP logged-in experiments with just experiment name + group.

But I also worry about performance and adding overhead to the request size. Basic research says that the browser by default includes all relevant cookies in the HTTP header for every request made to a domain, including requests for static assets like images, scripts, CSS, etc.

For a standard logged-in session on Vector to en.wikipedia.org, even with ResourceLoader, we might be looking at 8+ requests to the domain:

  • initial HTML
  • 3-5 ResourceLoader requests (CSS, JS, user settings - preferences, gadgets, etc)
  • 5-10 media/api requests - icons? thumbnails? api calls for notifications, messages

This exposure log cookie will be included in the HTTP header of every one of these subrequests meaning our cookie would be processed by WMF's application servers that many times (8+) for a single page view.

Maybe based on this performance consideration alone, we might want to skip the cookie route unless I'm mistaken and missing something about how MediaWiki and ResourceLoader works.

If I am mistaken and we still want to forge ahead, we can use the following logic for the cookie implementation:

  • If the cookie already has the experiment key, we can suppress the log exposure event and if the key is missing, the exposure can be logged again.
  • If the user deletes the cookie, we can log exposure again which is ok given permissible duplication.

So then in theory, the cookie-based Tier 2 for PHP logged-in users will log no more than 1 exposure event per experiment per login session.

Upon receiving a request, PHP would

  • read the cookie (say tk_exposures)
  • parse the existing experiments
  • if the experiment key exists, don't log the exposure
  • if the experiment key does not exist:
    • log the exposure
    • add the experiment key
    • update the cookie
class ExposureLogTracker {
    private const COOKIE_NAME = 'tk_exposures';

    public function shouldLog(string $experimentName, string $groupAssignment): bool | string {
        $shortKey = $this->generateShortKey($experimentName, $groupAssignment);
        $existingExposures = $this->getCookie();

        if (in_array($shortKey, $existingExposures)) {
            return false; // Already logged this session
        }
        return $shortKey; // Green light to log exposure
    }

    public function addLog(string $shortKey, callable $existingExposures): void {
        $this->updateCookie($shortKey, $existingExposures());
    }

    private function updateCookie(string $newKey, array $existing): void {
        $existing[] = $newKey;
        $value = implode('|', array_unique($existing));

        // Set session cookie
        setcookie(self::COOKIE_NAME, $value, [
            'expires' => ??,
            'httponly' => false, // Allow JS Tier 2 to read/sync maybe?
            'secure' => true
        ]);
    }

    private function getCookie(): array {
        return explode('|', $_COOKIE[self::COOKIE_NAME] ?? '');
    }

    private function generateShortKey($experiment, $group): string {
        // return some hashing of the experiment name + group
    }
}

// Usage

if ($key = $this->shouldLog($experimentName, $groupAssignment) {
    $this->addLog($key, [$this, 'getCookie']);
}

Anyway, we could always put this in a separate ticket and decide if we have the time/will to implement sooner or later or at all.

Good start, @cjming.

Firstly, I would recommend against cookies as a state store. Responses to requests for HTML resources respond with the Vary: Cookie header. If an experiment sent an exposure event and we recorded that in a cookie, then the browser might evict the HTML resource from its cache, impacting performance for that user. This has happened in other situations, e.g. the Session Length instrumentation used cookies as a state store and triggered this browser behaviour (see T295619 for details).

Secondly, I encourage you to think about expiry. Consider the following situations:

  1. An experiment ends naturally
  2. (After T408186: Configure experiments with stream, schema and contextual attributes) An experiment is disabled, its contextual attributes are updated, and then the experiment is re-enabled
    • Experiments have been tweaked in production before. I expect that it will happen again
  3. The panic button is pushed and all experiments are disabled and later re-enabled
  4. The exposure event fails to send (and the SDK doesn't know)

How could the proposed Tier 2 ledger deal with these scenarios?

Thirdly:

  1. Tier 2 for more optimal logging - per session
    • Javascript:
      • per-session Set/Map - sessionStorage backing store (or cookie for cross-tab?)
      • survives navigation in a tab
      • clears upon tab closure
      • provides no more than one exposure event per experiment per session (when available)

sessionStorage is per-browsing-context (per tab). localStorage is cross-browsing-context (cross-tab). However, both sessionStorage and localStorage are per-origin, e.g. if a user navigates between enwiki and dewiki, then we should expect to receive an exposure event for enwiki and dewiki. Therefore, we can guarantee at best:

  1. sessionStorage: 1 exposure event per experiment per tab, per origin
  2. localStorage: 1 exposure event per experiment per origin

thank you for piping in @phuedx ! always appreciate your perspective and prescriptive expertise

Firstly, I would recommend against cookies as a state store

Sounds good to me - my gut/research says it's a bad idea (performance-related I originally thought more having to do with subrequests than with caching degradation - I stand corrected) and your pointing out + past session length instrument kerfuffles confirm. While it was a good exercise for me to contemplate how it might work, I agree that it's a dealbreaker with the cache misses it would cause.

Given the known browser behavior around the Vary: Cookie header, we should then definitely not use cookies as an exposure state store which brings us back to the original proposal wherein we stick to Tier 1 (in-memory) only for PHP.

Secondly, I encourage you to think about expiry.... How could the proposed Tier 2 ledger deal with these scenarios?

Thanks for articulating these very real and likely scenarios.

TL;DR - can we use versioned keys with a short TTL for Tier 2?

The first strategy that occurs to me is to implement some kind of short-lived TTL. If we envision Tier 2 as a best effort, optimal exposure event suppression mechanism to pre-empt multiple/redundant exposure logging during fast navigation or re-rendering, by setting say a 15-30 minute TTL to suppress exposures, this eventually (though not immediately) handles the panic button and disable/re-enable cases.

But to address the case say where experiment config changes right after an exposure event happens, we want to be able to log that exposure again immediately, not wait for the TTL to expire. Maybe we need to implement some kind of experiment config versioning and include this in the experiment key so that when the experiment ends or when experiment config changes, we log a new exposure as soon as it's detected? Something like:

// experiment key structure:
tk.exposureLog.{experimentName}:{groupAssignment}:{version}

sessionStorage.setItem("testKitchen.exposureLog.experimentFoo:groupBar:v3", Date.now().toString());

I think this would require us to pass through a version number in the api responses from the Test Kitchen UI so that we can build the experiment key accordingly.

Proposed JSON for https://test-kitchen.wikimedia.org/api/v1/experiments?format=config&authority=mediawiki for example:

{
  "name": "experiment-foo",
  "start": "2026-06-01T14:30:00Z",
  "end": "2026-07-01T14:30:00Z",
  "sample_rate": {
    "1": [
      "frwiki",
      "arwiki",
      "zhwiki"
    ],
    "default": 0
  },
  "groups": [
    "control",
    "treatment"
  ],
  "version": 3 
}

This would also require changes in the TK UI such that version gets bumped whenever the application detects:

  • changes in experiment config
  • experiment disabled/re-enabled (and config changes in between)
  • panic button scenario
  • production tweaks (not sure how to detect these - lofi: rely on engineer to remember to update version at same time?)

Exposure suppression logic:

  • if experiment key exists and timestamp < TTL, then suppress exposure logging
  • if version changes, generate new experiment key, and log exposure asap
  • if TTL expires, log exposure again (check-in behavior)

Pros:

  • accuracy when experiment config changes
  • deduplication of exposure log events (less noise)
  • no persistent suppression of exposure log events

In the last scenario where exposure fails to send and the SDK doesn't know, would the following logic address?

if (shouldLog) {
   sendExposure()
   if (success) {
       markLogged()
   }
}

By combining both short TTL and versioned key strategies, I think we cover the disrupting scenarios:

ScenarioVersioned key + TTL
experiment endsversion removed - no exposure logging suppression
experiment disabled/re-enabledversion changes - new exposure log event
production tweakversion changes (manual) - new exposure log event
panic buttonversion invalidated - exposure log events sent when resumed
exposure event fails to sendmark logged after exposure event sent

It seems like both these implementations address different concerns:

  • short TTL reduces multiple exposure logging events
  • versioned keys solves for experiment accuracy

What do you think?

Thirdly: we can guarantee at best:

sessionStorage: 1 exposure event per experiment per tab, per origin
localStorage: 1 exposure event per experiment per origin

Thanks for the clarification/correction - 100% yes. Updated original comment.

Nice write up.

By the way, the mw.storage object, which wraps local- and sessionStorage, implements TTLs, including reaping expired entries.

I think this would require us to pass through a version number in the api responses from the Test Kitchen UI so that we can build the experiment key accordingly.
<snip />
This would also require changes in the TK UI such that version gets bumped whenever the application detects:

  • changes in experiment config
  • experiment disabled/re-enabled (and config changes in between)
  • panic button scenario
  • production tweaks (not sure how to detect these - lofi: rely on engineer to remember to update version at same time?)

(Emphasis my own)

If you generate the version string by hashing the appropriate properties (e.g. include machine-readable name, exclude friendly name), then you don't need to worry about friendly database tinkerers keeping the version field up to date.

In the last scenario where exposure fails to send and the SDK doesn't know, would the following logic address?

if (shouldLog) {
   sendExposure()
   if (success) {
       markLogged()
   }
}

The problem is that you don't (and can't) know the value of success. I think a short TTL for the first few attempts followed by a long TTL could work, e.g. 5 minutes for the first 10 attempts, 24 hours thereafter.

If you generate the version string by hashing the appropriate properties (e.g. include machine-readable name, exclude friendly name), then you don't need to worry about friendly database tinkerers keeping the version field up to date.

+1, and also at some point we'll have phases (from GrowthBook) and would be able to incorporate phase ID into the mix

The problem is that you don't (and can't) know the value of success. I think a short TTL for the first few attempts followed by a long TTL could work, e.g. 5 minutes for the first 10 attempts, 24 hours thereafter.

Proposed scheme sounds good