Python SDK
controlvar (v0.3.0) is a synchronous, dependency-free Python client for the
Controlvar public API: experiment assignment, feature-flag evaluation and event
tracking. Requires Python 3.9+; HTTP goes through the standard library (urllib).
By default, flag evaluation and experiment assignment are decided by the server: every call
goes to the public API with your X-API-Key, the server buckets the user (sticky per user +
experiment), and the SDK caches the answer per user + key. In server-side code you can opt in to
local evaluation (evaluation="local"): flags are then
answered in-process from the server's ruleset, with the server's answers, and experiments stay on
the server.
Source: sdk/python. The OpenFeature provider in sdk/openfeature-python is built on top of this
client (see openfeature.md).
Installation
If you installed experimently, the name this package had before the project was renamed, uninstall it and install controlvar.
The controlvar package is on PyPI. 0.3.0 is a
beta release.
To work on the SDK itself, install it from the root of a clone of this repository instead:
Quick start
If you set EXPERIMENTLY_API_KEY or EXPERIMENTLY_API_URL from an earlier version of these pages, set CONTROLVAR_API_KEY and CONTROLVAR_API_URL instead.
render_new_checkout() and use_new_search() below stand for your own code: define them, or
replace the two calls, before you run the block. As written, a branch that reaches one of them
raises NameError.
import os
from controlvar import ExperimentationClient, ExperimentationError
client = ExperimentationClient(
api_url=os.environ.get("CONTROLVAR_API_URL", "http://localhost:8000"), # origin only
api_key=os.environ["CONTROLVAR_API_KEY"],
)
# Experiments — sticky assignment made by the server (POST /api/v1/tracking/assign)
variant = client.get_variant("checkout_flow", user_id="user-123", user_attributes={"plan": "pro"})
if variant == "treatment":
render_new_checkout() # your own code
assignment = client.get_assignment("checkout_flow", "user-123") # raises on failure
assignment.variant_name, assignment.is_control, assignment.configuration
# Feature flags (GET /api/v1/feature-flags/evaluate/{key}?user_id=…&context=<url-encoded attributes>)
if client.is_feature_enabled("new_search", "user-123", user_attributes={"plan": "pro"}):
use_new_search() # your own code
flag = client.get_feature_flag("new_search", "user-123") # FlagEvaluation(key, enabled, config, reason, source, value, value_type)
flags = client.get_all_flags("user-123", {"plan": "pro"}) # {"new_search": True, ...}
# Tracking (never raises)
client.track("user-123", "purchase", event_value=49.99, experiment_key="checkout_flow")
client.track("user-123", "page_view", properties={"page": "/"}) # no key: fanned out, see below
Constructor
ExperimentationClient(
api_url: str, # backend origin, e.g. "https://api.example.com"; the SDK appends /api/v1/...
api_key: str, # sent as X-API-Key
timeout_seconds: float = 5.0, # per request
cache_ttl_seconds: float = 300, # how long a successful assignment/evaluation is reused per user + key
default_variant: str = "control",# what get_variant returns on failure
transport: Transport | None = None, # inject your own HTTP layer (tests use controlvar.testing.FakeTransport)
evaluation: str = "server", # "server" (default) or "local" (server-side only; see Local evaluation)
refresh_interval_seconds: float = 30, # local mode: ruleset refresh (minimum 5, ±10% jitter)
max_stale_seconds: float | None = None, # local mode: evaluate on the server once the ruleset is this old
on_error=None, # on_error(error, operation): "value" and "exposure" in either mode; "refresh" | "flush" | "evaluate" in local mode
on_exposure=None, # on_exposure(exposure): see Exposure hook
)
Instances are thread-safe and should be shared across your application (one per process is
typical): the keys a client has answered for a user are what make a key-less track count for
every experiment the user is in.
API reference
| Method | Returns | Failure behaviour |
|---|---|---|
get_assignment(experiment_key, user_id, user_attributes=None) |
Assignment(experiment_key, user_id, variant_id, variant_name, is_control, configuration, assigned, reason) |
raises ExperimentationError (status == 404 when no experiment has the key, or for a draft with no control variant); an experiment that is not ACTIVE returns its control variant with assigned False and reason its status |
get_variant(experiment_key, user_id, user_attributes=None) |
str — the variant name |
returns default_variant ("control") |
get_feature_flag(flag_key, user_id, user_attributes=None) |
FlagEvaluation(key, enabled, config, reason, source, value, value_type) |
raises ExperimentationError (status == 404 when the flag key is unknown; a flag that is not ACTIVE returns enabled=False, reason="inactive") |
is_feature_enabled(flag_key, user_id, user_attributes=None) |
bool |
returns False |
get_string_value(flag_key, user_id, user_attributes=None, *, default) |
str, the string a string flag serves this user; see Flag values |
returns default; never raises; logs a warning and calls on_error(error, "value") |
get_number_value(flag_key, user_id, user_attributes=None, *, default) |
int or float as saved (never a bool), the number a number flag serves this user |
returns default; never raises; logs a warning and calls on_error(error, "value") |
get_json_value(flag_key, user_id, user_attributes=None, *, default) |
a new copy of the dict or list a json flag serves this user |
returns default; never raises; logs a warning and calls on_error(error, "value") |
get_all_flags(user_id, user_attributes=None) |
dict[str, bool] (not cached) |
raises ExperimentationError |
track(user_id, event_name, event_value=None, properties=None, experiment_key=None, feature_flag_key=None, event_type=None, timestamp=None, event_id=None) |
bool — True when it was sent and the server answered 2xx |
never raises; False on failure |
track_batch(events) |
BatchResult(success_count, failure_count, errors), .ok |
never raises; sends chunks of 100, a failed chunk counts all its events as failures |
report_error(error_type, message, *, feature_flag_key=None, experiment_key=None, user_id=None, stack_trace=None, metadata=None, timestamp=None) |
bool — True when the server stored the report (201); see Reporting errors |
never raises; False and a logged warning otherwise |
get_assignments(user_id, active_only=True) |
list[dict] — the user's assignments from the server (not cached) |
raises ExperimentationError |
alias(anonymous_id, user_id) |
bool — True when this call stored the link, False when it was already stored; in the source tree only, see Linking an anonymous id to a known user id |
raises ExperimentationError, with the server's status and body |
cached_assignments(user_id) / cached_flags(user_id) |
cached, unexpired entries for the user | — |
clear_cache() |
— (keeps the keys a key-less track is sent to) |
— |
ready(timeout_seconds=None) |
ReadyResult(ok, ruleset_version, error), truthy when ready; ReadyResult(ok=True) at once in server mode |
never raises |
status() |
LocalEvaluationStatus(evaluation, ready, ruleset_version, last_refresh_at, last_error, server_evaluated_flags) |
— |
close(), with ExperimentationClient(...) as client: |
local mode: stops the refresh thread and sends the remaining evaluation counts; a no-op in server mode | never raises |
consistent_hash(user_id, flag_key) / md5_hex(user_id, flag_key) |
cross-SDK MD5 bucket in [0, 1) / hex digest |
pure functions; not the flag bucketing function and not used to decide variants or flags |
Assignment, FlagEvaluation and Exposure are frozen dataclasses. ExperimentationError carries
.status (HTTP status, None for network errors and timeouts), .body (raw response text) and
.code: "TYPE_MISMATCH" or "INVALID_RESPONSE" on an error a typed getter makes itself, and
"HOOK_ERROR" on the error on_error receives with "exposure". Other errors carry no code in this
version; .status describes them.
FlagEvaluation.reason ("targeting_rule", "rollout", "inactive" or "error") says why the
server decided; it is None when the server does not send one. FlagEvaluation.source is set only
in local mode: "local" when answered in-process, "server" when the server evaluated it.
Enrolment: assigned and reason
An Assignment also carries assigned and reason. assigned is False means the server did not
enrol the user (reason is "holdout", "mutual_exclusion" or "targeting") and returned the
control variant so you render the default experience; no exposure was recorded. When you export
exposures to a warehouse, exclude assignments with assigned is False: the user was not enrolled,
and reason says why. A server that predates the fields sends neither, so assigned is None
(never False). Decide deliberately how to treat those rows rather than dropping them with an
assigned is True filter.
An experiment that is not ACTIVE answers every user with its control variant, assigned False and
reason set to its status ("draft", "paused", "completed" or "archived").
Targeting context
user_attributes is what the platform's targeting rules evaluate against, and what sets the
user's segment in a breakdown. It is sent as context
in the POST /api/v1/tracking/assign body and, when non-empty, as context=<url-encoded JSON>
(compact json.dumps(..., separators=(",", ":")), percent-encoded) on
GET /api/v1/feature-flags/evaluate/{flag_key} and GET /api/v1/feature-flags/user/{user_id} —
so a flag whose dashboard rule says os_version semver_gte 17.0.0 AND tier equals premium turns
on only for matching users. Top-level keys are also reachable under user. / device. / app.
aliases in rules (country matches user.country), and nested dicts flatten to dotted keys
({"app": {"version": "3.2.1"}} answers app.version).
Attributes are assumed stable per user: evaluations and assignments are cached by user + key
only, so call clear_cache() after changing a user's attributes.
An experiment that balances its split within groups reads
its attribute from the top level of user_attributes only: {"tier": "gold"}, not
{"user": {"tier": "gold"}}.
Caching and retries
- Successful assignments and evaluations are cached per user + key for
cache_ttl_seconds(default 300 s). Failures are never cached, so the next call retries. - A
429is retried once afterRetry-Afterseconds (capped at 5 s; 1 s when the header is missing or unparseable). Any other non-2xx status raises immediately. trackreturnsFalseon a timeout even when the server stored the event. See How events count before you send it again.- The cache is checked before any request, so a cached value is returned even if the backend is currently unreachable.
Tracking fan-out rule
- With
experiment_keyand/orfeature_flag_key→ onePOST /api/v1/tracking/track. - Without a key → one
POST /api/v1/tracking/batch(chunks of 100) containing one entry per experiment (experiment_key) and one per flag (feature_flag_key) this client answered for the user in the last 24 hours, whether or not the answer is still cached. - An experiment that is not running (its latest answer has
reason"draft","paused","completed"or"archived") gets no entry. An answer withassigned=Falsefor"holdout","mutual_exclusion"or"targeting"keeps its entry: holdout results count those users' events. - An experiment whose assignment is later answered 404 loses its entry at once, so key-less events stop reaching it; any other failure (a 5xx, a network error) keeps it.
- With nothing to attribute it to, the event is still sent: one
POST /api/v1/tracking/trackwith no key. The server stores it as history, which counts in holdout results and as CUPED history, never in an experiment's results. trackreturnsTruewhen the event was sent and the server answered 2xx (every request, when the fan-out takes more than one), andFalseotherwise. A 2xx batch can still report a failed entry, such as a key the server no longer has;track_batchreturns the per-entry results.- The keys live in this client's memory, for up to 10,000 users (the user answered least recently
is dropped first).
clear_cache()keeps them, and another process does not have them. On a server, the process that records a purchase is often not the one that assigned the user, so passexperiment_keyon conversions there. track_batchsends the events it is given as they are: an entry with no key is stored as history.
event_type defaults to event_name; properties is sent as metadata; timestamp may be a
datetime (naive values are treated as UTC) or an ISO-8601 string. Conversions are matched to
experiment metrics by event name.
track returns False, and sends nothing, when event_value or properties holds NaN or an
infinite number. get_assignment raises ExperimentationError
for the same in user_attributes, and get_variant returns the default for a user with no
cached assignment (a cached assignment is returned as before).
Event ids
event_id is your id for one event. The server stores an event sent again with the same
event_id, user, experiment, flag and event name only once (see
How events count). It needs a
Controlvar server that includes the event_id change (#1640),
which the platform release after 0.39.0 is to carry; an older server ignores the field and stores
an event sent again a second time.
track(..., event_id=None)sends it asevent_id. The SDK makes no id. An event without anevent_idis sent without one, and one sent again is stored and counted again. Make the id once, when the event happens, for example withstr(uuid.uuid4()), and give the same one each time you send that event.event_id=Noneand""send noevent_id. The SDK does not check the id: the server refuses (422) one of more than 255 characters or one holding NUL, and in a batch one such event refuses the whole request.- An event fanned out to several experiments and flags carries the same
event_idin every entry, so it counts once in each of them. track_batchsends the events it is given as they are, so anevent_idkey in an event's dict is sent as it is. Each event keeps its own.- A
429that is retried sends the same request again, so the sameevent_id. - A request that fails on the network or times out is not sent again by the SDK, and the server may
have stored it. Send it again with the same
event_idand it is stored once.
Reporting errors
report_error(error_type, message, ...) sends one POST /api/v1/tracking/errors for an error
that happened while a flag or experiment was active, in either evaluation mode; every argument
after message is keyword-only. The server needs feature_flag_key or experiment_key, and the
SDK sends the report without checking it.
Truemeans the server stored the report: it answered 201.Falsemeans it did not: any other answer (401, 404, 422, a 429 after its one retry, 5xx) or a network failure, which is also logged as a warning.report_errornever raises.- A stored report counts toward the flag's error rate and automatic rollback only when it names
that flag in
feature_flag_key(a report with onlyexperiment_keyis stored, but counts toward no flag's rate) and the client's key is a server-side key: one with thesdk:rulesetscope, created by a user who can change feature flags. A report sent with any other production key is stored too and still returnsTrue; the flag's safety check shows those reports asuncounted_error_count. See Which errors count. - The error rate divides the counted errors by the flag's evaluations in the check's 15-minute
window. With no evaluations in the window it reads 0, so an error-rate threshold cannot fire: in
local mode the counts reach the server every 60 seconds and on
close().
Linking an anonymous id to a known user id: alias
alias is in the source tree only: it is not in the published controlvar 0.3.0, and arrives
with the package's next release. Until then, call POST /api/v1/tracking/alias from your
backend, or install the SDK from a clone of this repository (see Installation).
alias(anonymous_id, user_id) sends one POST /api/v1/tracking/alias (beta): the anonymous id a
visitor was assigned under and the user id they signed in with are one person. From then on, in
each experiment, the assignment stored first among the two ids answers for both, so a user id with
no assignment of its own is answered the variant the anonymous id holds, and its events for that
experiment count toward it. The rules and every answer are in
Link an anonymous id to a known user id.
# In your backend, when the visitor signs in:
server = ExperimentationClient(api_url, server_key) # a key with the sdk:ruleset scope
created = server.alias(visitor_id, customer_id) # False: the link was already stored
- It needs a server-side key: one with the
sdk:rulesetscope, created by a user who can change feature flags. Call it from your backend. - It returns
Truewhen this call stored the link andFalsewhen the link was already stored. - Any other answer raises
ExperimentationError, asget_assignmentdoes, with the server'sstatusandbody:404from a server without the route,403for a key that is not a server-side key,409when a rule refuses the link (the anonymous id is already linked to another user id, for one), and422for an id the server refuses (the two ids equal, for one). A network failure or a timeout raises it withstatusNone. A429is retried once, as for every call. - A failed alias is yours to call again: the client keeps nothing of it. Until it succeeds, the server may give the user id an assignment of its own.
- On success the client sends a key-less
track(user_id, ...)to each experiment a key-lesstrack(anonymous_id, ...)would reach (see the fan-out rule), for 24 hours from the alias, and not to the anonymous id's flags: flags are not linked. It also drops the user id's cached assignments, so its nextget_assignmentasks the server. - The anonymous id's own events keep the anonymous id: nothing already sent, or sent later under it, is changed.
- The copy helps only on the client that assigned the anonymous id. After a browser assigned it
and your backend called
alias, the backend's client holds nothing for the anonymous id: callget_assignment(experiment_key, user_id)there before a key-lesstrack(user_id, ...).
Flag values
A flag serves its on value to the users it is on for, and its off value to everyone else, and
to everyone while it is turned off; a string, number or json flag with a split, or a matched
rule with a value of its own, serves those users that value instead. Who the flag is on for, and
the reason the server gives (targeting_rule or rollout), are decided as for any flag: see
Multi-way flags. For a string, number or json flag, read the value
with the getter of its type: get_string_value, get_number_value or get_json_value.
label = client.get_string_value("checkout-button-label", "user-123", {"plan": "pro"}, default="Buy now")
limit = client.get_number_value("free-shipping-threshold", "user-123", default=50)
theme = client.get_json_value("checkout-theme", "user-123", default={"color": "gray"})
Pass the flag's off value as your default, so that a flag your code cannot reach behaves as off.
default is keyword-only, so a call that passes it by position raises TypeError rather than
evaluating the flag for a user named after your default. OpenFeature's get_string_value takes the
default second; this client takes the user id second.
A getter never raises. It returns your default, logs a warning, and passes the reason to
on_error(error, "value") when the request fails (including a 404 for a flag the server does not
know; error.status says which), when the server's answer carries no value (in server mode, from a
server from before flag values, error.code "INVALID_RESPONSE"; in local mode, every flag the
client answers locally from such a server's ruleset reads as boolean, so the getter reports
"TYPE_MISMATCH"), or when the flag serves another type (error.code "TYPE_MISMATCH", with a
message such as Flag "checkout-button-label" serves a string; get_number_value returned your default).
A boolean flag is another type; read it with is_feature_enabled. Nothing is coerced: "10" is not
a number, and neither is True.
get_number_value returns the number as it was saved: an int, or a float (10.0 stays a
float). get_json_value checks that the value is a dict or a list, and returns a new copy on
every call.
A getter is evaluated as get_feature_flag is: cached per user and flag for cache_ttl_seconds
(0 caches nothing), and in local mode answered from the ruleset. get_feature_flag returns the
same answer with value and value_type; in server mode both are None from a server without
flag values.
Exposure hook
on_exposure is a function you give the client when you create it. The client calls it once each
time the server enrols the user in an experiment and the answer did not come from the client's
cache: the moment the server records the exposure. Use it to send the exposure to your analytics
tool or warehouse.
The example needs an ACTIVE experiment with the key checkout_flow; put your own key in its place.
It prints exposure checkout_flow <variant> user-123 once, or nothing for a user the experiment
did not enrol.
import os
import queue
import threading
from controlvar import ExperimentationClient
exposures = queue.Queue(maxsize=10_000)
def send_exposures():
while True:
exposure = exposures.get()
# Your analytics tool's call goes here: it runs on this thread, not inside get_variant.
print("exposure", exposure.experiment_key, exposure.variant_name, exposure.user_id)
exposures.task_done()
threading.Thread(target=send_exposures, daemon=True).start()
def on_exposure(exposure):
try:
exposures.put_nowait(exposure)
except queue.Full:
pass # drop it rather than make get_variant wait
client = ExperimentationClient(
api_url=os.environ.get("CONTROLVAR_API_URL", "http://localhost:8000"),
api_key=os.environ["CONTROLVAR_API_KEY"],
on_exposure=on_exposure,
)
client.get_variant("checkout_flow", "user-123")
exposures.join()
It receives an Exposure: experiment_key, user_id, variant_id (None when the server sends
none) and variant_name, in a new object for each call. Nothing else: not the user's attributes
and not the variant's configuration. Exposure is a frozen dataclass, exported from controlvar.
It is not called for:
- an answer from the client's cache;
- a user the experiment did not enrol (
assignedFalse, withreason"holdout","mutual_exclusion"or"targeting"), or an experiment that is not running ("draft","paused","completed"or"archived"): the server records no exposure for them, and the client returns the control variant; - a call that fails, including one that times out after the server recorded the exposure;
- a feature flag, in either evaluation mode.
It is not called when the server does not send assigned; every Controlvar server release sends it.
It is called again, and the server records another exposure, after the cache lifetime
(cache_ttl_seconds, 300 seconds by default; with cache_ttl_seconds=0, on every call), after
clear_cache(), and in every new client: each process, such as each worker of a web server, has
its own. So your tool can receive several exposures for one user and experiment: count users, not
events. It never receives one the server did not record.
It is called when your code asks for the assignment, whether or not you then show the variant, so ask for it where the variant is shown.
It runs in the thread that called get_assignment or get_variant, after the answer is cached and
before the call returns, so its running time is added to that call. The client cannot time it out:
a function that blocks for a second makes that call a second slower. Calls for other users and
experiments are not held up. Put the exposure on a queue, as above, so a slow analytics request
never sits inside an assignment.
It can run on several threads at once: make it safe for that. Two threads that ask for the same new user and experiment at the same moment send two requests, and the server records two exposures; the hook is called once.
If it raises, the answer is unchanged. The client logs the error at ERROR, with its traceback, on
the controlvar.client logger, and passes it to on_error with the operation "exposure": an
ExperimentationError whose code is "HOOK_ERROR", whose message starts with
on_exposure failed:, and whose __cause__ is what your function raised. KeyboardInterrupt and
SystemExit are not caught.
An async def, or a functools.partial of one, is refused with TypeError when you create the
client: the client never awaits it, so its body would never run. An object whose __call__ is
async def is not detected then: the coroutine it returns is closed without running, and reported
as above. Anything else it returns, such as an asyncio task it scheduled itself, is left alone.
The constructor raises TypeError for a value that is not callable; None sets none.
In a test, a FakeTransport answer for POST /api/v1/tracking/assign must include
"assigned": True, or the hook is not called.
Backend endpoints used
Every request carries X-API-Key: <key>, Content-Type: application/json and
Accept: application/json.
| SDK call | Method and path | Body / query | Response used |
|---|---|---|---|
get_assignment, get_variant |
POST /api/v1/tracking/assign |
{experiment_key, user_id, context?} |
{experiment_key, user_id, variant_id, variant_name, is_control, configuration, assigned, reason}; 404 when no experiment has the key, or for a draft with no control variant; an experiment that is not ACTIVE answers its control variant with assigned: false |
get_feature_flag, is_feature_enabled |
GET /api/v1/feature-flags/evaluate/{flag_key}?user_id=…&context=<url-encoded JSON> |
context = user_attributes (omitted when empty) |
{key, enabled, config, reason}; enabled: false, reason: "inactive" when the flag is not ACTIVE; 404 only for an unknown key |
get_all_flags |
GET /api/v1/feature-flags/user/{user_id}?context=<url-encoded JSON> |
context = user_attributes (omitted when empty) |
{"<flag_key>": bool, …} |
track with a key |
POST /api/v1/tracking/track |
{event_type, event_name, user_id, experiment_key?, feature_flag_key?, value?, metadata?, timestamp?, event_id?} |
ignored |
track without keys |
POST /api/v1/tracking/batch, one entry per experiment and flag it reaches; with none, POST /api/v1/tracking/track |
{events: [<track body>, …]} (max 100 per request); with none, the track body with no key |
ignored |
track_batch |
POST /api/v1/tracking/batch |
{events: [<track body>, …]} (max 100 per request) |
{success_count, failure_count, errors} |
get_assignments |
GET /api/v1/tracking/assignments/{user_id}?active_only=true |
— | list of dicts |
alias |
POST /api/v1/tracking/alias (beta; a server-side key) |
{anonymous_id, user_id} |
{anonymous_id, user_id, created} |
| local mode: ruleset refresh | GET /api/v1/sdk/ruleset (beta) |
If-None-Match: "<version>" |
the ruleset and ETag; 304 when unchanged |
| local mode: evaluation counts | POST /api/v1/tracking/evaluations (beta) |
{evaluations: [{flag_key, count, enabled_count, window_start, window_end}]} |
{accepted, errors} |
report_error |
POST /api/v1/tracking/errors |
{error_type, message, feature_flag_key?, experiment_key?, user_id?, stack_trace?, metadata?, timestamp?} |
201 and the stored report (only the status is read) |
These SDK paths share a rate-limit ceiling per IP address and path of SDK_RATE_LIMIT_PER_MINUTE
requests (default 6000) on the backend; the SDK honours Retry-After on 429 as described above.
Local evaluation (server-side, beta)
With evaluation="local" the client downloads the flag ruleset (GET /api/v1/sdk/ruleset),
refreshes it on a daemon thread every refresh_interval_seconds (30 s by default, 5 s minimum),
and answers get_feature_flag, is_feature_enabled and get_all_flags in-process whenever it can
give exactly the server's answer; otherwise it makes the usual request. Experiments are always
assigned by the server. It needs an Controlvar server at 0.11.0 or later and a key with the
sdk:ruleset scope, and it is for server-side code only.
from controlvar import ExperimentationClient
with ExperimentationClient(api_url, server_key, evaluation="local") as client:
client.ready(timeout_seconds=5) # optional; never raises
flag = client.get_feature_flag("new_search", "user-123", {"country": "US"})
print(flag.enabled, flag.reason, flag.source) # source: "local" or "server"
A value flag's value is answered locally too, unless it has a split or a rule with a value of its
own: its on value when the flag is on for the user, its off value otherwise, and its off value to
everyone while it is turned off. A flag with a split or a rule's own value is evaluated by the
server while it is on, and answered locally, its off value to everyone, once it is turned off
(see Local evaluation). A flag entry this SDK
cannot read (an evaluation or value_type from a newer server, or a value of the wrong type) is
evaluated by the server, the rest of the ruleset is still answered locally, and, while the flag is
active, status().server_evaluated_flags lists it.
A flag whose stored values the server cannot serve reaches every local client as a
server-evaluated flag, whatever its status (only a direct database write, or a rollback past a
release with wider value limits, produces one). Turning such a flag off does not change the
ruleset. So a local client of any version keeps the server's answer it cached for that user and
flag for up to cache_ttl_seconds (5 minutes by default) before it sees the flag off, and while
the flag exists get_all_flags asks the server on every call.
A change made in the dashboard reaches the process at its next successful refresh. For a flag
with a split or a rule's own value, a change other than turning it off reaches a user the client
has already cached once that answer expires, cache_ttl_seconds (5 minutes by default). While the API
is unreachable the last ruleset keeps being served (set max_stale_seconds to bound that); a 401
or 403 on refresh discards it. A client created before os.fork() (gunicorn --preload) keeps
working in each child, which starts its own refresh thread and reports only its own evaluations.
What is answered locally, the refresh failure table, safety monitoring and troubleshooting:
Local evaluation.
Testing your own code
controlvar.testing.FakeTransport records requests and serves canned responses, so unit
tests can assert the exact request without a network:
from controlvar import ExperimentationClient
from controlvar.testing import FakeTransport
transport = FakeTransport().route(
"GET", "/api/v1/feature-flags/evaluate/new_search",
json={"key": "new_search", "enabled": True, "config": None},
)
client = ExperimentationClient("http://test", "key", transport=transport)
assert client.is_feature_enabled("new_search", "user-1")
assert transport.last.query == {"user_id": "user-1"}
assert transport.last.headers["X-API-Key"] == "key"
Contract smoke
Runs the four contract steps (sticky assignment, flag evaluation, keyed track, key-less fan-out
plus a 2-event batch), sends one event twice with the same event_id, and runs two exposure hook
steps (a new client assigns twice and its hook is called once; a hook that raises is reported)
against a live backend and prints one JSON line:
It prints:
{"sdk":"python","assign":{"variant_name":"control","is_control":true,"sticky":true},"flag":{"enabled":true},"track":{"ok":true},"fanout":{"ok":true},"event_id":{"user_id":"smoke-<uuid>","event_name":"contract_dedup_<uuid>","id":"contract-<uuid>","sends":2},"exposure":{"calls":1,"payload":{"experiment_key":"sdk_contract_ab","variant_name":"control","variant_id":"<id>","user_id":"smoke-<uuid>"}}}
Env: CONTROLVAR_API_URL (default http://localhost:8000), CONTROLVAR_API_KEY (required),
CONTRACT_EXPERIMENT_KEY (default sdk_contract_ab), CONTRACT_FLAG_KEY (default
sdk_contract_flag), CONTRACT_USER_ID (default random smoke-<uuid>). No install is needed;
the script adds sdk/python to sys.path.
CI runs this SDK's contract smoke against a real API: python is in the sdks: list of the
SDK Live Contract job in pr-qa-gate.yml.
Fixtures: backend/scripts/seed_sdk_contract.py; the live
runner: python tests/sdk-contract/live/run_live_contract.py --sdk python --strict.
The runner gives the smoke the seed's sdk:ruleset key as CONTROLVAR_LOCAL_API_KEY. With it the
smoke also links a new anonymous id to a new known id with alias and reports them as alias,
and the runner checks in the database that the two ids hold one assignment row, the anonymous
id's, and that the key-less event the smoke sent under the known id is stored under the anonymous
id with the experiment and its variant.
Development
source venv/bin/activate
python -m pytest sdk/python/tests -q -o addopts="" -p no:cacheprovider
python tests/sdk-contract/hash_contract.py python
python -m pytest sdk/python/tests -q -o addopts="" -p no:cacheprovider: HTTP is fakedpython tests/sdk-contract/hash_contract.py python: this SDK's hash vs the golden vectors