Repository navigation
fix(flags): don't match person_metadata filters against person properties - #1288
srednoff888-art wants to merge 4 commits into
Conversation
…ties A cohort can filter on Person metadata > First seen (type "person_metadata", key "created_at"). /flags reads that value from the persons table and ignores any created_at person property. Local evaluation treated every filter type other than cohort and flag as a person property, so a caller passing created_at got an answer based on that value, which could disagree with /flags. Only person and group filters are now matched against the properties the caller passes. Any other type is unsupported_definition: the definition check flags it when definitions load, and evaluation falls back to /flags (or stays unresolved with only_evaluate_locally). match_property itself is unchanged. Part of PostHog/posthog#137503 (posthog-python) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dustinbyrne
left a comment
There was a problem hiding this comment.
The runtime change in posthog/feature_flags.py looks minimal and matches both /flags (person_metadata reads from the persons table rather than person properties) and posthog-dotnet's allow-list approach for unsupported property filter types.
There are two test concerns inline before approval:
- The new
_is_unsupported_propertycheck (posthog/feature_flags.py:1862) has no test coverage, and the new test file only exercises the deprecatedget_feature_flagpath. TestPersonMetadataFilters._clientconstructs liveClient(..., send=True)instances withoutclient.shutdown(), leaking backgroundConsumerthreads that attempt outbound capture POSTs during longer test runs.
Outside the scope of this PR (non-blocking follow-ups): codifying the property filter type allow-list in PostHog/sdk-specs, aligning remaining peer server SDKs and the posthog.com local-evaluation restrictions docs, and evaluating separately whether sdk-specs should address multi-condition multivariate / early_exit catch-all fallthrough after an inconclusive condition.
AI-assisted review.
| return _is_unsupported_dependency(prop, flags_by_key) | ||
| if property_type != "cohort": | ||
| try: | ||
| _assert_property_filter_type_supported(prop) |
There was a problem hiding this comment.
Concern: The new _assert_property_filter_type_supported(prop) check in _is_unsupported_property has no test coverage, and all four tests in posthog/test/test_feature_flags_person_metadata.py only exercise the deprecated get_feature_flag API after assigning client.feature_flags directly.
Deleting line 1862 leaves every test in test_feature_flags_person_metadata.py (and the existing test suite) passing, yet that call governs two observable contracts from sdk-specs (evaluate-flags load-time unresolvable warnings and snapshot unresolved_flags reporting):
Client._load_feature_flags()logging a load-time(reason: unsupported_definition)warning for flags withperson_metadatafilters (direct or inside dynamic cohorts) — verified via base/head comparison (warn_count=0on merge-base84fc9e06vswarn_count=1on head41e6d3de).client.evaluate_flags(..., only_evaluate_locally=True).unresolved_flagsreportingUnresolvedFlagReason.UNSUPPORTED_DEFINITION(including taking precedence overMISSING_CONTEXTwhencreated_atis omitted fromperson_properties: merge-base reportedMISSING_CONTEXT, head reportsUNSUPPORTED_DEFINITION).
In addition, test_feature_flags_person_metadata.py does not test that cohort leaf negation: True and cohort operator: "not_in" stay unresolved rather than inverting to True (required by sdk-specs local-feature-flag-evaluator), nor does it include "group" and omitted-type negative controls alongside "person".
Consider adding tests in posthog/test/test_feature_flags_person_metadata.py (using client._load_feature_flags() and client.evaluate_flags(...)) covering those paths, for example:
definitions = {
"flags": [_flag(IN_COHORT)],
"group_type_mapping": {},
"cohorts": FIRST_SEEN_COHORT,
}
with (
mock.patch(
"posthog.client.get",
return_value=GetResponse(data=definitions, etag="e1", not_modified=False),
),
self.assertLogs("posthog", level=logging.WARNING) as logs,
):
client._load_feature_flags()
self.assertTrue(
any(
"first-seen-flag" in r.getMessage()
and "(reason: unsupported_definition)" in r.getMessage()
for r in logs.records
)
)
for props in ({"created_at": "2026-06-01"}, {}):
snapshot = client.evaluate_flags(
"user-123", person_properties=props, only_evaluate_locally=True
)
self.assertIsNone(snapshot.get_flag("first-seen-flag"))
self.assertEqual(
dict(snapshot.unresolved_flags),
{"first-seen-flag": UnresolvedFlagReason.UNSUPPORTED_DEFINITION},
)Plus cohort negation: True / operator: "not_in" cases and "group" / omitted-type negative controls.
There was a problem hiding this comment.
Added in 494a2c3: the load-time warning, unresolved_flags with and without created_at, negation and not_in, and group and untyped controls, all through _load_feature_flags() and evaluate_flags().
I also made one change you didn't ask for. Your finding on PostHog/posthog-js#5840 and PostHog/posthog-go#465 applies here too: a later condition could decide the flag. The unsupported type now raises RequiresServerEvaluation, like a static cohort. Three tests for it fail without the change. An OR cohort that another filter would satisfy now goes to /flags as well.
|
|
||
| class TestPersonMetadataFilters(unittest.TestCase): | ||
| def _client(self, properties, cohorts=None): | ||
| client = Client(FAKE_TEST_API_KEY, secret_key=FAKE_TEST_API_KEY) |
There was a problem hiding this comment.
Concern: Client(FAKE_TEST_API_KEY, secret_key=FAKE_TEST_API_KEY) leaves send=True (the default) and never calls client.shutdown(), so each test leaks a live Consumer background thread and enqueues a $feature_flag_called event (via default send_feature_flag_events=True) that attempts an unmocked outbound HTTP POST to https://us.i.posthog.com/i/v1/analytics/events once flush_interval=5.0s elapses during the pytest suite.
Observed when running TestPersonMetadataFilters in an isolated test run:
- 4 live background threads remain after the test class finishes (
Consumer:Thread-1..Consumer:Thread-4). Client.__init__emits[PostHog] Multiple active PostHog clients detected for the same project API key and host....- On drain/flush, the leaked consumers attempt capture uploads (
[PostHog] 1 event(s) not persisted by /i/v1/analytics/events: CaptureError from ConnectionError (status=0)when network is blocked, or real outbound requests tous.i.posthog.comin CI).
Consider isolating the test client and registering cleanup, matching TestUnresolvableFlagWarning._client in posthog/test/test_evaluate_flags.py:
def _client(self, properties, cohorts=None):
client = Client(
FAKE_TEST_API_KEY,
secret_key=FAKE_TEST_API_KEY,
enable_local_evaluation=False,
send=False,
)
self.addCleanup(client.shutdown)
client.feature_flags = [_flag(properties)]
client.cohorts = cohorts or {}
return clientAlso consider exercising client.evaluate_flags(...) alongside (or instead of) the deprecated get_feature_flag(...) calls so the new test file doesn't emit 4 DeprecationWarnings on every run.
There was a problem hiding this comment.
Fixed in 494a2c3: send=False, enable_local_evaluation=False, shutdown in cleanup, and evaluate_flags instead of the deprecated calls.
The error let later conditions decide the flag. Only /flags knows the value, so treat it like a static cohort. Also cover the load-time warning, evaluate_flags and negation, with a client that sends nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for updating the tests and fixing the test client cleanup — both concerns from the earlier review (_load_feature_flags() / evaluate_flags() / unresolved_flags / negation & negative-control coverage, and send=False + client.shutdown()) are addressed cleanly.
One Breaking regression remains inline on posthog/feature_flags.py before approval: switching _assert_property_filter_type_supported to raise RequiresServerEvaluation breaks three-valued AND/OR short-circuiting in match_property_group for dynamic cohorts that combine person_metadata with another filter (affecting both AND — including not_in — and OR cohorts, regressing merge-base behavior when created_at is omitted, and diverging from sdk-specs).
Optional Suggestion (non-blocking, outside the current diff): consider adding "an unsupported filter type" to the example list in the load-time unsupported_definition warning (posthog/client.py:4280-4288) and UnresolvedFlagReason.UNSUPPORTED_DEFINITION docstring (posthog/types.py:130-133) so operators seeing the warning for a dynamic cohort with a First seen filter can diagnose it directly.
(Outside this PR's scope as non-blocking follow-ups: pre-existing filter-order handling in _match_condition_properties at posthog/feature_flags.py:928 matches test_static_cohort_after_unchecked_filter_lets_later_conditions_resolve and peer SDKs; documenting person_metadata restrictions in PostHog/posthog.com and codifying unsupported filter types in PostHog/sdk-specs.)
AI-assisted review.
| def _assert_property_filter_type_supported(prop) -> None: | ||
| property_type = prop.get("type") | ||
| if property_type and property_type not in _PROPERTY_FILTER_TYPES: | ||
| raise RequiresServerEvaluation( |
There was a problem hiding this comment.
Breaking: Raising RequiresServerEvaluation here breaks three-valued AND and OR short-circuiting in match_property_group (posthog/feature_flags.py:1738-1769) for dynamic cohorts that combine person_metadata with a decisive sibling filter.
Why this matters (trigger → actual → expected):
- Trigger: A flag targets a dynamic cohort mixing
person_metadata("First seen") with an ordinary person property filter — e.g.AND(plan == "paid", created_at > 2025-01-01)evaluated for{"plan": "free"}(includingnot_in), orOR(plan == "paid", created_at > 2025-01-01)evaluated for{"plan": "paid"}— in either filter order, with or withoutcreated_atsupplied. - Actual (head
494a2c3f):match_property_groupcatchesRequiresServerEvaluationat lines 1752–1755 and immediately re-raises, discardingdecisive_resulteven when the decisive sibling ran first. Underonly_evaluate_locally=True,evaluate_flagsreturnsNone(unresolved_flags = {'first-seen-flag': UnresolvedFlagReason.UNSUPPORTED_DEFINITION}) instead ofFalse/True(flippingis_enabled(...)fromTruetoFalseforORandnot_inANDcohorts). With remote fallback enabled, every user already decisively excluded from anANDcohort or decisively included in anORcohort now forces a billable/flagsrequest. - Expected (merge base
84fc9e06,sdk-specs, and/flags): The cohort resolves locally toFalse(AND),True(not_inonAND), orTrue(OR) withunresolved_flags == {}and 0/flagscalls, while still blocking later flag conditions whenever the cohort itself is undecided (ANDwithplan="paid"orORwithplan="free").
Contract and base/head evidence:
- Governing contracts:
PostHog/sdk-specs(openspec/specs/local-feature-flag-evaluator/spec.md,44fe27ab, lines 1096 and 1127–1139) normatively specifies three-valued composition for dynamic cohort groups (AND(false, inconclusive) -> false,OR(true, inconclusive) -> true), matching/flags(rust/feature-flags/src/cohorts/cohort_operations.rs:333-366). It also matches this PR's own condition-level guarantee intest_another_filter_still_rules_the_condition_out, whereasperson_metadataprimarily arrives inside dynamic cohorts (products/feature_flags/backend/api/filters_schema.py:63-66). - Executed base-vs-head verification (isolated sandbox, Python 3.11.13, pytest 8.4.1, running the regression test below via
Client.evaluate_flags(..., only_evaluate_locally=True)):- Merge base
84fc9e06: 9/9 PASSED (AND,AND + not_in, andORin both filter orders resolved locally toFalse/Truewithunresolved_flags == {}and 0/flagscalls). - PR head
494a2c3f: 0/9 PASSED (9/9 FAILED) withAssertionError: None is not False/True : unresolved={'first-seen-flag': <UnresolvedFlagReason.UNSUPPORTED_DEFINITION: 'unsupported_definition'>}. - Undecided-cohort control (
ANDwithplan="paid",ORwithplan="free"): 0/2 on base → 2/2 PASSED on head ("new-user", 1/flagscall).
- Merge base
Recommendation:
Consider preserving eager RequiresServerEvaluation propagation in match_property_group for missing/static nested cohorts and malformed group structures (keeping test_missing_nested_cohort_always_requires_server_evaluation and test_only_canonical_empty_groups_match passing), while deferring a leaf-level unsupported-filter RequiresServerEvaluation behind decisive_result in match_property_group and re-raising it when decisive_result is None (preserving deferral across nested property groups, without changing RequiresServerEvaluation's public signature or class identity).
Consider adding regression tests covering decisive AND / AND + not_in / OR cohort siblings alongside undecided-cohort multi-condition fallback:
@parameterized.expand(
[
("and_plan_first_no_created_at", "AND", [PLAN_PAID, FIRST_SEEN_FILTER], IN_COHORT, {"plan": "free"}, False),
("and_first_seen_first_no_created_at", "AND", [FIRST_SEEN_FILTER, PLAN_PAID], IN_COHORT, {"plan": "free"}, False),
("and_not_in_no_created_at", "AND", [PLAN_PAID, FIRST_SEEN_FILTER], NOT_IN_COHORT, {"plan": "free"}, True),
("and_plan_first_with_created_at", "AND", [PLAN_PAID, FIRST_SEEN_FILTER], IN_COHORT, {"plan": "free", **CREATED_IN_2026}, False),
("and_first_seen_first_with_created_at", "AND", [FIRST_SEEN_FILTER, PLAN_PAID], IN_COHORT, {"plan": "free", **CREATED_IN_2026}, False),
("or_plan_first_no_created_at", "OR", [PLAN_PAID, FIRST_SEEN_FILTER], IN_COHORT, {"plan": "paid"}, True),
("or_first_seen_first_no_created_at", "OR", [FIRST_SEEN_FILTER, PLAN_PAID], IN_COHORT, {"plan": "paid"}, True),
("or_plan_first_with_created_at", "OR", [PLAN_PAID, FIRST_SEEN_FILTER], IN_COHORT, {"plan": "paid", **CREATED_IN_2026}, True),
("or_first_seen_first_with_created_at", "OR", [FIRST_SEEN_FILTER, PLAN_PAID], IN_COHORT, {"plan": "paid", **CREATED_IN_2026}, True),
]
)
@mock.patch("posthog.client.flags")
def test_decisive_cohort_sibling_resolves_locally(
self, _, group_type, values, flag_props, person_properties, expected, patch_flags
):
client = self._client(
[_flag(_condition(flag_props))],
cohorts={"7": {"type": group_type, "values": values}},
)
snapshot = client.evaluate_flags(
"user-123",
person_properties=person_properties,
only_evaluate_locally=True,
)
self.assertIs(snapshot.get_flag("first-seen-flag"), expected)
self.assertEqual(dict(snapshot.unresolved_flags), {})
self.assertEqual(patch_flags.call_count, 0)
@parameterized.expand(
[
("and_undecided", "AND", {"plan": "paid"}),
("or_undecided", "OR", {"plan": "free"}),
]
)
@mock.patch("posthog.client.flags")
def test_undecided_cohort_still_blocks_later_condition(
self, _, group_type, person_properties, patch_flags
):
patch_flags.return_value = {"featureFlags": {"target": "new-user"}}
flag = _flag(
_condition(IN_COHORT, variant="new-user"),
_condition([], variant="existing-user"),
key="target",
multivariate=VARIANTS,
)
client = self._client(
[flag],
cohorts={"7": {"type": group_type, "values": [PLAN_PAID, FIRST_SEEN_FILTER]}},
)
snapshot = client.evaluate_flags(
"user-123", person_properties=person_properties, flag_keys=["target"]
)
self.assertEqual(snapshot.get_flag("target"), "new-user")
self.assertEqual(patch_flags.call_count, 1)There was a problem hiding this comment.
Confirmed, that was my regression. Fixed in 07ee9f6, along the lines you suggested.
A private subclass, _RequiresServerFilter, marks a single filter that only the server can check. match_property_group defers it behind a decisive sibling and re-raises it when the cohort stays undecided. Missing cohorts and malformed groups still raise at once. A flag dependency keeps the type of the error that stopped it, so a dependency inside a cohort gets the same treatment.
Tests cover AND, OR and not_in on both, in either order, with the filter nested or behind a dependency, with and without created_at, and the undecided cohort. I reverted each part of the change in turn, and each time some of them fail. I also ran your AND case end to end against a local HTTP server.
The warning and the docstring now mention the filter type.
A cohort stopped at the first filter that only the server can check, even when another filter had already decided it. Raise the error only when the cohort stays undecided. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for the fast follow-up in 07ee9f6 — the _RequiresServerFilter deferral cleanly resolves the dynamic-cohort three-valued AND/OR regression (all 9 decisive-sibling regression cases now pass on 07ee9f6, alongside all 21 new tests and 1530 flag tests), and the warning/docstring updates look great.
One narrow Concern remains inline on posthog/feature_flags.py before approval: deferring _RequiresServerFilter in match_property_group drops higher-precedence UnresolvedFlagReason values (UNSUPPORTED_DEFINITION lost to UNRESOLVED_DEPENDENCY), with the same precedence drop amplified at _raise_condition_errors:960-961 and _match_flag_conditions:633-641. There is also one optional Suggestion inline on posthog/test/test_feature_flags_person_metadata.py.
(Outside this PR's scope as non-blocking follow-ups: documenting person_metadata / unsupported filter types in PostHog/posthog.com's local-evaluation restrictions, codifying them in PostHog/sdk-specs, and aligning peer server SDKs under PostHog/posthog#137503.)
AI-assisted review.
| if effective_match != is_and: | ||
| decisive_result = effective_match | ||
| except _RequiresServerFilter as e: | ||
| server_filter_error = server_filter_error or e |
There was a problem hiding this comment.
Concern: match_property_group drops higher-precedence UnresolvedFlagReason values when deferring _RequiresServerFilter (and the same reason drop is amplified at companion sites _raise_condition_errors:960-961 and _match_flag_conditions:633-641).
Contract & evidence: PostHog/sdk-specs (openspec/specs/evaluate-flags/spec.md, Snapshot unresolved flag reporting) requires (SHALL) reporting reasons in precedence order: experience_continuity > unsupported_definition > unresolved_dependency > missing_context, matching posthog-go (featureflags.go:1762-1766, 1910-1912) and posthog-dotnet (LocalEvaluator.cs:445-450, 603-606). Because server_filter_error = server_filter_error or e keeps only the first _RequiresServerFilter and raise server_filter_error ignores inconclusive_reason, an earlier _RequiresServerFilter(UNRESOLVED_DEPENDENCY) (from _evaluate_dependency at line 471) shadows a sibling InconclusiveMatchError(UNSUPPORTED_DEFINITION) or later _RequiresServerFilter(UNSUPPORTED_DEFINITION).
Minimal trigger & actual vs. expected (verified via base 84fc9e06 vs. head 07ee9f6c execution):
Static UNSUPPORTED_DEFINITION causes are recovered on Client.evaluate_flags by _enrich_server_evaluation_reason, so flag values and /flags fallback are unaffected. However, for runtime-only UNSUPPORTED_DEFINITION filters (such as regex deferral in _assert_regex_value_supported — e.g. r"\w+" on a non-ASCII string with punctuation/emoji or r"foo.*$" on "foo\n"):
- Cohort
AND([DEPENDS_ON_FIRST_SEEN, {"key": "name", "type": "person", "operator": "regex", "value": "foo.*$"}])evaluated viaclient.evaluate_flags("user-123", person_properties={"name": "foo\n"}, flag_keys=["target"], only_evaluate_locally=True):- Merge base
84fc9e06:snapshot.unresolved_flags == {"target": UnresolvedFlagReason.UNSUPPORTED_DEFINITION}(pass) - Head
07ee9f6c:snapshot.unresolved_flags == {"target": UnresolvedFlagReason.UNRESOLVED_DEPENDENCY}(fail)
- Merge base
- Same regression occurs when those two filters share a condition (
_raise_condition_errors:960-961) or span two conditions (_match_flag_conditions:633-641), and directmatch_property_groupcalls on[DEPENDS_ON_FIRST_SEEN, FIRST_SEEN_FILTER]become order-dependent (UNRESOLVED_DEPENDENCYvsUNSUPPORTED_DEFINITION).
Impact: Narrow diagnostic-only regression on snapshot.unresolved_flags (misattributes an unsupported_definition flag to unresolved_dependency); evaluated flag values and remote /flags fallback are unaffected.
Recommendation: Consider merging e.reason into inconclusive_reason via _pick_unresolved_reason and applying it before raising server_filter_error:
except _RequiresServerFilter as e:
server_filter_error = server_filter_error or e
inconclusive_reason = _pick_unresolved_reason(inconclusive_reason, e.reason)
except RequiresServerEvaluation as e:
if inconclusive_reason is not None:
e.reason = _pick_unresolved_reason(inconclusive_reason, e.reason)
raiseand before raising:
if server_filter_error is not None:
if inconclusive_reason is not None:
server_filter_error.reason = inconclusive_reason
raise server_filter_errorDoing the same _pick_unresolved_reason merge in _raise_condition_errors:960-961 and _match_flag_conditions:633-641 closes the amplified condition-level and multi-condition paths as well.
Consider adding a regression test locking in UNSUPPORTED_DEFINITION precedence over UNRESOLVED_DEPENDENCY:
def test_precedence_preserves_unsupported_definition_over_unresolved_dependency(self):
runtime_deferred_regex = {
"key": "name",
"type": "person",
"operator": "regex",
"value": "foo.*$",
}
dependency = _flag(_condition([FIRST_SEEN_FILTER]), key="dependency")
for cohort_filters in (
(DEPENDS_ON_FIRST_SEEN, runtime_deferred_regex),
(runtime_deferred_regex, DEPENDS_ON_FIRST_SEEN),
):
client = self._client(
[_flag(_condition(IN_COHORT), key="target"), dependency],
_cohort(*cohort_filters, group_type="AND"),
)
snapshot = client.evaluate_flags(
"user-123",
person_properties={"name": "foo\n"},
flag_keys=["target"],
only_evaluate_locally=True,
)
self.assertEqual(
dict(snapshot.unresolved_flags),
{"target": UnresolvedFlagReason.UNSUPPORTED_DEFINITION},
)
for target in (
_flag(_condition([DEPENDS_ON_FIRST_SEEN, runtime_deferred_regex]), key="target"),
_flag(
_condition([runtime_deferred_regex]),
_condition([DEPENDS_ON_FIRST_SEEN]),
key="target",
),
):
client = self._client([target, dependency], cohorts={})
snapshot = client.evaluate_flags(
"user-123",
person_properties={"name": "foo\n"},
flag_keys=["target"],
only_evaluate_locally=True,
)
self.assertEqual(
dict(snapshot.unresolved_flags),
{"target": UnresolvedFlagReason.UNSUPPORTED_DEFINITION},
)There was a problem hiding this comment.
Confirmed, fixed in 19000d3. The reasons are merged in match_property_group (for a _RequiresServerFilter and for an error that ends the group at once), in _raise_condition_errors and in _match_flag_conditions.
Your four evaluate_flags cases are in, plus direct match_property_group calls in both filter orders and one for a group that ends early. Removing any of the five merges makes a test fail.
| ] | ||
| ) | ||
| @mock.patch("posthog.client.flags") | ||
| def test_another_filter_still_decides_the_cohort( |
There was a problem hiding this comment.
Suggestion: The 3-valued cohort tests here already cover AND/OR, not_in, filter order, nested groups, and flag dependencies nicely. Consider also adding:
only_evaluate_locally=Trueassertions on decisive vs. undecided mixed cohorts (confirmingunresolved_flagsis empty when a sibling decides the cohort andUNSUPPORTED_DEFINITIONwhen undecided, including withNOT_IN_COHORT).- One case with a non-
person_metadataunsupported filter type (e.g."type": "behavioral") to exercise the("person", "group")allowlist directly. - A nested cohort-ID reference (
cohort 7 -> cohort 8) with a decisive sibling.
There was a problem hiding this comment.
All three added in 19000d3: only_evaluate_locally=True for decided and undecided cohorts, with not_in and an empty unresolved_flags; a behavioral filter; and a cohort that references another cohort.
…lter An error that only the server can resolve kept its own reason, so a flag with a runtime unsupported_definition filter could be reported as unresolved_dependency. The reasons are now merged in the cohort group, in the condition and across conditions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
|
lemme confirm PostHog/sdk-specs#251 before merging |
💡 Motivation and Context
Part of PostHog/posthog#137503, for posthog-python, where the issue was reproduced.
A cohort can filter on Person metadata > First seen:
{"type": "person_metadata", "key": "created_at", ...}./flagsreads that value from the persons table and ignores anycreated_atperson property. Local evaluation treated every filter type other thancohortandflagas a person property, so:person_properties={}was inconclusive and fell back to/flags(correct);person_properties={"created_at": "2026-06-01"}returned a local answer from that value, which can disagree with/flagsfor teams that set their owncreated_atperson property.Following the fix the issue suggests (and what posthog-dotnet already does), a filter type that local evaluation can't evaluate is unsupported:
_match_condition_filternow matches onlypersonandgroupfilters (or one without atype) against the caller's properties.cohortandflagfilters keep their own matching. Any other type raises_RequiresServerFilter, a privateRequiresServerEvaluationwithunsupported_definition, so a later condition can't decide the flag. This covers flag conditions and cohort criteria, which both go through it.match_property_groupholds that error back while another filter can still decide the cohort (ANDwith a mismatch,ORwith a match), as the spec's three-valued composition requires, and raises it when the cohort stays undecided. Missing cohorts and malformed groups still raise at once._is_unsupported_propertyapplies the same rule, so the definition check marks such a flagunsupported_definitionwhen definitions load.UNSUPPORTED_DEFINITIONdocstring mention filter types.match_propertyis unchanged.The same change for posthog-node is PostHog/posthog-js#5840.
💚 How did you test it?
New
posthog/test/test_feature_flags_person_metadata.py, throughClient.evaluate_flags:person_metadatafilter in a cohort, caller passescreated_at/flagsand returns its answerperson_metadatafilter directly in a flag condition/flagsonly_evaluate_locally=True, with and withoutcreated_at, and with negation ornot_inunsupported_definition, no/flagscallunsupported_definitionwarningearly_exitexclusion, or a dependent flag/flagsFalselocallyANDorORcohort, also withnot_in, in either order, with the filter nested, in another cohort or behind a flag dependency/flagscall/flagspersonor untyped filter oncreated_at, or agroupfilterReverting any one part of the change (the error type, the deferral, the dependency's error type, the definition check) makes some of these fail.
posthog/testtree with thetestextra, on Windows: 8938 passed, 41 skipped, 16 failed. 14 of them fail on the base commit too:forkhooks, path separators, and a digest of vendored fixtures. The other two are timing-dependent here: one also fails without this commit, the other passes when run alone.Posthogclient against a local HTTP server that serves the definitions and/flags, with anANDcohort of a plan filter and First seen. It answers locally for a person the plan rules out, and makes exactly one/flagsrequest otherwise.ruff format --checkis clean.ruff checkreports nothing in the new test file and nothing new infeature_flags.py.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
19000d3.person,group) instead of special-casingperson_metadata, so a filter type added on the server later also falls back instead of being matched as a person property.🤖 Generated with Claude Code