Skip to content

feat: user-scoped GrowthBookClient instances via create_scoped_instance - #141

Open
vazarkevych wants to merge 4 commits into
growthbook:mainfrom
vazarkevych:feat/user-scoped-instances
Open

vazarkevych wants to merge 4 commits into
growthbook:mainfrom
vazarkevych:feat/user-scoped-instances

Conversation

@vazarkevych

@vazarkevych vazarkevych commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

Every evaluation on GrowthBookClient takes an explicit UserContext (is_on(key, ctx), get_feature_value(key, fallback, ctx), run(experiment, ctx), …). In request-scoped backends the same context has to be threaded through every layer, and passing the wrong one is a silent bug: the wrong user gets the wrong variation.

What changed

  • GrowthBookClient.create_scoped_instance(user_context=None) returns a per-user UserScopedGrowthBook handle whose methods take no context:

    gb = gb_client.create_scoped_instance(UserContext(attributes={"id": user_id}))
    
    show_new_ui = await gb.is_on("new-ui")
    color = await gb.get_feature_value("button-color", "blue")
  • Evaluation: eval_feature, is_on, is_off, get_feature_value, run (each with optional tracking_buffer=), log_event, preload_remote_eval. All delegate to the shared client, so feature refresh, subscriptions and the remote-eval cache are reused. The handle holds no evaluation state and is cheap to create per request.

  • Per-user state (writes to the bound context): set_attributes, update_attributes (shallow merge, None is a no-op), set_url, set_forced_variations, set_forced_features, get_attributes() and the user_context property.

  • Per-user callbacks: set_tracking_callback / set_feature_usage_callback override Options.on_experiment_viewed / Options.on_feature_usage for this user and fall back to them when None. Backed by new optional UserContext.tracking_callback / feature_usage_callback fields, appended after remote_group_ids so positional construction is unchanged. Read via getattr, so custom contexts without them still work.

  • UserScopedGrowthBook is exported from growthbook. README section added.

Decisions worth reviewing

  • Context is bound by reference, not copied. Setters write back to the object passed in, and outside changes are visible to the handle, so user_context can be handed to plugins. A test pins this.
  • One handle per user. The bound context is mutable and also collects sticky bucket assignments, so sharing a handle across concurrent requests brings the bug back. Documented on the class and in the README.
  • set_forced_features() only applies in remote-eval mode. That is existing SDK behavior (local evaluation never reads forced_features). The docstring and README say so and point to set_forced_variations() instead.

How to test

pytest tests/test_growthbook_client.py -k "scoped or per_user or predating or positional"

14 new tests: evaluating without a context (matches the client with an explicit context), independent handles, every setter, binding by reference, per-user tracking and feature-usage callbacks (override, fallback, async), tracking_buffer, log_event and preload_remote_eval delegation, legacy contexts, and positional UserContext order.

Full suite with current main merged: 1955 passed. The 2 cache fixture errors in test_growthbook_client.py also happen on main.

Size

Production code +221 / −10, tests +362, README +71.

Migration

None. All changes are additive.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no outstanding correctness, security, or repository-rule violations were identified.

Reviews (4) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

@vazarkevych
vazarkevych force-pushed the feat/user-scoped-instances branch from 6765784 to 576bf29 Compare October 5, 2026 18:10
@andywhite37
andywhite37 self-requested a review October 8, 2026 21:28
@andywhite37 andywhite37 added effort:medium Focused review with meaningful behavior and test coverage to assess. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:normal Regular queue priority; no evidence of urgency or low value. risk:medium Changes behavior with a bounded impact that needs focused validation. labels Oct 20, 2026
@andywhite37

Copy link
Copy Markdown
Contributor

Maintainer decision needed: confirm the create_scoped_instance API and ownership rules. The handle binds UserContext by reference, its setters mutate that context, and a user callback overrides the client callback while None falls back to it. The README also limits scoped forced features to remote evaluation. These choices affect request isolation and tracking expectations; please record the accepted contract so implementation review can proceed.

@vazarkevych

Copy link
Copy Markdown
Collaborator Author

Recording the contract:

  1. Binding is by reference, not a copy. The handle stores the caller's
    UserContext; its setters write back to it. The handle exposes
    user_context so callers can pass it to layers that still take an explicit
    context — a copy would let those two silently diverge.

  2. One handle per user. Setters mutate the bound context, and evaluation
    writes sticky_bucket_assignment_docs onto it (pre-existing: core mutates
    that dict in place for read-your-writes while persistence is async). Same
    rule the README already states for UserContext itself. Evaluation does
    snapshot attributes at its boundary, so a mid-evaluation mutation can't tear
    a read — the rule is about handle ownership, not eval safety.

  3. Per-user tracking callback wins; None falls back to
    options.on_experiment_viewed. A request-scoped sink shouldn't disable the
    global one for other users. Firing both would double-report exposures.

  4. Scoped forced features are remote-eval only — a pre-existing limitation,
    not introduced here: core.py never reads UserContext.forced_features. I
    documented it on the setter and in the README so it isn't mistaken for a
    local override, and pointed at set_forced_variations instead. Happy to
    drop that documentation and file the gap separately if you'd rather.

None of this is load-bearing — say the word on any of the four and I'll change
it. Rebased on current main; 1203 tests pass.

Every evaluation on GrowthBookClient takes an explicit UserContext, so
request-scoped code has to thread the same context through every layer and a
mismatched one is a silent correctness bug.

Adds GrowthBookClient.create_scoped_instance(user_context), returning a
lightweight per-user UserScopedGrowthBook handle whose evaluation methods take
no context: eval_feature, is_on, is_off, get_feature_value, run, log_event and
preload_remote_eval. Calls delegate back to the shared client, so feature
refresh, subscriptions, the feature-usage callback and the remote-eval cache
are reused rather than forked.

The handle owns per-user state on its bound context: set_attributes,
update_attributes, set_url, set_forced_variations, set_forced_features, and
per-user set_tracking_callback / set_feature_usage_callback that override the
client-level Options.on_experiment_viewed / on_feature_usage for that user,
falling back to them when unset.

UserContext gains tracking_callback and feature_usage_callback for that, and
_track / _feature_usage prefer them. Evaluation wires each callback when either
a client-level or a per-user one exists — gating on the client-level option
alone would mean a client without it never calls through, and the per-user
callback would silently never fire. Both gates read the context with getattr:
callers may pass a duck-typed context, and a gate must not be what breaks an
evaluation.

The context is bound by reference, not copied, so the setters write back to the
caller's object and it stays usable with APIs that still take an explicit
context. One handle per user: the bound context is mutable and also accumulates
sticky bucket assignments.

All changes are additive and default to existing behavior.
@vazarkevych
vazarkevych force-pushed the feat/user-scoped-instances branch from 576bf29 to e452edf Compare November 10, 2026 13:03
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

Rebased onto current main and resolved the test-file conflict (both sides had
appended tests; kept both).

Also added set_feature_usage_callback, the one piece of
growthbook/growthbook@012752c that Python was missing — same
override/fallback contract as the tracking callback in point 3 above. The
other two parts of that commit don't apply here: our tracking plugin has no
event dedupe cache to mis-scope, and exposure dedupe is already keyed on the
bucketing unit.

One thing worth a look: evaluation wires these callbacks only when a consumer
exists, and gating on the client-level option alone meant a per-user callback
would never fire on a client without one. Both gates now read the context with
getattr — a duck-typed context (there's a test using SimpleNamespace) must
not break evaluation.

1788 tests pass; mypy, pyright and the typing suite clean

…ances-merge-main

# Conflicts:
#	growthbook/common_types.py
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook_client.py Resolved
Comment thread growthbook/common_types.py Resolved
remote_group_ids shipped in 4.1.0 as UserContext's ninth field. The new
tracking_callback / feature_usage_callback fields landed before it in the
merge with main, so a ninth positional argument became tracking_callback
and group targeting was lost. Append the callback fields after it.

_track read user_context.tracking_callback directly, so a custom context
without the field raised AttributeError before the callback's try block
and broke the evaluation whenever Options.on_experiment_viewed was set.
Use getattr like the other callback paths.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort:medium Focused review with meaningful behavior and test coverage to assess. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:normal Regular queue priority; no evidence of urgency or low value. risk:medium Changes behavior with a bounded impact that needs focused validation.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants