Skip to content

feat(flags): send $experiment_exposure for v2 experiment splits - #1154

Draft
andehen wants to merge 7 commits into
feat/flags-v3-responsefrom
feat/experiment-exposure
Draft

andehen wants to merge 7 commits into
feat/flags-v3-responsefrom
feat/experiment-exposure

Conversation

@andehen

@andehen andehen commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When a remotely evaluated config version 2 flag assigns an experiment variant, the SDK now sends a direct $experiment_exposure event next to $feature_flag_called. $feature_flag_called for every config version 2 flag now also carries the flag's config version, reason code and rule attribution, and the reason code replaces the human-readable $feature_flag_reason on these events.

This stacks on #1031 (base feat/flags-v3-response), which parses the /flags?v=4 records and keeps them on the flag. #1031 left event emission unchanged; this PR is where it changes.

When $experiment_exposure is sent

A read sends $experiment_exposure when it sends $feature_flag_called and all of these hold for the flag record that supplied its value:

  • the record was read without a parse error and is not failed
  • metadata.config_version is 2
  • reason.code is experiment_split
  • metadata.rule_type is experiment
  • metadata.rule_id and metadata.variant_key are present

The reads are get_feature_flag(), feature_enabled(), get_feature_flag_result(), get_feature_flag_payload(..., send_feature_flag_events=True) without match_value, and is_enabled() and get_flag() on an evaluate_flags() snapshot, on both the sync and async clients.

Nothing else sends it: targeting matches, rollouts, rollout misses, holdouts, paused experiments, defaults, failures, config version 1 flags, locally evaluated flags, and stale cached values. send_feature_flag_events=False suppresses both events, and payload reads that send no $feature_flag_called send no exposure either. The exposure goes through the same capture() as $feature_flag_called, so a capture failure never changes the value a read returns.

$feature_flag_called additions

Added only for config version 2 records:

Property Value
$feature_flag_config_version 2
$feature_flag_reason_code reason.code, such as holdout. It replaces the human-readable $feature_flag_reason, which a config version 2 event no longer carries, full or minimal.
$feature_flag_rule_id metadata.rule_id, by the table below
$feature_flag_rule_type metadata.rule_type, by the table below
$feature_flag_variant metadata.variant_key, for a complete experiment split only

What each outcome reports:

Outcome Rule ID and type Variant Exposure
complete experiment_split yes yes yes
targeting_match when present no no
rollout_miss when present no no
experiment_paused when present no no
holdout when present no no
malformed split (see below) no no no
no_rule_match, missing_group_key, flag_disabled, dependency_error, error, any other reason code, and any failed record no no no

The SDK never sends a field the table marks "no", even when the record carries it.

No event carries an experiment ID, a holdout ID or a seed. $feature_flag_response is unchanged.

$experiment_exposure properties

Property Value
$feature_flag Flag key
$feature_flag_response The same value as on its $feature_flag_called (the legacy rendering)
$feature_flag_variant metadata.variant_key
$feature_flag_rule_id metadata.rule_id
locally_evaluated false
$feature_flag_id, $feature_flag_version, $feature_flag_request_id, $feature_flag_evaluated_at Copied from its $feature_flag_called, when present

Like any captured event it also gets the library properties and $groups, and it uses the same distinct ID, groups and GeoIP setting as its $feature_flag_called. It is a separate capture with its own event UUID. It carries no payload and no $feature/<key>. It does not carry the config version, rule type, reason code or an exposure source; the config version, rule type and reason code stay on the $feature_flag_called of the same read.

Dedupe

  • $feature_flag_called keeps its dedupe key (distinct ID, flag key, response, sorted groups). For a config version 2 record the key also includes the config version, reason code, rule ID, rule type and variant key. Equal-valued A/A arms, successive experiments on one flag, and a holdout followed by a split of the same rule are therefore each reported. Config version 1 keys are unchanged.
  • $experiment_exposure has its own cache, keyed by the distinct ID as a string, the sorted groups, the flag key, the config version, the rule ID and the variant key. The value, request ID, evaluation time and local/remote source are left out, so one assignment sends one exposure however often it is read. Because the cache is separate, a $feature_flag_called that was already reported never suppresses its exposure. It has the same bound and eviction as the flag-called cache, and shutdown clears it.

What does not change

  • Config version 1 flags: same properties, including $feature_flag_reason, same dedupe key.
  • Local evaluation: this SDK evaluates only config version 1 flags locally, so locally evaluated flags send no exposure and no new properties.
  • $feature_flag_response stays the legacy rendering of the value.
  • Responses from servers without typed values: their records read as config version 1, so they send nothing new and keep $feature_flag_reason.

Notes for reviewers

  • One shared step. _capture_flag_events in posthog/client.py builds both events. Both clients' _capture_feature_flag_called_if_needed, which every single-flag getter and snapshot read already goes through, now call it, and the snapshot passes the record it already keeps from feat(flags): read the /flags?v=4 response #1031. A later read that reports through the snapshot's _record_access, such as the typed accessors in feat(flags): typed flag value accessors #1147 or the per-read option in feat: add a per-read send_feature_flag_events option to snapshot reads #1148, gets the exposure without changes. The decision reads the record, never the value the accessor returned, so a typed read that returns the caller default for a null or false value still reports the assignment, as docs(flags): propose typed flag values and evaluation details sdk-specs#104 asks. A typed read of the wrong type (TYPE_MISMATCH) sends neither event (feat(flags): typed flag value accessors #1147).
  • Private fields. feat(flags): read the /flags?v=4 response #1031 keeps the v4 fields private (_failed, _config_version and so on), and feat(flags): typed flag value accessors #1147 makes them public. _v4_field reads either spelling, so this PR and feat(flags): typed flag value accessors #1147 can merge in either order; the fallback can go once both have landed. A local merge with feat(flags): typed flag value accessors #1147 at b749299 has no conflicts and the flag test modules pass. Its typed reads send the exposure. A read of the wrong type sends neither event; the next read of the right type, or a get_flag() or is_enabled() read, then sends both.
  • Malformed splits. An experiment_split record without rule type experiment, a rule ID or a variant key sends no exposure. Its $feature_flag_called keeps the config version and reason code but leaves out the rule ID, rule type and variant together, never part of them. The SDK never guesses the identity from the value, the key or an earlier result.
  • Rule fields by reason code. Rule ID and rule type are sent only for the reason codes that name a terminal rule: targeting_match, rollout_miss, experiment_paused, holdout and a complete experiment_split. Every other reason code, including codes this SDK does not know, and every failed record send neither, even if the record carries them. Only a complete split sends $feature_flag_variant. This is a small allowlist in _rule_attribution, and it fails closed like the malformed split. It matches the contract's $feature_flag_called property schema.
  • Values the record did not supply. The exposure depends on where the reported value came from, never on comparing values. Comparing would not work: every number and object value reads as true. The single-flag path sets value_from_details only when the remote record supplied the value. get_feature_flag_payload(match_value=..., send_feature_flag_events=True) reports the caller's value, so it sends no exposure, even when that value equals the record's. Its call keeps the record's attribution, so it still reads as a config version 2 event, and a later read of the record sends the exposure. A stale cached value used after a failure sends no exposure either. Snapshot reads always report their record's value.
  • Minimal events. The five attribution properties are added to the minimal-event allowlist so minimization never strips them, as docs(flags): specify SDK-sent $experiment_exposure for config version 2 flags sdk-specs#162 requires. $feature_flag_reason stays on the allowlist for config version 1 events; a config version 2 event drops it before the allowlist applies. The exposure is never minimized.
  • Fixtures. The tests run every reader case of the vendored contract through every read path on both clients. They also validate the events against the contract's $feature_flag_called and $experiment_exposure property schemas, copied unchanged from harness release 1.27.0 (contract 8.0.0) and recorded in SOURCE.json. That release trims the exposure schema to the properties this SDK sends and rejects $feature_flag_reason on config version 2 calls. The schema projection drops undeclared properties, so the tests also assert that no exposure carries $feature_flag_config_version, $feature_flag_rule_type, $feature_flag_reason_code or $experiment_exposure_source.
  • Compliance adapter. The test harness has no exposure capability or exposure cases yet, so the adapter advertises nothing new.
  • Spec. docs(flags): specify SDK-sent $experiment_exposure for config version 2 flags sdk-specs#162 (draft, change add-experiment-exposure) is the cross-SDK contract for this behaviour: when the exposure is sent, its properties, the $feature_flag_called attribution and rule-field table, both dedupe keys, and minimal events. This PR follows it. The $feature_flag_called dedupe key here also includes the reason code and rule type, which fix(llm-observability): include the ai packages #162 is adopting.

Test plan

  • posthog/test/test_experiment_exposure.py: the reader cases on every read path and both clients, exact property sets (no exposure carries the four removed properties), rule fields by reason code (including stray rule fields on no-rule, failed and unknown-reason records), schema validation of every $feature_flag_called context, separate UUIDs, dedupe (repeat reads, A/A arms, a new rule, value changes, groups, distinct ID types, a reported call not suppressing its exposure), opt-out, payload reads, local evaluation, older servers, minimal events, shutdown
  • $feature_flag_reason: left out of config version 2 calls (targeting match, no rule match, failed, split) on every read path, on the async client and on minimal events; kept on config version 1 and older-server calls, full and minimal
  • Full suite: uv run --frozen --all-extras pytest -q -p no:cacheprovider posthog/test
  • ruff format --check ., ruff check ., mypy with the baseline filter, public API snapshot unchanged

🤖 Generated with Claude Code

Copy the $feature_flag_called and $experiment_exposure property schemas
unchanged from the same test harness release as the other contract
fixtures, and record their digests in SOURCE.json.
A remotely evaluated config version 2 flag whose record assigns an
experiment variant now sends $experiment_exposure next to
$feature_flag_called. $feature_flag_called for every config version 2
flag also reports its config version, reason code, rule ID, rule type
and, for a complete split, variant key, and its dedupe key includes
them so equal-valued arms and successive experiments are each reported.

Both events are built in one step that every flag read goes through on
both clients, from the parsed record that supplied the value. The
exposure has its own dedupe cache, keyed by distinct ID, groups, flag,
rule and variant, so a reported call never suppresses it. A split
missing its rule type, rule ID or variant key sends no exposure and
reports no rule tuple. Config version 1 flags, local evaluation and
$feature_flag_response are unchanged.
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-30T20:01:15.399514+00:00
Duration: 259604ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 515ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 510ms
Required Headers.Has Authorization Bearer Header ✅ 509ms
Required Headers.Has Content Type Json ✅ 508ms
Required Headers.Has Posthog Sdk Info Format ✅ 509ms
Required Headers.Has Posthog Attempt Header ✅ 509ms
Required Headers.Has Posthog Request Id ✅ 508ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 509ms
Body Format.Body Has Created At And Batch ✅ 508ms
Body Format.No Api Key In Body ✅ 509ms
Body Format.No Sent At In Body ✅ 509ms
Event Format.Event Has Required Root Fields ✅ 508ms
Event Format.Event Uuid Is Valid ✅ 509ms
Event Format.Event Timestamp Is Rfc3339 ✅ 508ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 519ms
Event Format.Distinct Id Is String ✅ 509ms
Event Format.Distinct Id At Root Not Properties ✅ 509ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 508ms
Event Format.Groups Properties Preserved ✅ 508ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 508ms
Event Format.Event Has Required Root Fields Batch ✅ 511ms
Event Format.Event Uuid Is Valid Batch ✅ 512ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 511ms
Event Format.Distinct Id Is String Batch ✅ 511ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 511ms
Event Format.Custom Properties Preserved Batch ✅ 511ms
Event Format.Set Properties Preserved Batch ✅ 511ms
Event Format.Set Once Properties Preserved Batch ✅ 510ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 529ms
Batch Behavior.Multiple Events In Single Batch ✅ 515ms
Batch Behavior.Batch Envelope Smoke ✅ 512ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1009ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 511ms
Deduplication.Preserves Uuid On Retry ✅ 6513ms
Deduplication.Preserves Timestamp On Retry ✅ 6517ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6516ms
Deduplication.No Duplicate Events In Batch ✅ 515ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 509ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13524ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6513ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3017ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6514ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 509ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 512ms
Response Format Validation.Success No Retry After When All Ok ✅ 510ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1520ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 508ms
Retry Behavior.Retries On 408 ✅ 6517ms
Retry Behavior.Retries On 500 ✅ 6518ms
Retry Behavior.Retries On 503 ✅ 8519ms
Retry Behavior.Retries On 504 ✅ 6518ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11516ms
Retry Behavior.Does Not Retry On 400 ✅ 2512ms
Retry Behavior.Does Not Retry On 401 ✅ 2512ms
Retry Behavior.Does Not Retry On 402 ✅ 2511ms
Retry Behavior.Does Not Retry On 413 ✅ 2512ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22534ms
Retry Behavior.Max Retries Respected ✅ 22523ms
Partial Batch Handling.Handles 200 Full Success ✅ 2510ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3514ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6516ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6519ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6519ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8519ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3515ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 509ms
Compression.Compressed Body Is Decompressible ✅ 509ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 508ms
Event Options.Disable Skew Correction Override ✅ 509ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 509ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 512ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 509ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 509ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 508ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 509ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 508ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 509ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 9ms
Request Payload.Flags Request Uses V4 Query Param ✅ 7ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 7ms
Request Payload.Flags Request Omits Authorization Header ✅ 8ms
Request Payload.Token In Flags Body Matches Init ✅ 7ms
Request Payload.Groups Round Trip ✅ 7ms
Request Payload.Groups Default To Empty Object ✅ 7ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 8ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 8ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 7ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 12ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 7ms
Retry Behavior.Retries Flags On 502 ✅ 311ms
Retry Behavior.Retries Flags On 504 ✅ 312ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 510ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 55ms
Versioned Boolean Matching.Matching Version 1 ✅ 54ms
Versioned Boolean Matching.Matching Version 2 ✅ 53ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 32ms

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostHog Review · Standard · reviewed fdb2709: 4 Should fix.

This is the only automatic review while this pull request is a draft. Comment @posthog review to review new changes sooner. Otherwise, a review of the new changes runs when you mark it ready for review.

See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.

Comment thread posthog/client.py Outdated
Comment on lines +4753 to +4754
value_from_details=isinstance(flag_details, FeatureFlag)
and response == flag_details.get_value(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Track explicit payload overrides independently of value equality

When get_feature_flag_payload() receives an explicit match_value equal to the remote split's value, this equality marks the caller's override as server-supplied and emits $experiment_exposure. The payload lookup also consumes the exposure dedupe entry before a subsequent value read. Thread the override's presence through instead of inferring provenance from equality.

Comment thread posthog/client.py
)
reported_flags.add(feature_flag_reported_key)

if attribution is None or attribution.variant_key is None or not value_from_details:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Exclude failed records from exposure emission

When a v4 record has failed: true but retains complete split metadata, the parser discards its value and returns the disabled fallback. _capture_flag_events nevertheless emits $experiment_exposure for the retained variant on both clients, counting a failed evaluation as an assignment. Check the parsed failure state before emitting an exposure.

Comment thread posthog/client.py
groups=capture_groups,
disable_geoip=disable_geoip,
)
reported_exposures.add(exposure_key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Record exposure deduplication only after capture succeeds

When the capture queue fills, capture() returns None, but _capture_flag_events still adds the assignment to reported_exposures. Every subsequent read suppresses that exposure after the queue recovers, losing experiment attribution until eviction or shutdown. Check the capture result and retain the dedupe entry only when the event is accepted.

Comment thread posthog/client.py
Comment on lines +564 to +565
if exposure_key in reported_exposures:
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Reserve exposure keys atomically before capturing

When threads read the same assignment with sync_mode=True, the first exposure's network request releases execution before its key is recorded. Another thread passes this check and sends another exposure with a separate UUID, defeating per-assignment deduplication. Atomically reserve the key before capture and release the reservation when capture fails.

$feature_flag_called for a config version 2 record now sends
$feature_flag_rule_id and $feature_flag_rule_type only for a targeting
match, a rollout miss, a paused experiment, a holdout and a complete
experiment split. Any other reason code, including one the SDK does not
know, and any failed record send neither, even when the record carries
them. A failed experiment split therefore sends no exposure either.
The single-flag path decided whether a read's record supplied its value
by comparing the reported value with the record's. Equal values do not
show where a value came from: a payload lookup whose match_value equals
the record's value, such as True for a number or object arm, sent the
exposure and reserved its dedupe key, so the real read sent none.

The path now sets value_from_details only when the remote record
supplied the value: not for a caller's match_value, and not for a stale
cached value used after a failure. Snapshot reads pass it explicitly,
and the capture helpers default to no exposure.
$experiment_exposure no longer carries $feature_flag_config_version,
$feature_flag_rule_type, $feature_flag_reason_code or
$experiment_exposure_source. The exposure of a complete config version 2
experiment split identifies the assignment by flag, variant key and rule
ID; the config version, rule type and reason code stay on the
$feature_flag_called of the same read. The trigger, both dedupe keys and
$feature_flag_response are unchanged.

The vendored exposure schema still requires the removed properties, so
the tests check exposures against it without them, and check that they
are absent.
$feature_flag_called for a config version 2 flag carried both
$feature_flag_reason_code and the human-readable $feature_flag_reason.
The reason code now replaces the description on these events, full and
minimal. Events of config version 1 flags, flags from servers without
typed values and locally evaluated flags keep $feature_flag_reason as
before.
Contract 8.0.0 trims the experiment exposure schema to the properties
the SDK sends and rejects $feature_flag_reason on config version 2
calls, so the exposure validator no longer drops properties from the
vendored schema. The four other vendored files are unchanged.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant