Skip to content

fix(flags): honor versioned local property matching - #922

Draft
marandaneto wants to merge 5 commits into
mainfrom
fix/versioned-boolean-local-evaluation
Draft

fix(flags): honor versioned local property matching#922
marandaneto wants to merge 5 commits into
mainfrom
fix/versioned-boolean-local-evaluation

Conversation

@marandaneto

@marandaneto marandaneto commented Sep 5, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

Local feature flag evaluation needs to honor the property_matching_version supplied with flag definitions. Otherwise Python can return a different result from the service when a project uses version 2 matching.

This follows the backend behavior and shared SDK contract.

  • Exactly version 2 uses explicit scalar equality and member equality for nonempty filter arrays. Missing/1 and unsupported selectors keep legacy matching. Empty filters retain recursive truthiness. For known properties, is_not complements exact.
  • The selector travels with person, group, nested cohort, and flag dependency evaluations, including multi-flag evaluations.
  • Definition snapshots and synchronous/asynchronous definition cache providers retain the selector. Version-only refreshes invalidate evaluated results even when flags are unchanged.
  • The first result after lazy definition loading is cached for fallback during an API outage. Definition publication advances an in-memory generation without waiting for Redis I/O. Separate write locks prevent an old in-flight write from overwriting a newer result within a Client. Locks are replaced after fork, and memory writes prune invalidated flags for reused users.
  • Client-managed Redis entries now include a private deterministic fingerprint of flags, cohorts, group mapping, and matching version. Normal and stale reads reject entries from other snapshots, including late writes and entries written by another worker. Matching snapshots can reuse results across workers even when their local generation counters differ. Fingerprint serialization happens outside the publication lock for API and provider loads.
  • Every snapshot change advances the local generation, including initial hydration and cohort/group-mapping-only changes. Writes retain the identity of the evaluation that produced them rather than adopting the definitions current at write completion.

Compatibility

The optional definition-cache field and matcher arguments are additive and included in the public API snapshot. Client supports async definition providers here. The separate AsyncClient remains remote-only. The existing Sampo changeset is a patch for pypi/posthog.

Redis keys, TTLs, public cache signatures, and standalone invalidation/clear behavior are unchanged. The new entry metadata is additive and readable by older SDKs. Older or unverifiable entries become cache misses for upgraded Client-managed caches. Older SDK readers do not gain these protections.

Before definitions load, remote results can still serve outage fallback within the same Client. Their private identity is unique to that Client and renewed after fork, so new Clients and workers cannot reuse unverifiable remote-only entries. Authentication or billing resets disable Redis result caching until valid definitions load again. Remote requests use their request-start generation only as a local invalidation boundary, not as proof of the server's definition snapshot.

Redis result writes remain synchronous. This change does not add Redis timeouts or make single-result cache writes nonblocking. Old entries can remain until their existing TTL expires, but upgraded readers only accept matching provenance.

Optional harness coverage is separate. This PR does not opt an SDK adapter into that coverage.

💚 How did you test it?

Using the existing cached virtualenv with PYTHONDONTWRITEBYTECODE=1 and PYTHONPATH=.:

  • 1,036 focused pytest cases passed across versioned matching, publication concurrency, definition providers, single/full/bulk APIs, async feature flags, fork handling, Client behavior, and memory/Redis cache serialization. These runs emitted 127 deprecation warnings.
  • The independent Redis restart reproducer failed both ordinary-definition and version-only cases on ef127fd. Permanent regression tests failed 24 cases on that head and pass with the fix. They cover restart, different worker snapshots, synchronous/asynchronous providers, cohort/group-mapping-only changes, paused writes, old entries without metadata, and delayed remote responses across hydration or reset.
  • Committed-branch autoreview found a further remote-only restart case on 806f735. Three regression cases failed before replacing shared remote-only provenance with per-Client identities. Same-Client fallback, matching-definition reuse, and fork controls pass.
  • Changed-file Ruff formatting and lint checks, public API snapshot verification, warning-as-error import, and whitespace checks passed. Mypy with baseline filtering passed for 230 source files.
  • Both new commits are signed. Commit 3dbe088 passed isolated committed-branch autoreview against origin/main with no actionable findings.

Targeted mutation CI repair

The targeted job stopped before mutation testing because its CRAP gate selects only test_utils.py and test_size_limited_dict.py. Cache publication tests in other files did not cover the new snapshot paths in that selection. The CRAP calculator also counts non-executable lines, and the Redis read method's complexity of 10 could not satisfy the strict below-10 limit.

  • Added 14 selected regression cases for generation fences, reused-user pruning, snapshot serialization, cross-worker reuse, wrong or missing fingerprints, disabled snapshots, TTL boundaries, and refresh during serialization. Added assertions that standalone entries have no snapshot metadata.
  • Removed repeated conditions in three cache methods. Memory cache initialization and eviction share one new-user check. Redis reads choose snapshot or standalone validation with an if/else. Redis writes select the fingerprint once. Publication fences, write locks, Redis I/O ordering, and public signatures are unchanged.
  • On Python 3.11.11, all 100 selected tests passed with 100% executable line coverage of utils.py. The maximum CRAP score is 8.66, below the unchanged limit of 10. A fresh actual mutation run killed all 535 mutants, with empty mutmut results and no survivors, timeouts, or untested mutants.
  • All 519 focused cache, snapshot, fork, definition-provider, and versioned-matching tests passed, with 127 deprecation warnings. Repository-wide Ruff format/lint, baseline-filtered Mypy for 230 source files, the public API snapshot check, warning-as-error import, and whitespace checks passed.
  • Signed commit a5a6dfb passed isolated committed-branch autoreview against origin/main with no actionable findings. All GitHub checks for a5a6dfb8e96c4b5cb8ad4e857ab2a18da3e6209e completed successfully, with no failed, pending, or skipped checks. The CI run includes Python 3.10 through 3.14 tests. Its targeted mutation job executed mutation testing rather than skipping on a cache hit and killed all 535 mutants. Both capture protocols also passed SDK compliance.

Full repository tests and generated mirror packaging were not run locally for this repair. Redis regressions use the repository's deterministic FakeRedis, not a live Redis service.

📝 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

The existing .sampo/changesets/versioned-property-matching.md patch changeset was updated. sampo add was not rerun and no duplicate changeset was added.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Pi agents implemented and tested this user-directed SDK contract update using repository inspection, Python/pytest, Ruff, Git, GitHub CLI, and the isolated autoreview helper. Human review is required before merging. No public agent session link is available.

Fresh review found that a process-local generation could allow invalidated Redis entries to revive after restart. The repair adds private snapshot provenance without putting Redis I/O under the publication lock. The user-directed review workflow approved the additive metadata and stricter handling of unverifiable remote-only entries. Legacy matching defaults, public cache APIs, and Redis key formats are preserved.

@marandaneto marandaneto self-assigned this Sep 5, 2026
@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-05 17:47:21 UTC
Duration: 256385ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 510ms
Required Headers.Has Authorization Bearer Header 511ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 511ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 510ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 511ms
Event Format.Event Timestamp Is Rfc3339 510ms
Event Format.Distinct Id Is String 511ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 511ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 510ms
Event Format.Event Has Required Root Fields Batch 514ms
Event Format.Event Uuid Is Valid Batch 513ms
Event Format.Event Timestamp Is Rfc3339 Batch 513ms
Event Format.Distinct Id Is String Batch 513ms
Event Format.Distinct Id At Root Not Properties Batch 514ms
Event Format.Custom Properties Preserved Batch 513ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 514ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 517ms
Batch Behavior.Batch Envelope Smoke 515ms
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 518ms
Deduplication.Different Events Same Content Different Uuids 512ms
Deduplication.Preserves Uuid On Retry 6519ms
Deduplication.Preserves Timestamp On Retry 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
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 13528ms
Header Behavior On Retry.Request Id Preserved On Retry 6518ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3019ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6521ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 516ms
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 513ms
Response Format Validation.Response Echoes Request Id 511ms
Retry Behavior.Retries On 408 6519ms
Retry Behavior.Retries On 500 6516ms
Retry Behavior.Retries On 503 8523ms
Retry Behavior.Retries On 504 6516ms
Retry Behavior.Retryable Errors Have Retry After 3516ms
Retry Behavior.Respects Retry After On Retryable Error 11516ms
Retry Behavior.Does Not Retry On 400 2514ms
Retry Behavior.Does Not Retry On 401 2513ms
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 2513ms
Retry Behavior.Implements Backoff 22533ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3517ms
Partial Batch Handling.Does Not Retry Dropped Events 3513ms
Partial Batch Handling.Does Not Retry Limited Events 3517ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6520ms
Partial Batch Handling.Retries Only Retry Events From Partial 6519ms
Partial Batch Handling.Partial Retry Preserves Uuids 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6522ms
Partial Batch Handling.Partial Retry Request Id Preserved 6522ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3513ms
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 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2512ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 511ms
Event Options.Options Override In Batch 513ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 510ms
Geoip And Historical Migration.Historical Migration Set In Body 511ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 12ms
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 9ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 10ms
Request Lifecycle.No Flags Request On Init Alone 4ms
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 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

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