Skip to content

fix(flags): don't match person_metadata filters against person properties - #1288

Open
srednoff888-art wants to merge 4 commits into
PostHog:mainfrom
srednoff888-art:fix/person-metadata-filters
Open

srednoff888-art wants to merge 4 commits into
PostHog:mainfrom
srednoff888-art:fix/person-metadata-filters

Conversation

@srednoff888-art

@srednoff888-art srednoff888-art commented Nov 21, 2026 •

Copy link
Copy Markdown

💡 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", ...}. /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:

  • 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 /flags for teams that set their own created_at person 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_filter now matches only person and group filters (or one without a type) against the caller's properties. cohort and flag filters keep their own matching. Any other type raises _RequiresServerFilter, a private RequiresServerEvaluation with unsupported_definition, so a later condition can't decide the flag. This covers flag conditions and cohort criteria, which both go through it.
  • match_property_group holds that error back while another filter can still decide the cohort (AND with a mismatch, OR with 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_property applies the same rule, so the definition check marks such a flag unsupported_definition when definitions load.
  • The load-time warning and the UNSUPPORTED_DEFINITION docstring mention filter types.
  • The public match_property is 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, through Client.evaluate_flags:

Case Expected
person_metadata filter in a cohort, caller passes created_at falls back to /flags and returns its answer
person_metadata filter directly in a flag condition falls back to /flags
only_evaluate_locally=True, with and without created_at, and with negation or not_in unresolved, unsupported_definition, no /flags call
loading the definitions logs the unsupported_definition warning
a later condition with another variant, an early_exit exclusion, or a dependent flag falls back to /flags
another filter in the condition that does not match False locally
another filter that decides an AND or OR cohort, also with not_in, in either order, with the filter nested, in another cohort or behind a flag dependency decided locally, no /flags call
a cohort that stays undecided, with a later condition falls back to /flags
several causes in one cohort, one condition or several conditions the highest-precedence reason
a person or untyped filter on created_at, or a group filter still evaluated locally

Reverting any one part of the change (the error type, the deferral, the dependency's error type, the definition check) makes some of these fail.

  • The whole posthog/test tree with the test extra, on Windows: 8938 passed, 41 skipped, 16 failed. 14 of them fail on the base commit too: fork hooks, 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.
  • End to end: a Posthog client against a local HTTP server that serves the definitions and /flags, with an AND cohort of a plan filter and First seen. It answers locally for a person the plan rules out, and makes exactly one /flags request otherwise.
  • ruff format --check is clean. ruff check reports nothing in the new test file and nothing new in feature_flags.py.

📝 Checklist

  • All commits are signed (see Commit signing)
  • 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. The account owner asked for fixes to open PostHog SDK issues, and the agent picked this one. The owner has reviewed the full diff at 19000d3.
  • I used an allow-list (person, group) instead of special-casing person_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

…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 dustinbyrne 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.

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:

  1. The new _is_unsupported_property check (posthog/feature_flags.py:1862) has no test coverage, and the new test file only exercises the deprecated get_feature_flag path.
  2. TestPersonMetadataFilters._client constructs live Client(..., send=True) instances without client.shutdown(), leaking background Consumer threads 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.

Comment thread posthog/feature_flags.py
return _is_unsupported_dependency(prop, flags_by_key)
if property_type != "cohort":
try:
_assert_property_filter_type_supported(prop)

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.

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):

  1. Client._load_feature_flags() logging a load-time (reason: unsupported_definition) warning for flags with person_metadata filters (direct or inside dynamic cohorts) — verified via base/head comparison (warn_count=0 on merge-base 84fc9e06 vs warn_count=1 on head 41e6d3de).
  2. client.evaluate_flags(..., only_evaluate_locally=True).unresolved_flags reporting UnresolvedFlagReason.UNSUPPORTED_DEFINITION (including taking precedence over MISSING_CONTEXT when created_at is omitted from person_properties: merge-base reported MISSING_CONTEXT, head reports UNSUPPORTED_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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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)

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.

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 to us.i.posthog.com in 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 client

Also 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 494a2c3: send=False, enable_local_evaluation=False, shutdown in cleanup, and evaluate_flags instead of the deprecated calls.

@dustinbyrne
dustinbyrne requested a review from a team November 23, 2026 21:43
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 dustinbyrne 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.

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.

Comment thread posthog/feature_flags.py Outdated
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(

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.

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"} (including not_in), or OR(plan == "paid", created_at > 2025-01-01) evaluated for {"plan": "paid"} — in either filter order, with or without created_at supplied.
  • Actual (head 494a2c3f): match_property_group catches RequiresServerEvaluation at lines 1752–1755 and immediately re-raises, discarding decisive_result even when the decisive sibling ran first. Under only_evaluate_locally=True, evaluate_flags returns None (unresolved_flags = {'first-seen-flag': UnresolvedFlagReason.UNSUPPORTED_DEFINITION}) instead of False/True (flipping is_enabled(...) from True to False for OR and not_in AND cohorts). With remote fallback enabled, every user already decisively excluded from an AND cohort or decisively included in an OR cohort now forces a billable /flags request.
  • Expected (merge base 84fc9e06, sdk-specs, and /flags): The cohort resolves locally to False (AND), True (not_in on AND), or True (OR) with unresolved_flags == {} and 0 /flags calls, while still blocking later flag conditions whenever the cohort itself is undecided (AND with plan="paid" or OR with plan="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 in test_another_filter_still_rules_the_condition_out, whereas person_metadata primarily 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, and OR in both filter orders resolved locally to False/True with unresolved_flags == {} and 0 /flags calls).
    • PR head 494a2c3f: 0/9 PASSED (9/9 FAILED) with AssertionError: None is not False/True : unresolved={'first-seen-flag': <UnresolvedFlagReason.UNSUPPORTED_DEFINITION: 'unsupported_definition'>}.
    • Undecided-cohort control (AND with plan="paid", OR with plan="free"): 0/2 on base → 2/2 PASSED on head ("new-user", 1 /flags call).

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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

@dustinbyrne
dustinbyrne requested a review from a team November 24, 2026 20:20
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 dustinbyrne 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.

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.

Comment thread posthog/feature_flags.py
if effective_match != is_and:
decisive_result = effective_match
except _RequiresServerFilter as e:
server_filter_error = server_filter_error or e

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.

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 via client.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)
  • 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 direct match_property_group calls on [DEPENDS_ON_FIRST_SEEN, FIRST_SEEN_FILTER] become order-dependent (UNRESOLVED_DEPENDENCY vs UNSUPPORTED_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)
            raise

and before raising:

    if server_filter_error is not None:
        if inconclusive_reason is not None:
            server_filter_error.reason = inconclusive_reason
        raise server_filter_error

Doing 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},
        )

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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(

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.

Suggestion: The 3-valued cohort tests here already cover AND/OR, not_in, filter order, nested groups, and flag dependencies nicely. Consider also adding:

  1. only_evaluate_locally=True assertions on decisive vs. undecided mixed cohorts (confirming unresolved_flags is empty when a sibling decides the cohort and UNSUPPORTED_DEFINITION when undecided, including with NOT_IN_COHORT).
  2. One case with a non-person_metadata unsupported filter type (e.g. "type": "behavioral") to exercise the ("person", "group") allowlist directly.
  3. A nested cohort-ID reference (cohort 7 -> cohort 8) with a decisive sibling.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

@dustinbyrne
dustinbyrne requested a review from a team November 24, 2026 21:34
…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>
@github-actions

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks 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
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 133.67 KiB/op 133.67 KiB/op No observed change Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,345.51 count/op 1,345.51 count/op No observed change Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 76.32 µs/op 76.41 µs/op 0.1% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 37.66 MiB 37.61 MiB 0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 40.11 MiB 40.06 MiB 0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 40.11 MiB 40.06 MiB 0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 80.42 µs/op 80.32 µs/op 0.1% less time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.36 MiB 40.36 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 185.75 KiB/op 185.75 KiB/op <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,337.51 count/op 1,337.51 count/op <0.1% more Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 99.58 µs/op 99.33 µs/op 0.3% less time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 41.21 MiB 41.24 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 47 MiB 47.02 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 47 MiB 47.02 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 97.47 µs/op 97.21 µs/op 0.3% less time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 51.43 MiB 51.46 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 138.73 KiB/op 138.73 KiB/op <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,390.29 count/op 1,390.3 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 88.28 µs/op 88.34 µs/op <0.1% more time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 37.52 MiB 37.62 MiB 0.3% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 37.69 MiB 37.78 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 37.69 MiB 37.78 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 90.35 µs/op 90.07 µs/op 0.3% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.36 MiB 40.36 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 190.9 KiB/op 190.9 KiB/op No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,382.19 count/op 1,382.19 count/op No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 105.47 µs/op 104.43 µs/op 1% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 41.07 MiB 41.12 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 41.53 MiB 41.57 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 41.13 MiB 41.17 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 102.65 µs/op 100.92 µs/op 1.7% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 41.49 MiB 41.5 MiB <0.1% more memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 56.99 µs/op 56.77 µs/op 0.4% less time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 57.15 µs/op 56.77 µs/op 0.7% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 56.87 µs/op 57.03 µs/op 0.3% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 56.97 µs/op 57.03 µs/op <0.1% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 225.43 KiB/op 234.05 KiB/op 3.8% more memory Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,279.42 count/op 2,352.93 count/op 3.2% more Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 137.84 µs/op 141.69 µs/op 2.8% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 137.83 µs/op 141.68 µs/op 2.8% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 2.17 MiB/op 2.25 MiB/op 3.9% more memory Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 22,413.69 count/op 23,148.75 count/op 3.3% more Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 1.3 ms/op 1.33 ms/op 2% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 1.3 ms/op 1.33 ms/op 2% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 21.63 MiB/op 22.47 MiB/op 3.9% more memory Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 223,655.44 count/op 231,005.5 count/op 3.3% more Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 12.73 ms/op 12.95 ms/op 1.7% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 12.73 ms/op 12.95 ms/op 1.7% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 43.87 MiB 43.81 MiB 0.2% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 44.18 MiB 44.15 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 44.18 MiB 44.15 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 43.92 MiB 43.9 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 42.98 MiB 42.98 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.99 MiB 42.99 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.99 MiB 42.99 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.77 MiB 43.28 MiB 1.2% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.74 KiB/op 15.74 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 162.77 count/op 162.77 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 7.22 µs/op 7.18 µs/op 0.5% less time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 7.22 µs/op 7.18 µs/op 0.5% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 24.6 KiB/op 25.31 KiB/op 2.9% more memory Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 239.28 count/op 245.28 count/op 2.5% more Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 9.63 µs/op 9.91 µs/op 3% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 9.63 µs/op 9.91 µs/op 3% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 39.81 KiB/op 41.4 KiB/op 4% more memory Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 388.27 count/op 401.77 count/op 3.5% more Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 13.93 µs/op 13.99 µs/op 0.5% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 13.93 µs/op 14 µs/op 0.5% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 60.59 KiB/op 63.4 KiB/op 4.6% more memory Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 584.27 count/op 608.27 count/op 4.1% more Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 19.78 µs/op 20.15 µs/op 1.9% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 19.78 µs/op 20.15 µs/op 1.9% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 59.22 KiB/op 62.03 KiB/op 4.7% more memory Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 567.77 count/op 591.77 count/op 4.2% more Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 18.46 µs/op 19.14 µs/op 3.7% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 18.46 µs/op 19.14 µs/op 3.7% more time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 19.04 KiB/op 19.39 KiB/op 1.8% more memory Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 192.27 count/op 195.27 count/op 1.6% more Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 7.8 µs/op 8.12 µs/op 4.2% more time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 7.8 µs/op 8.12 µs/op 4.2% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 20.66 KiB/op 21.02 KiB/op 1.7% more memory Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 197.77 count/op 200.77 count/op 1.5% more Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 8.63 µs/op 8.76 µs/op 1.5% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 8.63 µs/op 8.76 µs/op 1.5% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.89 KiB/op 14.89 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 152.77 count/op 152.77 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 6.45 µs/op 6.54 µs/op 1.4% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 6.45 µs/op 6.54 µs/op 1.4% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.9 KiB/op 15.9 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 166.77 count/op 166.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 7.34 µs/op 7.3 µs/op 0.6% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 7.34 µs/op 7.3 µs/op 0.6% less time Not flagged

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 84fc9e06bd898fe090e7443138e32010b9aa91db → 19000d370fbf104568f45ee163aa1fe1bbd33820.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

@marandaneto

Copy link
Copy Markdown
Member

lemme confirm PostHog/sdk-specs#251 before merging

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.

3 participants