Skip to content

feat(flags): read the /flags?v=3 response with typed values - #1031

Draft
andehen wants to merge 3 commits into
mainfrom
feat/flags-v3-response
Draft

andehen wants to merge 3 commits into
mainfrom
feat/flags-v3-response

Conversation

@andehen

@andehen andehen commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Public API change. This adds typed accessors to FeatureFlagEvaluations (get_boolean_value / get_boolean_details, and the same for string, number and object), the FlagEvaluationDetails and FlagEvaluationErrorCode types, new fields on FeatureFlag (value, failed, error_code, error_message) and new fields on FlagMetadata (config_version, rule_type, rule_id, variant_key, forced_variant). Existing getters keep their results.

The flags service can now answer /flags?v=3 (PostHog/posthog#107732). A v3 record carries one typed value (boolean, string, number, object or null) instead of enabled and variant, plus a structured reason and rule metadata. This PR moves the SDK to that response and keeps the full record for each flag, instead of reducing it to a value.

The reader follows the wire contract published in posthog-sdk-test-harness 1.13.1 (contracts/feature_flag_rules_v2):

  1. Both clients request /flags/?v=3. A record with value is a v3 record. A record without it comes from a server that does not serve v3 (an older or self-hosted deployment, or one with the v3 response turned off). Its value is variant, or enabled when there is no variant, its config version is 1, and any rule context in it is ignored. No probing or retry is needed.
  2. Unknown fields are ignored. A known field with the wrong JSON type fails only that record, with PARSE_ERROR; other flags in the response are unaffected. Before, a record that was not an object made the whole response fail to parse.
  3. Typed accessors never coerce. A null value, or false read as another type, returns the caller default without an error. Any other value of the wrong type returns the default with TYPE_MISMATCH.
  4. The legacy rendering is derived from value in one place, when the record is parsed: a boolean as is, a string as the variant, null as false, and a number or object as true with the value as a JSON-encoded payload. That is the shape servers send at v=2 today, so get_feature_flag, get_feature_flag_result, get_feature_flag_payload, get_all_flags(_and_payloads), the snapshot getters, $feature/<key>, $active_feature_flags and $feature_flag_called return the same values for both responses.
  5. A key missing from the response is FLAG_NOT_FOUND. A failed record is GENERAL (INVALID_CONTEXT when a required group is missing), with the reason description as the message. Both return the caller default.
flags = posthog.evaluate_flags("user-1")
limit = flags.get_number_value("upload-limit", 10)
copy = flags.get_string_details("banner-copy", "Welcome")
copy.value, copy.reason, copy.metadata, copy.error_code

$feature_flag_called is unchanged: same properties, same deduplication. A typed accessor counts as an access, exactly like get_flag(). Local evaluation is unchanged.

Notes for reviewers

  • The typed accessors are on the evaluate_flags() snapshot only, so they work for the sync and async clients. I did not add single-flag client methods, because the single-flag getters are deprecated in favour of evaluate_flags(). They are easy to add if we want them.
  • v3 leaves metadata.payload null for number and object values. To keep the legacy payload getters working, FlagMetadata.payload holds the value encoded as compact JSON in wire key order. Decoded payloads are identical to v=2. The encoded string matches the server's except for the spelling of float exponents (1e-07 here, 1e-7 from the server).
  • FlagMetadata.from_json() (the older record) now sets config_version=1, so one existing test that compared parsed metadata by equality was updated.
  • With a server that sends the older record, typed number and object reads return the default with TYPE_MISMATCH, because that record carries those values only in the payload. Legacy getters are not affected.
  • For flags in the new format, the server writes different reason.description texts at v3 than at v2 ("Matched rule 2" instead of "Matched condition set 2"). FeatureFlagResult.reason and $feature_flag_reason show the v3 text once a server sends v3. Values do not change, and v1 flags are identical in every field.
  • The SDK compliance suite's flags_request_uses_v2_query_param test asserts that the flags request uses v=2. Both compliance jobs fail on that one test, and pass everything else, until the harness accepts v=3. This PR does not change the harness.
  • A v3 record carries no experiment ID and no holdout ID. An experiment is linked to its rule on the server, by rule ID, and a holdout in the new format is local to its rule and has no ID (older records never sent one). So FlagMetadata has neither experiment_id nor holdout_id. A complete experiment split is config version 2, reason experiment_split, rule type experiment, a rule ID and a variant key; a holdout result is its rule ID with reason holdout. A record that still sends metadata.experiment_id or metadata.holdout_id has the key ignored, like any unknown field. Either field can be added back later without a breaking change if the server starts sending it.
  • This PR does not advertise any new SDK capability and does not emit $experiment_exposure.
  • Please do not merge yet: the release should wait until the server side is ready. The changeset is minor.

💚 How did you test it?

  • New posthog/test/test_flags_v3_response.py (193 tests), built on fixtures copied unchanged from the released harness contract. posthog/test/fixtures/feature_flag_rules_v2/SOURCE.json records the release, revision and file digests, and a test checks them. It covers:
    • all 37 reader fixtures, through the typed accessors. The vendored 1.13.1 fixtures still carry metadata.experiment_id and metadata.holdout_id, which the reader now ignores, so two cases that depend on experiment_id (partial_split_missing_experiment_id, split_wrong_type_experiment_id) are overridden in the test to expect a complete split. No reader case depends on holdout_id. When the harness releases a contract without these fields, the fixtures get re-pinned and the overrides removed;
    • all 25 valid producer responses, retained field by field (except the two ignored ID fields);
    • boolean, string, number and object v3 values against every typed accessor (coercion, null and false handling, TYPE_MISMATCH);
    • 18 wrongly typed known fields, sibling isolation and unknown fields, including experiment_id and holdout_id keys of either type;
    • failed, missing-group and absent records;
    • legacy parity: the 11 cases of the v1 legacy projection corpus and the 38 successful typed value corpus cases render the same legacy values from a v2-shaped and a v3-shaped record. One end-to-end test runs every legacy getter, the snapshot, capture(flags=...) and capture(send_feature_flags=True) against both shapes and compares every result and $feature_flag_called event;
    • the async client.
  • Full suite, ruff format --check, ruff check, mypy with the baseline filter, python -W error -c "import posthog", the public API snapshot check, and the OpenFeature provider's tests.
  • Ran this branch against a flags service built locally from master, with the v3 response turned on and then off, reading v1 flags and new-format boolean, string, number and object flags. With it on, the typed accessors returned the typed values with their reason and rule metadata. With it off, the SDK read the older record. Legacy values, payloads and $feature_flag_called events were identical between the two runs, apart from the reason description text noted above.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written with Claude Code (Claude Opus) from a brief by the assignee. The agent surveyed the existing v2 parsing path and extended it rather than adding a parallel one: the parsed FeatureFlag now carries the typed value and error, and the legacy fields are derived from it once. Choices the reviewer may want to revisit are listed under "Notes for reviewers".

🤖 Generated with Claude Code

Request /flags?v=3 from the sync and async clients and keep each flag's
typed value, structured reason and metadata on the parsed record.

- A record with a value member is a v3 record. A record without one comes
  from an older server: its value is variant, or enabled without one, and
  its config version is 1.
- A known field with the wrong JSON type fails only that record with
  PARSE_ERROR; unknown fields are ignored.
- Legacy getters, callbacks and $feature_flag_called keep reading the
  legacy rendering, now derived from value in one place: a string is the
  variant, null is disabled, and a number or object is enabled with the
  value as a JSON-encoded payload.
- evaluate_flags() snapshots gain get_boolean/string/number/object_value
  and _details accessors. They never coerce and return the caller default
  for missing, failed, null and mismatched values.
@andehen andehen self-assigned this Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-15T12:29:34.441132+00:00
Duration: 259800ms

⚠️ Some Tests Failed

120/121 tests passed, 1 failed


Capture_V1 Tests

✅ 95/95 tests passed

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

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

⚠️ 16/17 tests passed, 1 failed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 11ms
Request Payload.Flags Request Uses V2 Query Param ❌ 9ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 9ms
Request Payload.Flags Request Omits Authorization Header ✅ 10ms
Request Payload.Token In Flags Body Matches Init ✅ 9ms
Request Payload.Groups Round Trip ✅ 9ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 8ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 10ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 509ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 14ms
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

Failures

request_payload.flags_request_uses_v2_query_param

Expected /flags query param v='2', got '3'. All query params: {'v': '3'}

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 70ms
Versioned Boolean Matching.Matching Version 1 ✅ 69ms
Versioned Boolean Matching.Matching Version 2 ✅ 69ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 36ms

@github-actions

Copy link
Copy Markdown
Contributor

This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, post a comment or remove the stale label – otherwise this will be closed in another week.

A v3 record for a flag in the new format carries no experiment ID: an
experiment is linked to its rule on the server, by rule ID. A complete
experiment split is config version 2, reason experiment_split, rule type
experiment, a rule ID and a variant key.

- Remove experiment_id from FlagMetadata. An experiment_id key in a record
  is now ignored like any other unknown metadata key, whatever its type.
- The vendored harness 1.13.1 fixtures still carry the field. Two reader
  cases that depend on it are overridden in the test until the fixtures are
  re-pinned to a contract without it.

@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 811c6c2: 1 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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.

Comment thread posthog/types.py
Comment on lines +563 to +564
if accepts(flag.value):
return resolved(flag.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 · Copy object values before exposing them through typed accessors

When a caller modifies the dictionary returned by get_object_value() or get_object_details(), resolved(flag.value) exposes and mutates the retained record. Subsequent reads, including reads through filtered snapshots, return the modified configuration while legacy payload getters retain the original value. Preserve the point-in-time snapshot contract by returning a deep copy of object values.

A v3 record carries no holdout ID: holdouts in the new format are local to
their rule and have no ID, and older records never sent one. A holdout
result is identified by its rule ID and the reason holdout.

- Remove holdout_id from FlagMetadata. A holdout_id key in a record is now
  ignored like any other unknown metadata key, whatever its type.
- The vendored harness 1.13.1 fixtures still send the field. No reader case
  depends on it; the producer-response test skips it, like experiment_id,
  until the fixtures are re-pinned to a contract without it.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant