Skip to content

feat(flags): typed flag value accessors - #1147

Draft
andehen wants to merge 18 commits into
feat/flags-v3-responsefrom
feat/flags-typed-accessors
Draft

andehen wants to merge 18 commits into
feat/flags-v3-responsefrom
feat/flags-typed-accessors

Conversation

@andehen

@andehen andehen commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

#1031 reads the /flags?v=4 response and keeps each flag's typed value, reason and metadata, but adds no accessors for reading them. Callers still cannot read a number or object flag value as such, or see why a flag returned what it did.

Changes

The typed accessor API, split out of #1031 so that change can ship without new public methods:

  • get_boolean_value, get_string_value, get_number_value, get_integer_value, get_float_value and get_object_value on the evaluate_flags() snapshot, each with a _details form.
  • Every typed accessor, in both forms, takes the keyword-only send_feature_flag_events option, with the same meaning as on is_enabled() and get_flag() (feat: add a per-read send_feature_flag_events option to snapshot reads #1148). With send_feature_flag_events=False, the read sends no $feature_flag_called and leaves the dedupe cache alone, so a later read that sends events still reports the flag. The key still counts as accessed for only_accessed(). The value form passes the option to its details form.
  • FlagEvaluationDetails, FlagEvaluationReason and FlagEvaluationErrorCode, with OpenFeature reasons and error codes. The accessors never coerce: they return the caller default when the flag is missing, failed, unreadable, has no value, or has a value of another type.
  • A read of the wrong type (TYPE_MISMATCH, any of the 12 methods, either client) returns the caller default with the same details as before, but sends no $feature_flag_called and takes no dedupe slot. With feat(flags): send $experiment_exposure for v2 experiment splits #1154 that also means no $experiment_exposure. The next read of the right type, or a get_flag() or is_enabled() read, sends the event as a first read. The client logs the details' error_message as an error once per (flag key, requested type), in a cache bounded like the flag-event dedupe cache. The read still counts as accessed for only_accessed(), as before. A false or null value read through a non-boolean accessor, missing, failed and unreadable flags, and send_feature_flag_events=False keep their behaviour.
  • Numbers are binary64. get_number_value/get_number_details return an integer beyond 2**53 - 1 in magnitude as the nearest float, so Python returns what JavaScript does; an integer within range stays an int. get_float_value returns every number as the nearest float. An integer beyond the range of a double reads as an infinity, with its sign, through both. The integer accessors keep TYPE_MISMATCH beyond 2**53 - 1.
  • Details of a locally evaluated flag carry the local definition's id and version in flag_metadata. The snapshot record used to set version to None for a local flag. It now takes it from the definition, which is the same one-line change fix: send flag id and version on locally evaluated $feature_flag_called #1149 makes, so the $feature_flag_called event of a local snapshot read also carries $feature_flag_version. This branch and fix: send flag id and version on locally evaluated $feature_flag_called #1149 merge without conflicts.
  • error_code and error_message on FeatureFlag, including the cause for a flag local evaluation could not resolve.
  • Makes public the fields feat(flags): read the /flags?v=4 response #1031 keeps private until this API ships: value and failed on FeatureFlag, and config_version, rule_type, rule_id, variant_key and forced_variant on FlagMetadata.

This stacks on #1031 (base feat/flags-v3-response) and waits for the cross-SDK accessor spec in PostHog/sdk-specs#104. Names and semantics may change to match it.

This branch includes #1148 (merged from feat/snapshot-flag-event-option), because the typed accessors use its _record_access(key, send_feature_flag_events). Until #1148 lands on main and main is merged into #1031, #1148's diff (the option on is_enabled() and get_flag(), its tests and its changeset) also shows here. Review that part on #1148.

Testing

  • test_flags_v4_response.py, for each of the 12 typed methods on the sync and the async client:
    • With send_feature_flag_events=False, the read returns the flag's value, sends no $feature_flag_called and marks the key in only_accessed(). A later read with the default then sends exactly one event.
    • With the default, a read sends exactly one event, and a repeated read with send_feature_flag_events=True sends no second one.
    • Mutation check: these tests fail if the shared resolver ignores the option, if one value form does not pass it to its details form, or if one details form does not pass it to the resolver.
  • Type mismatches, for each of the 12 typed methods on the sync and the async client: a read of the wrong type returns the default with TYPE_MISMATCH, sends no $feature_flag_called, still marks the key in only_accessed(), and logs its error_message once although read twice. A later right-type read (value and details form), get_flag() or is_enabled() then sends exactly one event, on both clients. Two wrong types on one key log twice, a second snapshot from the same client logs nothing new, a read with send_feature_flag_events=False logs nothing new, and another client logs again. A null or false value read as another type, and a missing, failed or unreadable flag, still send their event and log nothing.
  • Numbers: the number accessor at ±(253 − 1) returns that int, and at ±253 and ±(253 + 1) the float ±253. The integer accessor returns TYPE_MISMATCH at ±253 and ±(253 + 1), and the float accessor returns the nearest float at all six. ±10**400 reads as ±infinity through the number and float accessors.
  • test_locally_evaluated_details_carry_the_definition_version: local boolean (value and details forms) and multivariate details carry the definition's version, a definition without one leaves it out, and the $feature_flag_called event reports the same version. The test fails without either half of the change.
  • With feat(flags): send $experiment_exposure for v2 experiment splits #1154 merged in locally (not pushed), a typed read with send_feature_flag_events=False on a v2 experiment split sends neither $feature_flag_called nor $experiment_exposure, as docs(flags): specify SDK-sent $experiment_exposure for config version 2 flags sdk-specs#162 asks. A later default read sends each event once. This holds for all 12 methods on both clients. The flag test modules also pass on the combined tree.
  • With feat(flags): send $experiment_exposure for v2 experiment splits #1154 merged in locally at 119a4c6 (not pushed), a typed read of the wrong type on a v2 experiment split sends neither $feature_flag_called nor $experiment_exposure, for each typed method on both clients, and the next right-type or get_flag()/is_enabled() read sends both. The flag test modules pass on the combined tree, which merges without conflicts.
  • pytest posthog/test: 6210 passed, 25 skipped, 3 failed. The 3 failures are the forked-child tests in test_metrics_autocapture.py, a macOS fork-safety crash. They also fail on main in a full run and pass when that file runs alone.
  • ruff format --check, ruff check, mypy (baseline filter) and the public API snapshot check pass.

🤖 Generated with Claude Code

Add get_boolean_value, get_string_value, get_number_value,
get_integer_value, get_float_value and get_object_value to the
evaluate_flags() snapshot, each with a _details form that returns a
FlagEvaluationDetails with an OpenFeature reason, error_code and
flag_metadata. The accessors never coerce: they return the caller default
when the flag is missing, failed, has no value, or has a value of another
type.

@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 3f8c315: 2 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/types.py Outdated
Comment on lines +611 to +613
"object": lambda value: (
copy.deepcopy(value) if isinstance(value, dict) else _NOT_ACCEPTED
),

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 · Handle recursion failures when copying object flag values

A valid JSON object nested 600 levels deep passes FeatureFlag.from_json, but copy.deepcopy exceeds Python's default recursion limit. Both get_object_value and get_object_details then propagate RecursionError into application code instead of returning a safe result, defeating the accessor's fallback behavior. Use an iterative copy or handle copy failures with the caller default.

Comment thread posthog/types.py
Comment on lines +745 to +747
id=metadata.id,
version=metadata.version,
config_version=metadata.config_version,

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 · Preserve absent metadata fields in evaluation details

When a typed record omits metadata.id or metadata.version, or sets either to null, parsing replaces it with 0. _resolve_flag_details then exposes that fabricated value in flag_metadata, violating the documented presence contract and giving consumers an identifier or version the server never supplied. Preserve field absence through parsing and omit those entries.

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-30T18:38:54.250111+00:00
Duration: 259804ms

✅ 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 ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 512ms
Required Headers.Has Authorization Bearer Header ✅ 511ms
Required Headers.Has Content Type Json ✅ 511ms
Required Headers.Has Posthog Sdk Info Format ✅ 511ms
Required Headers.Has Posthog Attempt Header ✅ 511ms
Required Headers.Has Posthog Request Id ✅ 510ms
Required Headers.Has Posthog Request Timestamp ✅ 511ms
Required Headers.Has User Agent ✅ 511ms
Body Format.Body Has Created At And Batch ✅ 511ms
Body Format.No Api Key In Body ✅ 510ms
Body Format.No Sent At In Body ✅ 511ms
Event Format.Event Has Required Root Fields ✅ 511ms
Event Format.Event Uuid Is Valid ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 520ms
Event Format.Distinct Id Is String ✅ 511ms
Event Format.Distinct Id At Root Not Properties ✅ 510ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 510ms
Event Format.Set Once Properties Preserved ✅ 511ms
Event Format.Groups Properties Preserved ✅ 512ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 510ms
Event Format.Event Has Required Root Fields Batch ✅ 513ms
Event Format.Event Uuid Is Valid Batch ✅ 515ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 513ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 514ms
Event Format.Set Once Properties Preserved Batch ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 513ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 517ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1012ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 511ms
Deduplication.Generates Unique Uuids ✅ 517ms
Deduplication.Different Events Same Content Different Uuids ✅ 515ms
Deduplication.Preserves Uuid On Retry ✅ 6519ms
Deduplication.Preserves Timestamp On Retry ✅ 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6521ms
Deduplication.No Duplicate Events In Batch ✅ 518ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13525ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6518ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 513ms
Response Format Validation.Success No Retry After When All Ok ✅ 513ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 514ms
Response Format Validation.Response Echoes Request Id ✅ 512ms
Retry Behavior.Retries On 408 ✅ 6520ms
Retry Behavior.Retries On 500 ✅ 6520ms
Retry Behavior.Retries On 503 ✅ 8524ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11523ms
Retry Behavior.Does Not Retry On 400 ✅ 2513ms
Retry Behavior.Does Not Retry On 401 ✅ 2516ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2514ms
Retry Behavior.Does Not Retry On 415 ✅ 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2514ms
Retry Behavior.Implements Backoff ✅ 22538ms
Retry Behavior.Max Retries Respected ✅ 22533ms
Partial Batch Handling.Handles 200 Full Success ✅ 2514ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3516ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3518ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6523ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6523ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8519ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3519ms
Compression.Sends Gzip Content Encoding ✅ 512ms
Compression.No Content Encoding When Disabled ✅ 510ms
Compression.Compressed Body Is Decompressible ✅ 511ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2513ms
Event Options.Cookieless Mode Override ✅ 512ms
Event Options.Disable Skew Correction Override ✅ 511ms
Event Options.Process Person Profile Override ✅ 511ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 512ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 512ms

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 13ms
Request Payload.Flags Request Uses V4 Query Param ✅ 9ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 9ms
Request Payload.Flags Request Omits Authorization Header ✅ 8ms
Request Payload.Token In Flags Body Matches Init ✅ 8ms
Request Payload.Groups Round Trip ✅ 8ms
Request Payload.Groups Default To Empty Object ✅ 8ms
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 ✅ 9ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 9ms
Retry Behavior.Retries Flags On 502 ✅ 313ms
Retry Behavior.Retries Flags On 504 ✅ 314ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 512ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 61ms
Versioned Boolean Matching.Matching Version 1 ✅ 55ms
Versioned Boolean Matching.Matching Version 2 ✅ 55ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 29ms

@andehen andehen mentioned this pull request Oct 29, 2026
5 tasks done
The integer accessors reject numbers beyond 2**53 - 1 in magnitude, such
as 1e21, so every SDK returns the same result for the same flag. A test
also pins that a throwing before_send does not break a typed read.
# Conflicts:
#	posthog/test/test_flags_v4_response.py
#	posthog/types.py
#	references/public_api_snapshot.txt
The object accessors copy the value so a caller cannot change the snapshot. A
value nested deeply enough made that copy raise RecursionError; it now returns
the caller default with PARSE_ERROR, so a typed read never throws.
…t/flags-typed-accessors

# Conflicts:
#	posthog/test/test_flags_v4_response.py
#1031 keeps the v4 value and rule metadata fields private. The typed
accessors make them public, so this branch keeps them public and the
changeset lists them.
…d accessors

Every typed value and details accessor on the evaluate_flags() snapshot now
takes the keyword-only send_feature_flag_events option that is_enabled() and
get_flag() take. With send_feature_flag_events=False the read sends no
$feature_flag_called and leaves the dedupe cache alone, so a later read that
sends events still reports the flag. The key still counts as accessed for
only_accessed(). The value form passes the option to its details form, so
both forms behave the same.
Typed details of a locally evaluated flag left the flag version out of
flag_metadata. The local flag definition carries the version, but the
evaluate_flags() snapshot record set it to None. The record now takes the
version from the definition, and the details add it to flag_metadata when it
is present. The record change is the same one #1149
makes, so $feature_flag_called for a snapshot read of a locally evaluated
flag also carries $feature_flag_version.
…ccessor

Numbers are IEEE-754 doubles in every PostHog SDK. get_number_value and
get_number_details returned an integer beyond 2**53 - 1 in magnitude
exactly, so Python could return a value JavaScript cannot. They now
return the nearest float. Integers within range keep their int type,
the integer accessors keep TYPE_MISMATCH beyond the range, and the
float accessors are unchanged. An integer too large for any double is
a TYPE_MISMATCH, as in the float accessor.
A typed accessor that resolves to TYPE_MISMATCH returned the caller's
default and still sent $feature_flag_called, which took the dedupe slot,
so the later read of the right type sent nothing. A read of the wrong
type is a bug in the calling code, not a use of the flag. It now sends
no event and takes no dedupe slot, so the next read of the right type,
or a get_flag() or is_enabled() read, reports the flag.

The client logs the error_message once per flag key and requested
type, in a cache bounded like the flag-event dedupe. The read still
counts as accessed for only_accessed(). A false or null value read as
another type, missing, failed and unreadable flags, and reads with
send_feature_flag_events=False are unchanged.
The float accessor returned TYPE_MISMATCH for an integer too large to
convert to a float, and the number accessor followed it. JavaScript
parses such a number as an infinity, the nearest IEEE-754 double. Both
accessors now return that infinity, with its sign, so every PostHog SDK
reads the same value. The integer accessors keep TYPE_MISMATCH.
… state

Move the client's record of logged type mismatches next to
_logged_untyped_flags_response, the other once-per-client flag log
state, in both clients.

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