-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
12789/feat/AB Testing #12788
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Sadashii
wants to merge
11
commits into
internetarchive:master
Choose a base branch
from
Sadashii:feat/ab-testing-architecture
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+354
−26
Open
12789/feat/AB Testing #12788
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
93152c5
feat: Add client and server-side A/B testing architecture
Sadashii f37803b
feat: Add URL-based overrides for active experiments in ?experiment_[…
Sadashii 341b3aa
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 84f1e1e
feat: add authorized_only parameter to A/B testing experiments
Sadashii f4cec9d
refactor: optimize experiments middleware, filter query overrides, an…
Sadashii 2e76bd8
refactor(ab-testing): improve type safety and cryptographic session v…
Sadashii e9e432a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4d31692
refactor(ab-testing): unify request evaluation, secure json serializa…
Sadashii 8d6f6f1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 8876e68
refactor(security): unify HTML-safe JSON serialization and replace du…
Sadashii fd51484
Merge branch 'upstream/master' into feat/ab-testing-architecture
Sadashii File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import hashlib | ||
| from typing import Final, Literal, TypedDict | ||
|
|
||
|
|
||
| class Audience: | ||
| """Constants for experiment audience targeting.""" | ||
|
|
||
| ALL: Final = "all" | ||
| LOGGED_IN: Final = "logged_in" | ||
| LOGGED_OUT: Final = "logged_out" | ||
|
|
||
|
|
||
| class ExperimentConfig(TypedDict, total=False): | ||
| """Type schema for autocomplete and static analysis.""" | ||
|
|
||
| variants: dict[str, int] | ||
| audience: Literal["all", "logged_in", "logged_out"] | ||
|
|
||
|
|
||
| ACTIVE_EXPERIMENTS: dict[str, ExperimentConfig] = { | ||
| "Sample_Experiment_1": { | ||
| "variants": {"control": 30, "a": 35, "b": 35}, | ||
| "audience": Audience.ALL, | ||
| }, | ||
| "Sample_Experiment_2": { | ||
| "variants": {"control": 50, "treatment": 50}, | ||
| "audience": Audience.LOGGED_OUT, | ||
| }, | ||
| "Sample_Experiment_3": { | ||
| "variants": {"control": 50, "treatment": 50}, | ||
| "audience": Audience.LOGGED_IN, | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| def get_variant(experiment_name: str, user_identifier: str | None, is_logged_in: bool = False) -> str: | ||
| """Assigns a user to a variant based on configured weights and audience rules.""" | ||
| if not user_identifier or experiment_name not in ACTIVE_EXPERIMENTS: | ||
| return "control" | ||
|
|
||
| config = ACTIVE_EXPERIMENTS[experiment_name] | ||
| audience = config.get("audience", Audience.ALL) | ||
|
|
||
| if audience == Audience.LOGGED_IN and not is_logged_in: | ||
| return "control" | ||
| if audience == Audience.LOGGED_OUT and is_logged_in: | ||
| return "control" | ||
|
|
||
| hash_key = f"{experiment_name}-{user_identifier}".encode() | ||
| bucket = int(hashlib.md5(hash_key).hexdigest()[:8], 16) % 100 | ||
|
|
||
| cumulative_weight = 0 | ||
| for variant, weight in config.get("variants", {}).items(): | ||
| cumulative_weight += weight | ||
| if bucket < cumulative_weight: | ||
| return variant | ||
|
|
||
| return "control" | ||
|
|
||
|
|
||
| def get_user_experiments( | ||
| user_identifier: str | None, | ||
| overrides: dict[str, str] | None = None, | ||
| is_logged_in: bool = False, | ||
| ) -> dict[str, str]: | ||
| """Evaluates all active experiments for a user, handling optional overrides.""" | ||
| overrides = overrides or {} | ||
| results = {} | ||
|
|
||
| for exp_name, config in ACTIVE_EXPERIMENTS.items(): | ||
| override_val = overrides.get(f"experiment_{exp_name}") | ||
|
|
||
| if override_val in config.get("variants", {}): | ||
| results[exp_name] = override_val | ||
| else: | ||
| results[exp_name] = get_variant(exp_name, user_identifier, is_logged_in) | ||
|
|
||
| return results | ||
|
|
||
|
|
||
| def evaluate_experiments_for_request( | ||
| session_value: str | None, | ||
| forwarded_for: str | None, | ||
| client_ip: str | None, | ||
| query_params: dict[str, str], | ||
| ) -> dict[str, str]: | ||
| """Resolves active experiments for a request based on session, IP, and query params.""" | ||
| from openlibrary.accounts.model import verify_session_cookie | ||
|
|
||
| is_authenticated = False | ||
| user_id = None | ||
|
|
||
| if session_value and session_value.startswith("/people/") and verify_session_cookie(session_value): | ||
| is_authenticated = True | ||
| user_id = session_value.split(",")[0] | ||
|
|
||
| if not user_id: | ||
| if forwarded_for: | ||
| user_id = forwarded_for.split(",")[0].strip() | ||
| else: | ||
| user_id = client_ip or "127.0.0.1" | ||
|
|
||
| query_overrides = {k: v for k, v in query_params.items() if k.startswith("experiment_")} | ||
|
|
||
| return get_user_experiments(user_id, overrides=query_overrides, is_logged_in=is_authenticated) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| from fastapi import Request | ||
|
|
||
| from infogami import config | ||
| from openlibrary.core.experiments import evaluate_experiments_for_request | ||
|
|
||
| if TYPE_CHECKING: | ||
| from starlette.types import ASGIApp, Receive, Scope, Send | ||
|
|
||
|
|
||
| class ABTestingMiddleware: | ||
| def __init__(self, app: ASGIApp) -> None: | ||
| self.app = app | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| request = Request(scope, receive=receive) | ||
|
|
||
| session_value = request.cookies.get(config.get("login_cookie_name", "session")) | ||
| forwarded_for = request.headers.get("X-Forwarded-For") | ||
| client_ip = request.client.host if request.client else "127.0.0.1" | ||
| query_params = dict(request.query_params) | ||
|
|
||
| request.state.experiments = evaluate_experiments_for_request( | ||
| session_value=session_value, | ||
| forwarded_for=forwarded_for, | ||
| client_ip=client_ip, | ||
| query_params=query_params, | ||
| ) | ||
|
|
||
| await self.app(scope, receive, send) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| export function getExperiment(experimentName) { | ||
| if (typeof window === 'undefined') { | ||
| return 'control'; | ||
| } | ||
| return window.OL_EXPERIMENTS?.[experimentName] || 'control'; | ||
| } | ||
|
|
||
| if (typeof window !== 'undefined') { | ||
| window.getExperiment = getExperiment; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -303,7 +303,7 @@ def commify_list(items: Iterable[Any]) -> str: | |
|
|
||
| @public | ||
| def json_encode(d, indent=0) -> str: | ||
| return json.dumps(d, indent=indent) | ||
| return json.dumps(d, indent=indent).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This seems kind of hacky.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure of simpler ways, do you have any recommendations? |
||
|
|
||
|
|
||
| @public | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.