Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(feature-flags): add test_evaluation endpoint (#55149)

Gustavo H. Strassburger7127cbee97ec
diff --git a/playwright/snapshots.yml b/playwright/snapshots.yml
index d36d93bf1902..d01ae6845a63 100644
--- a/playwright/snapshots.yml
+++ b/playwright/snapshots.yml
@@ -7,6 +7,6 @@ snapshots:
tabs-after-close-frozen-chromium-linux:
hash: v1.k794b7964.2fca90256612fb00cd9acfae8212369d7d5c55c79934d67bf585fcde88544dba.ACLl0M4x2-BDmhIal2C0rYq943n8Iw0K2RurdONJC3U
tabs-after-mouse-leave-chromium-linux:
- hash: v1.k794b7964.2d65fc8d2ae1d11dbe893408f84286d6b055981a98c2cf8fae6730615c5db543.OrtKPeft24KO45UT-N9tVWWSBpeW8_aV3tcb_zK6SgM
+ hash: v1.k794b7964.6460c310ea022cab5db9c9e83f7a0d6befc8124219d66119740132021bd41b66.TgtCEZ70Ouqrrn29tWCZwARG38NRUwBMaxNeiqjvkWw
tabs-before-close-chromium-linux:
hash: v1.k794b7964.390a720db821713b68967fce0e58c0353a8a8b75ffc06f0fc96365231e465765.q5cxWDQCSymsGK8OwJBx9_yVMQOnD_-2XreBkTtaaqM
diff --git a/posthog/api/feature_flag.py b/posthog/api/feature_flag.py
index 258483cdfc8a..e2ef3684dc63 100644
--- a/posthog/api/feature_flag.py
+++ b/posthog/api/feature_flag.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
import re
import copy
import json
@@ -7,7 +8,7 @@ import math
import time
import logging
import functools
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any, Optional, cast
from django.conf import settings
@@ -35,7 +36,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.services.flags_service import get_flags_from_service
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
-from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action
+from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action
from posthog.approvals.decorators import approval_gate
from posthog.approvals.mixins import ApprovalHandlingMixin
from posthog.auth import (
@@ -45,6 +46,7 @@ from posthog.auth import (
ProjectSecretAPIKeyAuthentication,
SessionAuthentication,
)
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.constants import PRODUCT_TOUR_TARGETING_FLAG_PREFIX, SURVEY_TARGETING_FLAG_PREFIX, FlagRequestType
from posthog.date_util import thirty_days_ago
from posthog.event_usage import report_user_action
@@ -81,13 +83,18 @@ from posthog.models.feature_flag.types import PropertyFilterType
from posthog.models.feature_flag.version_history import (
VersionHistoryIncomplete,
VersionNotFound,
+ reconstruct_flag_at_timestamp,
reconstruct_flag_at_version,
)
+from posthog.models.person.point_in_time_properties import (
+ build_person_properties_at_time,
+ get_person_and_distinct_ids_for_identifier,
+)
from posthog.models.property import Property
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.permissions import ProjectSecretAPITokenPermission
from posthog.queries.base import determine_parsed_date_for_property_matching
-from posthog.rate_limit import BurstRateThrottle
+from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.settings.feature_flags import LOCAL_EVAL_RATE_LIMITS, REMOTE_CONFIG_RATE_LIMITS
@@ -105,6 +112,19 @@ BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"
REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"
MIXED_TARGETING_FLAG = "feature-flag-mixed-targeting"
+# Fields that Rust's FeatureFlag struct expects for historical evaluation
+RUST_FLAG_FIELDS = (
+ "name",
+ "active",
+ "deleted",
+ "version",
+ "filters",
+ "bucketing_identifier",
+ "evaluation_runtime",
+ "ensure_experience_continuity",
+ "evaluation_tags",
+)
+
def _is_realtime_cohort_flag_targeting_enabled(request) -> bool:
"""Check whether the realtime cohort flag targeting feature is enabled for this request."""
@@ -360,6 +380,37 @@ def calculate_filter_size_bytes(filters: dict | None) -> int:
return len(filter_json.encode("utf-8"))
+def _filter_person_properties_for_flag(filters: dict[str, Any], person_properties: dict[str, Any]) -> dict[str, Any]:
+ """
+ Filter person_properties to only include keys referenced by the given flag filters.
+
+ For historical (timestamp-based) evaluations the caller must pass the
+ *reconstructed* filters, not the live record's filters — otherwise the
+ response can leak property values that weren't relevant at the requested
+ point in time.
+
+ Walks ``groups`` (regular release conditions), ``super_groups`` (early-access
+ gating), and ``multivariate.override_property_values`` (per-variant property
+ overrides). Cohort-typed conditions reference person properties indirectly
+ via the cohort definition; this helper does not resolve cohorts, so a flag
+ whose only conditions are cohort lookups returns an empty person_properties
+ block.
+ """
+ referenced_keys: set[str] = set()
+
+ for section in ("groups", "super_groups"):
+ for group in filters.get(section, []) or []:
+ for prop in group.get("properties", []) or []:
+ if prop.get("type") == "person" and prop.get("key"):
+ referenced_keys.add(prop["key"])
+
+ for override in (filters.get("multivariate", {}) or {}).get("override_property_values", []) or []:
+ if override.get("type") == "person" and override.get("key"):
+ referenced_keys.add(override["key"])
+
+ return {key: value for key, value in person_properties.items() if key in referenced_keys}
+
+
def check_flag_limits_for_team(
team_id: int,
is_create: bool = True,
@@ -1112,7 +1163,12 @@ class FeatureFlagSerializer(
code="invalid_value",
)
try:
- if float(prop.value[0]) > float(prop.value[1]):
+ min_val = prop.value[0]
+ max_val = prop.value[1]
+ # Type check: ensure both values can be converted to float
+ if not isinstance(min_val, (int, float, str)) or not isinstance(max_val, (int, float, str)):
+ raise ValueError("Values must be numeric")
+ if float(min_val) > float(max_val):
raise serializers.ValidationError(
detail=f"{prop.operator} operator requires min value to be less than or equal to max value",
code="invalid_value",
@@ -1997,6 +2053,106 @@ class DependentFlagSerializer(serializers.Serializer):
name = serializers.CharField(help_text="Feature flag name")
+class FeatureFlagTestEvaluationRequestSerializer(serializers.Serializer):
+ distinct_id = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ help_text="User distinct ID to test against (mutually exclusive with person_id)",
+ )
+ person_id = serializers.CharField(
+ required=False, allow_blank=False, help_text="Person ID to test against (mutually exclusive with distinct_id)"
+ )
+ timestamp = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Optional point-in-time to evaluate the flag against — both flag conditions "
+ "and person properties are reconstructed as they existed at that timestamp. "
+ "ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. "
+ "Naive timestamps (no timezone) are interpreted as UTC."
+ ),
+ )
+ groups = serializers.JSONField(
+ required=False,
+ default=dict,
+ help_text="Groups for feature flag evaluation (JSON object, defaults to empty dict)",
+ )
+
+ def validate(self, attrs):
+ distinct_id = attrs.get("distinct_id")
+ person_id = attrs.get("person_id")
+
+ if not distinct_id and not person_id:
+ raise serializers.ValidationError("Either distinct_id or person_id must be provided")
+
+ if distinct_id and person_id:
+ raise serializers.ValidationError("Cannot provide both distinct_id and person_id")
+
+ return attrs
+
+
+class FeatureFlagConditionPropertyAnalysisSerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="Property key")
+ operator = serializers.CharField(help_text="Comparison operator")
+ value = serializers.JSONField(help_text="Expected property value")
+ type = serializers.CharField(help_text="Property type (person, group, etc.)")
+ actual_value = serializers.JSONField(allow_null=True, help_text="Actual property value from user")
+ matched = serializers.BooleanField(help_text="Whether this property condition matched")
+ explanation = serializers.CharField(help_text="Human-readable explanation of the match result")
+
+
+class FeatureFlagConditionAnalysisSerializer(serializers.Serializer):
+ index = serializers.IntegerField(help_text="Index of this condition in the feature flag")
+ matched = serializers.BooleanField(
+ help_text=(
+ "True when this condition was the one that determined the flag's outcome. "
+ "Use this to find the winning condition — at most one condition per flag is True."
+ )
+ )
+ properties_matched = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "True when every property in this condition evaluated to true, regardless of "
+ "whether this condition was the eventual winner."
+ ),
+ )
+ explanation = serializers.CharField(
+ help_text="Human-readable explanation of why this condition matched/didn't match"
+ )
+ rollout_percentage = serializers.FloatField(help_text="Rollout percentage for this condition (0.0-100.0)")
+ rollout_excluded = serializers.BooleanField(
+ help_text="Whether this condition matched properties but was excluded due to rollout"
+ )
+ variant = serializers.CharField(allow_null=True, help_text="Variant associated with this condition")
+ properties = FeatureFlagConditionPropertyAnalysisSerializer(
+ many=True, help_text="Analysis of each property in this condition"
+ )
+
+
+class FeatureFlagTestEvaluationResponseSerializer(serializers.Serializer):
+ flag_key = serializers.CharField(help_text="Feature flag key")
+ result = serializers.JSONField(help_text="The evaluated value of the feature flag (boolean or variant key string)")
+ reason = serializers.CharField(help_text="The reason for the evaluation result")
+ condition_index = serializers.IntegerField(
+ allow_null=True, help_text="The index of the condition that matched, if applicable"
+ )
+ payload = serializers.JSONField(allow_null=True, help_text="Payload associated with the flag result, if any")
+ person_properties = serializers.DictField(
+ help_text="Person properties at the time of evaluation (for historical evaluations)"
+ )
+ evaluation_distinct_id = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The distinct_id used for rollout/variant bucketing. Echoes the caller-provided "
+ "distinct_id when one was sent; null on the person_id path so the endpoint doesn't "
+ "leak the person's other distinct_ids to a feature_flag:read-only token."
+ ),
+ )
+ conditions = FeatureFlagConditionAnalysisSerializer(
+ many=True, help_text="Detailed analysis of each condition in the feature flag"
+ )
+
+
class FeatureFlagVersionResponseSerializer(serializers.ModelSerializer):
"""Feature flag state at a given version plus reconstruction metadata."""
@@ -3383,6 +3539,302 @@ class FeatureFlagViewSet(
status=status.HTTP_200_OK,
)
+ @validated_request(
+ request_serializer=FeatureFlagTestEvaluationRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=FeatureFlagTestEvaluationResponseSerializer),
+ 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid parameters"),
+ 404: OpenApiResponse(response=ErrorResponseSerializer, description="Person not found"),
+ 500: OpenApiResponse(response=ErrorResponseSerializer, description="Server error"),
+ 502: OpenApiResponse(response=ErrorResponseSerializer, description="Flag evaluation service error"),
+ },
+ )
+ @action(
+ methods=["POST"],
+ detail=True,
+ required_scopes=["feature_flag:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
+ def test_evaluation(self, request: request.Request, **kwargs):
+ """
+ Test feature flag evaluation against a specific user at an optional point in time.
+
+ This endpoint allows testing how a feature flag would evaluate for a specific user,
+ optionally at a historical timestamp. When a timestamp is provided, both the flag
+ conditions and person properties are evaluated as they existed at that time.
+ """
+ feature_flag = self.get_object()
+
+ # Extract validated data - prioritize person_id over distinct_id
+ distinct_id = request.validated_data.get("distinct_id")
+ person_id = request.validated_data.get("person_id")
+ timestamp = request.validated_data.get("timestamp")
+ groups = request.validated_data.get("groups") or {}
+
+ # Resolve person and distinct_ids
+ try:
+ person, distinct_ids = get_person_and_distinct_ids_for_identifier(
+ team_id=self.team_id, distinct_id=distinct_id, person_id=person_id
+ )
+ except ValueError as e:
+ capture_exception(e)
+ return Response({"error": "Invalid parameters"}, status=status.HTTP_400_BAD_REQUEST)
+ except Exception as e:
+ capture_exception(e)
+ return Response({"error": "Failed to resolve person"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+ if not person or not distinct_ids:
+ identifier_type = "distinct_id" if distinct_id else "person_id"
+ identifier_value = distinct_id or person_id
+ return Response(
+ {"detail": f"Person not found for {identifier_type}: {identifier_value}"},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+
+ # Prefer the caller-provided distinct_id for evaluation when it resolves to this person,
+ # since rollout/variant assignment can depend on the exact distinct_id used.
+ # If person_id was provided, pick the lexicographically smallest distinct_id so the
+ # choice is stable across calls — proto_person_to_model / the ORM don't guarantee order.
+ evaluation_distinct_id = distinct_id if distinct_id and distinct_id in distinct_ids else sorted(distinct_ids)[0]
+ person_properties: dict[str, Any] = {}
+
+ # Build person properties at timestamp if provided
+ if timestamp:
+ try:
+ # Tag the ClickHouse call so query_log attribution stays correct.
+ tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY, team_id=self.team_id)
+ lower_bound = timestamp - timedelta(days=730)
+ if feature_flag.created_at:
+ lower_bound = min(max(lower_bound, feature_flag.created_at), timestamp)
+ person_properties = build_person_properties_at_time(
+ team_id=self.team_id,
+ timestamp=timestamp,
+ distinct_ids=distinct_ids,
+ include_set_once=True,
+ lower_bound=lower_bound,
+ )
+ except ValueError as e:
+ # Our own validation (invalid timestamp shape, naive datetime, etc.) —
+ # Validation failures should be logged server-side, but return a generic
+ # message to avoid exposing internal exception details to API callers.
+ logger.warning("Invalid timestamp input for flag %s: %s", feature_flag.key, e)
+ return Response(
+ {"error": "Invalid timestamp format."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except Exception:
+ # ClickHouse / infra failures keep the generic 500 but log the real cause.
+ logger.exception("Failed to build person properties at timestamp for flag %s", feature_flag.key)
+ return Response(
+ {"error": "Failed to build person properties at specified timestamp."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ else:
+ # Use current person properties
+ person_properties = person.properties or {}
+
+ # If timestamp is provided, reconstruct the flag at that point in time.
+ # ``evaluation_filters`` is what we hand to _filter_person_properties_for_flag
+ # and what the Rust override payload's "filters" entry comes from.
+ evaluation_filters: dict[str, Any] = feature_flag.filters or {}
+ reconstructed_flag_data: Optional[dict[str, Any]] = None
+ if timestamp:
+ try:
+ # Reconstruct the flag at the timestamp using the efficient single-pass method
+ reconstructed_flag_data = reconstruct_flag_at_timestamp(
+ flag=feature_flag,
+ timestamp=timestamp,
+ team_id=self.team_id,
+ )
+ evaluation_filters = reconstructed_flag_data.get("filters") or {}
+
+ except VersionNotFound:
+ return Response(
+ {"error": f"Feature flag '{feature_flag.key}' did not exist at the specified timestamp."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except VersionHistoryIncomplete:
+ return Response(
+ {"error": "Could not reconstruct flag at timestamp due to incomplete history."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except ValueError as e:
+ # e.g. "timestamp must be timezone-aware" from version_history.
+ logger.warning("Invalid timestamp for flag reconstruction (flag %s): %s", feature_flag.key, e)
+ return Response(
+ {"error": "Invalid timestamp."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except Exception:
+ logger.exception("Failed to reconstruct flag at timestamp for flag %s", feature_flag.key)
+ return Response(
+ {"error": "Failed to reconstruct flag at specified timestamp."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ # Evaluate the flag
+ try:
+ # Get team API token for Rust service
+ team_token = self.team.api_token
+
+ # If we reconstructed a historical version, ship the reconstructed
+ # field set as the override payload. Building straight from
+ # reconstructed_flag_data avoids round-tripping through an in-memory
+ # FeatureFlag(...), which would silently substitute model defaults
+ # for any field we forgot to copy (bucketing_identifier,
+ # evaluation_runtime, ensure_experience_continuity, evaluation_tags,
+ # …) and ship those defaults as the historical value.
+ override_definitions = None
+ if timestamp and reconstructed_flag_data is not None:
+ try:
+ # Use allowlist of fields that Rust expects, avoiding the need to track
+ # what _build_response might inject in the future
+ flag_dict: dict[str, Any] = {
+ k: reconstructed_flag_data[k] for k in RUST_FLAG_FIELDS if k in reconstructed_flag_data
+ }
+ flag_dict.update({"id": feature_flag.id, "key": feature_flag.key, "team_id": feature_flag.team_id})
+
+ # Stringify datetime fields for JSON serialization.
+ if flag_dict.get("created_at") and hasattr(flag_dict["created_at"], "isoformat"):
+ flag_dict["created_at"] = flag_dict["created_at"].isoformat()
+
+ override_definitions = {feature_flag.key: flag_dict}
+ except Exception as e:
+ logger.exception("Failed to serialize flag for override")
+ capture_exception(e)
+ return Response(
+ {"error": "Failed to prepare historical flag definition for evaluation."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ internal_token = os.getenv("INTERNAL_REQUEST_TOKEN")
+ if not internal_token:
+ return Response(
+ {"error": "Internal request token not configured"},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ rust_response = get_flags_from_service(
+ token=team_token,
+ distinct_id=evaluation_distinct_id,
+ groups=groups,
+ detailed_analysis=True,
+ person_properties=person_properties,
+ only_use_override_person_properties=timestamp is not None,
+ flag_keys=[feature_flag.key],
+ internal_request_token=internal_token,
+ override_flags_definitions=override_definitions,
+ )
+
+ # Extract the flag result from the Rust response
+ flags = rust_response.get("flags", {})
+ flag_result = flags.get(feature_flag.key)
+
+ # Initialize defaults
+ condition_index = None
+ payload = None
+ detailed_conditions: list[dict] = []
+ result: bool | str = False
+
+ if flag_result is None:
+ result = False
+ reason = "flag_not_found"
+ else:
+ # Extract the detailed flag result data
+ if isinstance(flag_result, dict):
+ result = flag_result.get("enabled", False)
+ variant = flag_result.get("variant")
+ reason_data = flag_result.get("reason", {})
+ metadata = flag_result.get("metadata", {})
+
+ # Extract values from the correct nested structures
+ reason = reason_data.get("code", "unknown") if reason_data else "unknown"
+ condition_index = reason_data.get("condition_index") if reason_data else None
+ payload = metadata.get("payload") if metadata else None
+ # Extract conditions from flag result (only valid path per Rust FlagDetails contract).
+ # When ``timestamp`` is set, missing conditions almost certainly means Rust
+ # rejected the internal token and silently fell back to current-state
+ # evaluation: returning a 200 with current-state values would silently corrupt
+ # the historical contract this endpoint promises, so fail loudly instead.
+ if "conditions" not in flag_result:
+ if timestamp:
+ logger.error(
+ "Historical evaluation returned no conditions; INTERNAL_REQUEST_TOKEN may be misconfigured",
+ extra={
+ "flag_key": feature_flag.key,
+ "response_keys": list(flag_result.keys()),
+ },
+ )
+ return Response(
+ {"error": "Historical evaluation unavailable. Check service configuration."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ logger.warning(
+ "Missing 'conditions' key in flag evaluation response",
+ extra={"flag_key": feature_flag.key, "response_keys": list(flag_result.keys())},
+ )
+ detailed_conditions = flag_result.get("conditions", [])
+
+ # If there's a variant, use it as the result
+ if variant is not None:
+ result = variant
+ else:
+ # /flags endpoint with v=2 always returns dict, these branches should never fire
+ logger.error(
+ "Unexpected flag_result type in test_evaluation",
+ extra={
+ "flag_key": feature_flag.key,
+ "result_type": type(flag_result).__name__,
+ "result_value": str(flag_result)[:100],
+ },
+ )
+ return Response(
+ {"error": "Unexpected response format from flag evaluation service"},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ # Only echo back the bucketing distinct_id when the caller already
+ # had it (they sent it in the request). On the person_id path we
+ # picked one for them out of the person's set, and surfacing it
+ # would let a ``feature_flag:read``-only token enumerate distinct
+ # IDs for any UUID — which normally requires ``person:read``.
+ response_evaluation_distinct_id = (
+ evaluation_distinct_id if distinct_id and distinct_id in distinct_ids else None
+ )
+ response_data = {
+ "flag_key": feature_flag.key,
+ "result": result,
+ "reason": reason,
+ "condition_index": condition_index,
+ "payload": payload,
+ "person_properties": _filter_person_properties_for_flag(evaluation_filters, person_properties),
+ "evaluation_distinct_id": response_evaluation_distinct_id,
+ "conditions": detailed_conditions,
+ }
+
+ response_serializer = FeatureFlagTestEvaluationResponseSerializer(data=response_data)
+ response_serializer.is_valid(raise_exception=True)
+ return Response(response_serializer.data)
+
+ except Exception as e:
+ logger.exception(
+ "Error evaluating flag '%s' for distinct_id='%s' person_id='%s' timestamp='%s': %s",
+ feature_flag.key,
+ distinct_id,
+ person_id,
+ timestamp,
+ e,
+ extra={
+ "flag_key": feature_flag.key,
+ "distinct_id": distinct_id,
+ "person_id": person_id,
+ "timestamp": timestamp,
+ "groups": groups,
+ },
+ )
+ capture_exception(e)
+ return Response({"error": "Failed to evaluate flag"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
@action(
methods=["GET"],
detail=True,
diff --git a/posthog/api/person.py b/posthog/api/person.py
index ad5d16483f29..89706dfb5f28 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -4,7 +4,6 @@ from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any, List, Optional, TypeVar, Union, cast # noqa: UP035
-from django.conf import settings
from django.db.models import Prefetch
from django.shortcuts import get_object_or_404
@@ -331,18 +330,6 @@ class PersonPropertiesAtTimeMetadataSerializer(serializers.Serializer):
distinct_ids_count = serializers.IntegerField(help_text="Number of distinct_ids associated with this person")
-class PersonPropertiesAtTimeDebugSerializer(serializers.Serializer):
- """Serializer for the debug information (only available to staff users)."""
-
- query = serializers.CharField(help_text="The ClickHouse query that was executed")
- params = serializers.DictField(help_text="The parameters passed to the query")
- events_found = serializers.IntegerField(help_text="Number of events found")
- events = serializers.ListField(
- child=serializers.DictField(), help_text="Raw events that were used to build the properties"
- )
- error = serializers.CharField(required=False, help_text="Error message if debug query failed")
-
-
class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):
"""Serializer for the point-in-time person properties response."""
@@ -364,9 +351,6 @@ class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):
point_in_time_metadata = PersonPropertiesAtTimeMetadataSerializer(
help_text="Metadata about the point-in-time query"
)
- debug = PersonPropertiesAtTimeDebugSerializer(
- required=False, help_text="Debug information (only available when debug=true and DEBUG=True)"
- )
def get_funnel_actor_class(filter: Filter) -> Callable:
@@ -1306,13 +1290,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
description="Whether to handle $set_once operations (default: false)",
required=False,
),
- OpenApiParameter(
- name="debug",
- type=bool,
- location=OpenApiParameter.QUERY,
- description="Whether to include debug information with raw events (only works when DEBUG=True, default: false)",
- required=False,
- ),
],
responses={
200: PersonPropertiesAtTimeResponseSerializer,
@@ -1334,7 +1311,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- distinct_id: The distinct_id of the person
- timestamp: ISO datetime string for the point in time (e.g., "2023-06-15T14:30:00Z")
- include_set_once: Whether to handle $set_once operations (default: false)
- - debug: Whether to include debug information with raw events (default: false)
"""
from posthog.models.person.point_in_time_properties import (
build_person_properties_at_time,
@@ -1345,7 +1321,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
person_id = request.GET.get("person_id")
timestamp_str = request.GET.get("timestamp")
include_set_once = request.GET.get("include_set_once", "false").lower() == "true"
- debug = request.GET.get("debug", "false").lower() == "true"
# Validate parameters
if distinct_id and person_id:
@@ -1401,33 +1376,13 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
# Build point-in-time properties using the pre-fetched distinct_ids
- # If debug mode is enabled, get raw events to avoid duplicate query
- debug_rows: list[Any] = []
- debug_query: str = ""
- debug_params: dict[str, Any] = {}
- point_in_time_properties: dict[str, Any]
- if debug and settings.DEBUG:
- result = build_person_properties_at_time(
- team_id=self.team_id,
- timestamp=timestamp,
- distinct_ids=distinct_ids_queried,
- include_set_once=include_set_once,
- return_debug_info=True,
- )
- # Type cast to help mypy understand the tuple unpacking
- point_in_time_properties, debug_rows, debug_query, debug_params = cast(
- tuple[dict[str, Any], list[Any], str, dict[str, Any]], result
- )
- else:
- point_in_time_properties = cast(
- dict[str, Any],
- build_person_properties_at_time(
- team_id=self.team_id,
- timestamp=timestamp,
- distinct_ids=distinct_ids_queried,
- include_set_once=include_set_once,
- ),
- )
+ tag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY, team_id=self.team_id)
+ point_in_time_properties = build_person_properties_at_time(
+ team_id=self.team_id,
+ timestamp=timestamp,
+ distinct_ids=distinct_ids_queried,
+ include_set_once=include_set_once,
+ )
# Serialize the person object
person_data = PersonSerializer(person, context={"get_team": lambda: self.team}).data
@@ -1446,18 +1401,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"distinct_ids_count": len(distinct_ids_queried),
}
- # Add debug information if requested and in debug mode
- if debug and settings.DEBUG:
- # Use the raw events, query, and params that were already fetched to avoid duplicate query
- person_data["debug"] = {
- "query": debug_query,
- "params": debug_params,
- "events_found": len(debug_rows),
- "events": [
- {"properties_json": row[0], "timestamp": str(row[1]), "event": row[2]} for row in debug_rows
- ],
- }
-
return response.Response(person_data)
except Exception:
diff --git a/posthog/api/services/flags_service.py b/posthog/api/services/flags_service.py
index 1674056961c5..cf5b42fa2078 100644
--- a/posthog/api/services/flags_service.py
+++ b/posthog/api/services/flags_service.py
@@ -19,6 +19,12 @@ def get_flags_from_service(
token: str,
distinct_id: str,
groups: dict[str, Any] | None = None,
+ detailed_analysis: bool = False,
+ person_properties: dict[str, Any] | None = None,
+ only_use_override_person_properties: bool = False,
+ flag_keys: list[str] | None = None,
+ internal_request_token: str | None = None,
+ override_flags_definitions: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
Proxy a request to the Rust feature flags service /flags endpoint.
@@ -27,10 +33,16 @@ def get_flags_from_service(
token: The project API token (the public token) for the team
distinct_id: The distinct ID for the user
groups: Optional groups for group-based flags (default: None)
+ detailed_analysis: Whether to include detailed condition analysis (default: False)
+ person_properties: Optional person properties for evaluation (default: None)
+ only_use_override_person_properties: Whether to ignore database person properties and only use provided ones (default: False)
+ flag_keys: Optional list of specific flag keys to evaluate (default: None, evaluates all flags)
+ internal_request_token: Optional token to mark request as internal (non-billable) (default: None)
+ override_flags_definitions: Optional dict of flag key -> flag definition to override database flags (default: None)
Returns:
The full response from the flags service as a dict, typically containing:
- - "flags": dict of flag key -> value/boolean
+ - "flags": dict of flag key -> flag data (enabled, variant, etc.)
- "featureFlagPayloads": dict of flag key -> payload (if requested)
- Other metadata depending on API version
@@ -59,12 +71,32 @@ def get_flags_from_service(
if groups:
payload["groups"] = groups
+ if person_properties is not None:
+ payload["person_properties"] = person_properties
+
+ if flag_keys:
+ payload["flag_keys"] = flag_keys
+
+ if override_flags_definitions:
+ payload["override_flags_definitions"] = override_flags_definitions
+
params: dict[str, str] = {"v": "2"}
+ if detailed_analysis:
+ params["detailed_analysis"] = "true"
+
+ if only_use_override_person_properties:
+ params["only_use_override_person_properties"] = "true"
+
+ headers = {}
+ if internal_request_token and internal_request_token.strip():
+ headers["Authorization"] = f"Bearer {internal_request_token}"
+
response = _FLAGS_SERVICE_SESSION.post(
f"{flags_service_url}/flags",
params=params,
json=payload,
+ headers=headers,
timeout=proxy_timeout,
)
response.raise_for_status()
diff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.py
index 10787c98f994..1ddf39482adb 100644
--- a/posthog/api/test/test_feature_flag.py
+++ b/posthog/api/test/test_feature_flag.py
@@ -1,3 +1,4 @@
+import os
import json
from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
@@ -12776,3 +12777,510 @@ class TestFeatureFlagVersions(APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/versions/1/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "not available" in response.json()["detail"].lower()
+
+
+class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_happy_path(self, mock_get_person, mock_get_flags):
+ """Test successful evaluation of a feature flag."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="test-flag",
+ filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "[email protected]"}]}]},
+ )
+ person = Person.objects.create(
+ team=self.team, distinct_ids=["test-user"], properties={"email": "[email protected]"}
+ )
+
+ # Mock person lookup
+ mock_get_person.return_value = (person, ["test-user"])
+
+ # Mock successful flag evaluation response
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": True,
+ "variant": None,
+ "reason": {"code": "condition_match", "condition_index": 0},
+ "metadata": {"payload": None},
+ "conditions": [
+ {
+ "index": 0,
+ "matched": True,
+ "explanation": "Condition matched",
+ "rollout_percentage": 100.0,
+ "rollout_excluded": False,
+ "variant": None,
+ "properties": [],
+ }
+ ],
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["flag_key"], "test-flag")
+ self.assertEqual(data["result"], True)
+ self.assertEqual(data["reason"], "condition_match")
+ self.assertEqual(data["condition_index"], 0)
+ self.assertIsInstance(data["person_properties"], dict)
+ # Caller-provided distinct_id resolves to the person → it must drive bucketing.
+ self.assertEqual(data["evaluation_distinct_id"], "test-user")
+ self.assertEqual(mock_get_flags.call_args.kwargs["distinct_id"], "test-user")
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_with_person_id_uses_smallest_distinct_id(self, mock_get_person, mock_get_flags):
+ """When the caller passes person_id (no distinct_id), bucketing must
+ pick the lexicographically smallest distinct_id so two calls with the
+ same person_id are deterministic — proto_person_to_model / the ORM
+ don't guarantee a stable order. The response must NOT echo the chosen
+ distinct_id back, otherwise feature_flag:read tokens could enumerate
+ distinct_ids for any person UUID."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ person = Person.objects.create(team=self.team, distinct_ids=["zzz", "aaa", "mmm"])
+
+ # Hand the resolver back distinct_ids in deliberately non-sorted order
+ # to prove the sort happens in feature_flag.py, not upstream.
+ mock_get_person.return_value = (person, ["zzz", "aaa", "mmm"])
+
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ "conditions": [],
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"person_id": str(person.uuid)},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # Bucketing still uses the resolved smallest distinct_id...
+ self.assertEqual(mock_get_flags.call_args.kwargs["distinct_id"], "aaa")
+ # ...but the response must NOT leak it back to the caller.
+ self.assertIsNone(response.json()["evaluation_distinct_id"])
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_with_timestamp(self, mock_get_flags):
+ """Historical evaluation must drive the Rust call with reconstructed
+ person properties + override definitions, not the live flag's data."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="test-flag",
+ filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "x"}]}]},
+ bucketing_identifier="device_id",
+ evaluation_runtime="server",
+ ensure_experience_continuity=True,
+ )
+
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ "conditions": [],
+ }
+ }
+ }
+
+ with patch("posthog.api.feature_flag.build_person_properties_at_time") as mock_build_props:
+ mock_build_props.return_value = {"email": "[email protected]"}
+
+ # Use a recent timestamp that's after flag creation
+ from datetime import datetime
+
+ recent_timestamp = datetime.now(UTC).isoformat()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": recent_timestamp},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_build_props.assert_called_once()
+
+ # Build was given the requested timestamp and the resolved distinct_ids,
+ # so the historical props lookup actually targeted the right window/person.
+ _, build_kwargs = mock_build_props.call_args
+ self.assertEqual(build_kwargs["distinct_ids"], ["test-user"])
+ self.assertTrue(build_kwargs["include_set_once"])
+ self.assertEqual(build_kwargs["timestamp"].isoformat(), recent_timestamp)
+
+ # The whole point of the timestamp branch: the Rust call must use
+ # the reconstructed person_properties, not the live person row, and
+ # must include the historical override definition keyed by flag key.
+ _, get_flags_kwargs = mock_get_flags.call_args
+ self.assertTrue(get_flags_kwargs["only_use_override_person_properties"])
+ self.assertEqual(get_flags_kwargs["person_properties"], {"email": "[email protected]"})
+ self.assertIn("test-flag", get_flags_kwargs["override_flags_definitions"])
+ self.assertEqual(get_flags_kwargs["override_flags_definitions"]["test-flag"]["id"], flag.id)
+ self.assertEqual(get_flags_kwargs["override_flags_definitions"]["test-flag"]["team_id"], self.team.pk)
+ self.assertEqual(get_flags_kwargs["override_flags_definitions"]["test-flag"]["key"], "test-flag")
+ self.assertEqual(
+ get_flags_kwargs["override_flags_definitions"]["test-flag"]["bucketing_identifier"], "device_id"
+ )
+ self.assertEqual(get_flags_kwargs["override_flags_definitions"]["test-flag"]["evaluation_runtime"], "server")
+ self.assertEqual(
+ get_flags_kwargs["override_flags_definitions"]["test-flag"]["ensure_experience_continuity"], True
+ )
+
+ # Filtered person_properties in the response only carry keys referenced
+ # by the (reconstructed) flag's conditions.
+ self.assertEqual(response.json()["person_properties"], {"email": "[email protected]"})
+
+ def test_test_evaluation_distinct_id_person_id_conflict(self):
+ """Test validation error when both distinct_id and person_id are provided."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "person_id": "123"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("Cannot provide both distinct_id and person_id", response.json()["detail"])
+
+ def test_test_evaluation_person_not_found(self):
+ """Test 404 when person doesn't exist."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "nonexistent-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.json()["detail"], "Person not found for distinct_id: nonexistent-user")
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ def test_test_evaluation_missing_internal_token_error(self, mock_get_flags):
+ """Test 500 when INTERNAL_REQUEST_TOKEN is not set."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ with patch("posthog.api.feature_flag.os.getenv", return_value=None):
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ self.assertEqual(response.json()["error"], "Internal request token not configured")
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_historical_missing_conditions_502(self, mock_get_flags):
+ """Test 502 when historical evaluation returns no conditions (misconfigured token)."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ # Mock service to return flag dict without 'conditions' key - indicates token issue
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ # Missing 'conditions' key indicates token misconfiguration
+ }
+ }
+ }
+
+ with patch("posthog.api.feature_flag.build_person_properties_at_time", return_value={}):
+ # Use a recent timestamp that's after flag creation
+ from datetime import datetime
+
+ recent_timestamp = datetime.now(UTC).isoformat()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": recent_timestamp},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
+ self.assertEqual(response.json()["error"], "Historical evaluation unavailable. Check service configuration.")
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_current_missing_conditions_200(self, mock_get_flags):
+ """Test 200 when current evaluation returns no conditions (no 502 for current evaluation)."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ # Mock service to return flag dict without 'conditions' key
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ # Missing 'conditions' key - should not cause 502 for current evaluation
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ # No timestamp = current evaluation
+ format="json",
+ )
+
+ # The key test: current evaluation should not return 502 even with missing conditions
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # Verify the response is still valid
+ self.assertIn("result", response.json())
+
+ @patch("posthog.api.feature_flag.build_person_properties_at_time")
+ def test_test_evaluation_build_properties_failure(self, mock_build_props):
+ """Test 500 when build_person_properties_at_time raises exception."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ # Mock exception during property building
+ mock_build_props.side_effect = Exception("Database error")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": "2023-01-01T00:00:00Z"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ self.assertEqual(response.json()["error"], "Failed to build person properties at specified timestamp.")
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_filters_person_properties(self, mock_get_flags):
+ """Test that person_properties are filtered to only flag-referenced keys."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="test-flag",
+ filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "[email protected]"}]}]},
+ )
+ Person.objects.create(
+ team=self.team,
+ distinct_ids=["test-user"],
+ properties={"email": "[email protected]", "name": "Test User", "age": 30},
+ )
+
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": True,
+ "variant": None,
+ "reason": {"code": "condition_match"},
+ "metadata": {},
+ "conditions": [
+ {
+ "index": 0,
+ "matched": True,
+ "explanation": "Condition matched",
+ "rollout_percentage": 100.0,
+ "rollout_excluded": False,
+ "variant": None,
+ "properties": [],
+ }
+ ],
+ }
+ }
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ # Should only include 'email' since that's referenced in the flag, not 'name' or 'age'
+ self.assertEqual(data["person_properties"], {"email": "[email protected]"})
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_unexpected_response_type(self, mock_get_flags):
+ """Test 502 when flag service returns unexpected response format."""
+ flag = FeatureFlag.objects.create(team=self.team, key="test-flag")
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ # Mock unexpected response format (not a dict)
+ mock_get_flags.return_value = {"flags": {"test-flag": "unexpected_string"}}
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
+ self.assertEqual(response.json()["error"], "Unexpected response format from flag evaluation service")
+
+ def test_test_evaluation_missing_distinct_id(self):
+ """Test validation error when distinct_id is missing."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ name="Test Flag",
+ key="test-flag",
+ created_by=self.user,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/test_evaluation/",
+ data={"flag_key": "test-flag"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_test_evaluation_invalid_timestamp(self):
+ """Test validation error with invalid timestamp format."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ name="Test Flag",
+ key="test-flag",
+ created_by=self.user,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/test_evaluation/",
+ data={"distinct_id": "user123", "flag_key": "test-flag", "timestamp": "invalid"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 400)
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_build_properties_value_error_no_leak(self, mock_get_flags):
+ """Test that ValueError from build_person_properties_at_time doesn't leak sensitive information."""
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ "conditions": [],
+ }
+ }
+ }
+
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="test-flag",
+ filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "x"}]}]},
+ bucketing_identifier="device_id",
+ evaluation_runtime="server",
+ ensure_experience_continuity=True,
+ )
+
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+
+ with patch("posthog.api.feature_flag.build_person_properties_at_time") as mock_build_props:
+ # Mock build_person_properties_at_time to raise ValueError with sensitive information
+ mock_build_props.side_effect = ValueError("naive datetime: /secret/path/user123")
+
+ # Use a recent timestamp that's after flag creation
+ recent_timestamp = datetime.now(UTC).isoformat()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": recent_timestamp},
+ format="json",
+ )
+
+ # Should return 400 with generic message
+ self.assertEqual(response.status_code, 400)
+ response_data = response.json()
+ self.assertEqual(response_data["error"], "Invalid timestamp format.")
+
+ # Ensure the sensitive information doesn't leak into the response
+ response_content = response.content.decode()
+ self.assertNotIn("secret", response_content.lower())
+ self.assertNotIn("/secret/path/user123", response_content)
+ self.assertNotIn("naive datetime", response_content)
+
+ # Verify the mock was called
+ mock_build_props.assert_called_once()
+
+ @patch("posthog.api.feature_flag.get_flags_from_service")
+ @patch.dict(os.environ, {"INTERNAL_REQUEST_TOKEN": "test-token"})
+ def test_test_evaluation_reconstruct_flag_value_error_no_leak(self, mock_get_flags):
+ """Test that ValueError from reconstruct_flag_at_timestamp doesn't leak sensitive information."""
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ name="Test Flag",
+ key="test-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ Person.objects.create(team=self.team, distinct_ids=["test-user"])
+ mock_get_flags.return_value = {
+ "flags": {
+ "test-flag": {
+ "enabled": False,
+ "variant": None,
+ "reason": {"code": "no_condition_match"},
+ "metadata": {},
+ "conditions": [],
+ }
+ }
+ }
+
+ with patch("posthog.api.feature_flag.reconstruct_flag_at_timestamp") as mock_reconstruct:
+ # Mock reconstruct_flag_at_timestamp to raise ValueError with sensitive information
+ mock_reconstruct.side_effect = ValueError("timestamp must be timezone-aware: /secret/config/token")
+
+ # Use a recent timestamp that's after flag creation
+ recent_timestamp = datetime.now(UTC).isoformat()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",
+ {"distinct_id": "test-user", "timestamp": recent_timestamp},
+ format="json",
+ )
+
+ # Should return 400 with generic message
+ self.assertEqual(response.status_code, 400)
+ response_data = response.json()
+ self.assertEqual(response_data["error"], "Invalid timestamp.")
+
+ # Ensure the sensitive information doesn't leak into the response
+ response_content = response.content.decode()
+ self.assertNotIn("secret", response_content.lower())
+ self.assertNotIn("/secret/config/token", response_content)
+ self.assertNotIn("timezone-aware", response_content)
+
+ # Verify the mock was called
+ mock_reconstruct.assert_called_once()
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index 0341d68692ab..fbc84965e52e 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -45,6 +45,10 @@ from posthog.utils_cors import cors_response
logger = structlog.get_logger(__name__)
+class ErrorResponseSerializer(serializers.Serializer):
+ error = serializers.CharField(help_text="Error message")
+
+
class PaginationMode(Enum):
next = auto()
previous = auto()
diff --git a/posthog/health.py b/posthog/health.py
index 0a5b19d404b9..b17dc1eebb16 100644
--- a/posthog/health.py
+++ b/posthog/health.py
@@ -260,7 +260,7 @@ def is_cache_backend_connected() -> bool:
# convenient less fragile way to do this. It would be nice if we could
# have a `check_health` exposed in some generic way, as the python redis
# client does appear to have something for this task.
- cache.has_key("_connection_test_key") # noqa: W601
+ cache.has_key("_connection_test_key")
except Exception:
# NOTE: We catch all exceptions here because we never want to throw from these checks
logger.debug("cache_backend_connection_failure", exc_info=True)
diff --git a/posthog/models/person/point_in_time_properties.py b/posthog/models/person/point_in_time_properties.py
index c4928129c2e2..a65de537a7b8 100644
--- a/posthog/models/person/point_in_time_properties.py
+++ b/posthog/models/person/point_in_time_properties.py
@@ -7,8 +7,8 @@ chronologically.
"""
import json
-from datetime import UTC, datetime
-from typing import TYPE_CHECKING, Any, Optional, Union
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Any, Optional
from posthog.clickhouse.client import sync_execute
@@ -16,10 +16,19 @@ if TYPE_CHECKING:
from posthog.models.person import Person
+DEFAULT_PROPERTY_ROW_LIMIT = 100_000
+
+# Hard floor on how far back the property scan walks. Anything older is almost
+# certainly past retention anyway; bounding here saves ClickHouse from walking
+# dead partitions when ``timestamp`` is the only bound (worst case: a brand-new
+# distinct_id with no matching events on a team with multi-year retention).
+_HISTORY_SCAN_FLOOR = timedelta(days=365 * 2)
+
+
def get_person_and_distinct_ids_for_identifier(
team_id: int,
distinct_id: Optional[str] = None,
- person_id: Optional[Union[str, int]] = None,
+ person_id: Optional[str] = None,
) -> tuple[Optional["Person"], list[str]]:
"""
Helper function to get person object and all distinct_ids for a person based on either distinct_id or person_id.
@@ -36,8 +45,6 @@ def get_person_and_distinct_ids_for_identifier(
ValueError: If parameters are invalid or both distinct_id and person_id are provided
Exception: If person lookup fails
"""
- from posthog.models.person.util import get_person_by_distinct_id, get_person_by_uuid
-
# Validation
if distinct_id is not None and person_id is not None:
raise ValueError("Cannot provide both distinct_id and person_id - choose one")
@@ -51,25 +58,27 @@ def get_person_and_distinct_ids_for_identifier(
if person_id is not None and not person_id:
raise ValueError("person_id must be a non-empty value")
- try:
- if distinct_id is not None:
- person = get_person_by_distinct_id(team_id, distinct_id)
- else:
- person = get_person_by_uuid(team_id, str(person_id))
+ from posthog.models.person.util import get_person_by_distinct_id, get_person_by_uuid
- if person is None:
- return None, []
+ if distinct_id is not None:
+ person = get_person_by_distinct_id(team_id, distinct_id)
+ else:
+ assert person_id is not None
+ person = get_person_by_uuid(team_id, person_id)
- return person, list(person.distinct_ids)
+ if person is None:
+ return None, []
- except Exception as e:
- raise Exception(f"Failed to query person distinct_ids: {str(e)}") from e
+ # Person.distinct_ids returns the in-memory cache when populated (e.g. by
+ # the personhog client wrapper around posthog/personhog_client/) and
+ # otherwise falls back to a DB query, so we can rely on it directly.
+ return person, person.distinct_ids
def get_distinct_ids_for_person_identifier(
team_id: int,
distinct_id: Optional[str] = None,
- person_id: Optional[Union[str, int]] = None,
+ person_id: Optional[str] = None,
) -> list[str]:
"""
Legacy helper function that returns only distinct_ids.
@@ -87,13 +96,11 @@ def build_person_properties_at_time(
distinct_ids: list[str],
include_set_once: bool = False,
timeout: Optional[int] = 30,
- return_debug_info: bool = False,
-) -> Union[dict[str, Any], tuple[dict[str, Any], list, str, dict[str, Any]]]:
+ row_limit: int = DEFAULT_PROPERTY_ROW_LIMIT,
+ lower_bound: Optional[datetime] = None,
+) -> dict[str, Any]:
"""
- Build person properties as they existed at a specific point in time.
-
- This method queries ClickHouse events to find all person property updates
- up to the given timestamp and reconstructs the final person properties state.
+ Build person properties at a specific point in time from ClickHouse events.
Args:
team_id: The team ID to filter events by
@@ -101,11 +108,11 @@ def build_person_properties_at_time(
distinct_ids: List of distinct_ids to query for person properties
include_set_once: If True, also handles $set_once operations (default: False)
timeout: Query timeout in seconds (default: 30)
- return_debug_info: If True, also returns query and params for debugging (default: False)
+ row_limit: Maximum property update rows to ship back from ClickHouse (default 100_000).
+ lower_bound: Optional lower bound for the time range scan. If not provided, defaults to timestamp - 2 years.
Returns:
- If return_debug_info=False: Dictionary of person properties as they existed at the specified time
- If return_debug_info=True: Tuple of (properties dict, raw_rows, query_string, query_params)
+ Dict containing person properties as they existed at the specified timestamp.
Raises:
ValueError: If parameters are invalid
@@ -124,49 +131,43 @@ def build_person_properties_at_time(
if not all(isinstance(did, str) and did for did in distinct_ids):
raise ValueError("All distinct_ids must be non-empty strings")
- # Build the ClickHouse query for all distinct_ids
+ if not isinstance(row_limit, int) or row_limit <= 0:
+ raise ValueError("row_limit must be a positive integer")
+
if include_set_once:
- # Query to get all property update events ($set, $set_once) up to timestamp
- # This includes both dedicated events and other events with $set in their properties
- query = """
- SELECT
- toJSONString(properties) as properties_json,
- timestamp,
- event
- FROM events
- WHERE team_id = %(team_id)s
- AND distinct_id IN %(distinct_ids)s
- AND timestamp <= %(timestamp)s
- AND (
- event = '$set'
- OR event = '$set_once'
- OR JSONHas(properties, '$set')
- )
- ORDER BY timestamp ASC
- """
+ event_filter = "event IN ('$set', '$set_once') OR JSONHas(properties, '$set')"
else:
- # Query to get all events that might contain $set operations
- # This includes both dedicated $set events and other events with $set in their properties
- query = """
- SELECT
- toJSONString(properties) as properties_json,
- timestamp,
- event
- FROM events
- WHERE team_id = %(team_id)s
- AND distinct_id IN %(distinct_ids)s
- AND timestamp <= %(timestamp)s
- AND (
- event = '$set'
- OR JSONHas(properties, '$set')
- )
- ORDER BY timestamp ASC
- """
+ event_filter = "event = '$set' OR JSONHas(properties, '$set')"
+
+ # Pulls every property-update event in the window. Existence is established
+ # upstream by get_person_and_distinct_ids_for_identifier (Postgres row);
+ # ``existed`` here means "had property activity in the scan window", which
+ # the property row count answers directly. We extract $set / $set_once raw
+ # JSON instead of shipping the full properties blob, and the timestamp
+ # window + LIMIT keeps ClickHouse from walking dead partitions.
+ query = f"""
+ SELECT
+ JSONExtractRaw(properties, '$set') AS set_json,
+ JSONExtractRaw(properties, '$set_once') AS set_once_json,
+ event AS event_name
+ FROM events
+ WHERE team_id = %(team_id)s
+ AND distinct_id IN %(distinct_ids)s
+ AND timestamp >= %(lower_bound)s
+ AND timestamp <= %(upper_bound)s
+ AND ({event_filter})
+ ORDER BY timestamp ASC
+ LIMIT {int(row_limit)}
+ """
+
+ # Use provided lower_bound or default to timestamp - 2 years
+ effective_lower_bound = lower_bound if lower_bound is not None else timestamp - _HISTORY_SCAN_FLOOR
params = {
"team_id": team_id,
"distinct_ids": distinct_ids,
- "timestamp": timestamp.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"),
+ "lower_bound": effective_lower_bound.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"),
+ "upper_bound": timestamp.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"),
}
try:
@@ -174,46 +175,30 @@ def build_person_properties_at_time(
except Exception as e:
raise Exception(f"Failed to query ClickHouse events: {str(e)}") from e
- # Build person properties by applying operations chronologically
- person_properties = {}
+ person_properties: dict[str, Any] = {}
for row in rows:
- properties_json, event_timestamp, event_name = row
+ set_json, set_once_json, event_name = row
- if properties_json:
+ if set_json:
try:
- # ClickHouse toJSONString() may return double-escaped JSON
- # Parse defensively to handle both single and double encoding
- parsed = json.loads(properties_json)
- event_properties = json.loads(parsed) if isinstance(parsed, str) else parsed
-
- if include_set_once:
- # Handle both $set and $set_once when include_set_once is True
- # Handle $set operations from any event (including nested $set in $pageview etc.)
- if "$set" in event_properties:
- set_properties = event_properties["$set"]
- if isinstance(set_properties, dict):
- person_properties.update(set_properties)
-
- # Handle $set_once operations (only from dedicated $set_once events)
- if event_name == "$set_once" and "$set_once" in event_properties:
- set_once_properties = event_properties["$set_once"]
- if isinstance(set_once_properties, dict):
- for key, value in set_once_properties.items():
- if key not in person_properties:
- person_properties[key] = value
- else:
- # Only handle $set operations when include_set_once is False
- if "$set" in event_properties:
- set_properties = event_properties["$set"]
- if isinstance(set_properties, dict):
- person_properties.update(set_properties)
-
- except (json.JSONDecodeError, KeyError, TypeError):
- # Skip events with malformed property data
- continue
-
- if return_debug_info:
- return person_properties, rows, query, params
- else:
- return person_properties
+ set_properties = json.loads(set_json)
+ except (json.JSONDecodeError, TypeError):
+ set_properties = None
+
+ if isinstance(set_properties, dict):
+ person_properties.update(set_properties)
+
+ # $set_once semantics only apply to dedicated $set_once events.
+ if include_set_once and event_name == "$set_once" and set_once_json:
+ try:
+ set_once_properties = json.loads(set_once_json)
+ except (json.JSONDecodeError, TypeError):
+ set_once_properties = None
+
+ if isinstance(set_once_properties, dict):
+ for key, value in set_once_properties.items():
+ if key not in person_properties:
+ person_properties[key] = value
+
+ return person_properties
diff --git a/posthog/models/person/test/test_point_in_time_properties.py b/posthog/models/person/test/test_point_in_time_properties.py
index 90270f1519d9..82909fcfcbeb 100644
--- a/posthog/models/person/test/test_point_in_time_properties.py
+++ b/posthog/models/person/test/test_point_in_time_properties.py
@@ -9,7 +9,7 @@ from typing import cast
from posthog.test.base import BaseTest
from unittest.mock import patch
-from django.test import SimpleTestCase, TestCase
+from django.test import SimpleTestCase
from parameterized import parameterized_class
@@ -21,9 +21,21 @@ from posthog.personhog_client.fake_client import fake_personhog_client
from posthog.personhog_client.test_helpers import PersonhogTestMixin
-class TestPointInTimeProperties(TestCase):
+def _prop_row(
+ set_dict: dict | None = None,
+ set_once_dict: dict | None = None,
+ event: str = "$set",
+) -> tuple:
+ """Helper to build a property-update row matching the SELECT shape."""
+ return (
+ json.dumps(set_dict) if set_dict is not None else "",
+ json.dumps(set_once_dict) if set_once_dict is not None else "",
+ event,
+ )
+
+
+class TestPointInTimeProperties(SimpleTestCase):
def test_build_person_properties_at_time_validation(self):
- """Test input validation for build_person_properties_at_time."""
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
# Test invalid team_id
@@ -55,73 +67,61 @@ class TestPointInTimeProperties(TestCase):
build_person_properties_at_time(1, timestamp, ["user123", ""])
self.assertIn("All distinct_ids must be non-empty strings", str(cm.exception))
+ # Invalid row_limit
+ with self.assertRaises(ValueError) as cm:
+ build_person_properties_at_time(1, timestamp, ["user123"], row_limit=0)
+ self.assertIn("row_limit must be a positive integer", str(cm.exception))
+
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_empty_result(self, mock_sync_execute):
- """Test building properties when no events exist."""
+ """Zero rows means the person had no property activity at or before timestamp."""
mock_sync_execute.return_value = []
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"])
+ properties = build_person_properties_at_time(1, timestamp, ["user123"])
- self.assertEqual(result, {})
+ self.assertEqual(properties, {})
mock_sync_execute.assert_called_once()
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_single_set(self, mock_sync_execute):
- """Test building properties with a single $set event."""
- # Mock ClickHouse response with a single $set event
- properties = {"$set": {"name": "John Doe", "email": "[email protected]"}}
- # ClickHouse toJSONString() returns double-encoded JSON
- double_encoded_json = json.dumps(json.dumps(properties))
- mock_sync_execute.return_value = [(double_encoded_json, datetime(2023, 1, 1, 10, 0, 0), "$set")]
+ mock_sync_execute.return_value = [
+ _prop_row(set_dict={"name": "John Doe", "email": "[email protected]"}, event="$set"),
+ ]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"])
+ properties = build_person_properties_at_time(1, timestamp, ["user123"])
- expected = {"name": "John Doe", "email": "[email protected]"}
- self.assertEqual(result, expected)
+ self.assertEqual(properties, {"name": "John Doe", "email": "[email protected]"})
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_multiple_sets(self, mock_sync_execute):
- """Test building properties with multiple $set events applied chronologically."""
- # Mock ClickHouse response with multiple $set events
- # ClickHouse toJSONString() returns double-encoded JSON
mock_sync_execute.return_value = [
- (json.dumps(json.dumps({"$set": {"name": "John", "age": 25}})), datetime(2023, 1, 1, 9, 0, 0), "$set"),
- (
- json.dumps(json.dumps({"$set": {"name": "John Doe", "location": "SF"}})),
- datetime(2023, 1, 1, 10, 0, 0),
- "$pageview",
- ),
- (json.dumps(json.dumps({"$set": {"age": 26}})), datetime(2023, 1, 1, 11, 0, 0), "$set"),
+ _prop_row(set_dict={"name": "John", "age": 25}, event="$set"),
+ _prop_row(set_dict={"name": "John Doe", "location": "SF"}, event="$pageview"),
+ _prop_row(set_dict={"age": 26}, event="$set"),
]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"])
+ properties = build_person_properties_at_time(1, timestamp, ["user123"])
- expected = {"name": "John Doe", "age": 26, "location": "SF"}
- self.assertEqual(result, expected)
+ self.assertEqual(properties, {"name": "John Doe", "age": 26, "location": "SF"})
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_malformed_json(self, mock_sync_execute):
- """Test handling of malformed JSON in event properties."""
- # ClickHouse toJSONString() returns double-encoded JSON
mock_sync_execute.return_value = [
- ("invalid json", datetime(2023, 1, 1, 9, 0, 0), "$set"),
- (json.dumps(json.dumps({"$set": {"name": "John"}})), datetime(2023, 1, 1, 10, 0, 0), "$set"),
- (json.dumps(json.dumps({"no_set_key": "value"})), datetime(2023, 1, 1, 11, 0, 0), "$pageview"),
+ ("invalid json", "", "$set"),
+ _prop_row(set_dict={"name": "John"}, event="$set"),
+ ("", "", "$pageview"),
]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"])
+ properties = build_person_properties_at_time(1, timestamp, ["user123"])
- # Should only get the valid $set event
- expected = {"name": "John"}
- self.assertEqual(result, expected)
+ self.assertEqual(properties, {"name": "John"})
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_clickhouse_error(self, mock_sync_execute):
- """Test handling of ClickHouse query errors."""
mock_sync_execute.side_effect = Exception("ClickHouse connection failed")
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
@@ -131,89 +131,76 @@ class TestPointInTimeProperties(TestCase):
self.assertIn("Failed to query ClickHouse events", str(cm.exception))
+ @patch("posthog.models.person.point_in_time_properties.sync_execute")
+ def test_row_limit_is_passed_to_query(self, mock_sync_execute):
+ mock_sync_execute.return_value = []
+
+ timestamp = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
-class TestPointInTimePropertiesWithSetOnce(TestCase):
+ build_person_properties_at_time(1, timestamp, ["user123"], row_limit=500)
+
+ mock_sync_execute.assert_called_once()
+ args, _ = mock_sync_execute.call_args
+ query, params = args[0], args[1]
+
+ self.assertIn("LIMIT 500", query)
+ self.assertEqual(params["upper_bound"], timestamp.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"))
+
+
+class TestPointInTimePropertiesWithSetOnce(SimpleTestCase):
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_with_set_once_basic(self, mock_sync_execute):
- """Test $set_once operations only set properties that don't exist."""
- # ClickHouse toJSONString() returns double-encoded JSON
+ """$set_once only sets properties that don't exist yet."""
mock_sync_execute.return_value = [
- (json.dumps(json.dumps({"$set": {"name": "John"}})), datetime(2023, 1, 1, 9, 0, 0), "$set"),
- (
- json.dumps(json.dumps({"$set_once": {"name": "Jane", "email": "[email protected]"}})),
- datetime(2023, 1, 1, 10, 0, 0),
- "$set_once",
- ),
+ _prop_row(set_dict={"name": "John"}, event="$set"),
+ _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),
]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
+ properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
- # name should remain "John" (not overwritten by $set_once)
- # email should be set by $set_once since it didn't exist
- expected = {"name": "John", "email": "[email protected]"}
- self.assertEqual(result, expected)
+ # name stays as "John" (not overwritten by $set_once); email is set by $set_once since it didn't exist
+ self.assertEqual(properties, {"name": "John", "email": "[email protected]"})
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_with_set_once_order_matters(self, mock_sync_execute):
- """Test that order of $set and $set_once operations matters."""
- # ClickHouse toJSONString() returns double-encoded JSON
mock_sync_execute.return_value = [
- (
- json.dumps(json.dumps({"$set_once": {"name": "Jane", "email": "[email protected]"}})),
- datetime(2023, 1, 1, 9, 0, 0),
- "$set_once",
- ),
- (json.dumps(json.dumps({"$set": {"name": "John"}})), datetime(2023, 1, 1, 10, 0, 0), "$set"),
+ _prop_row(set_once_dict={"name": "Jane", "email": "[email protected]"}, event="$set_once"),
+ _prop_row(set_dict={"name": "John"}, event="$set"),
]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
+ properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
# $set_once sets name first, then $set overwrites it
- expected = {"name": "John", "email": "[email protected]"}
- self.assertEqual(result, expected)
+ self.assertEqual(properties, {"name": "John", "email": "[email protected]"})
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_with_set_once_multiple_set_once(self, mock_sync_execute):
- """Test multiple $set_once operations - only first one should apply per property."""
- # ClickHouse toJSONString() returns double-encoded JSON
mock_sync_execute.return_value = [
- (
- json.dumps(json.dumps({"$set_once": {"name": "First", "email": "[email protected]"}})),
- datetime(2023, 1, 1, 9, 0, 0),
- "$set_once",
- ),
- (
- json.dumps(json.dumps({"$set_once": {"name": "Second", "location": "SF"}})),
- datetime(2023, 1, 1, 10, 0, 0),
- "$set_once",
- ),
+ _prop_row(set_once_dict={"name": "First", "email": "[email protected]"}, event="$set_once"),
+ _prop_row(set_once_dict={"name": "Second", "location": "SF"}, event="$set_once"),
]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
+ properties = build_person_properties_at_time(1, timestamp, ["user123"], include_set_once=True)
- # First $set_once should win for name, second should set location
- expected = {"name": "First", "email": "[email protected]", "location": "SF"}
- self.assertEqual(result, expected)
+ self.assertEqual(
+ properties,
+ {"name": "First", "email": "[email protected]", "location": "SF"},
+ )
@patch("posthog.models.person.point_in_time_properties.sync_execute")
def test_build_person_properties_at_time_with_distinct_ids_direct(self, mock_sync_execute):
- """Test building properties using distinct_ids parameter directly."""
- # Mock ClickHouse response with a single $set event
- properties = {"$set": {"name": "Jane Doe", "email": "[email protected]"}}
- # ClickHouse toJSONString() returns double-encoded JSON
- double_encoded_json = json.dumps(json.dumps(properties))
- mock_sync_execute.return_value = [(double_encoded_json, datetime(2023, 1, 1, 10, 0, 0), "$set")]
+ mock_sync_execute.return_value = [
+ _prop_row(set_dict={"name": "Jane Doe", "email": "[email protected]"}, event="$set"),
+ ]
timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- result = build_person_properties_at_time(1, timestamp, distinct_ids=["user123", "user456", "user789"])
+ properties = build_person_properties_at_time(1, timestamp, distinct_ids=["user123", "user456", "user789"])
- expected = {"name": "Jane Doe", "email": "[email protected]"}
- self.assertEqual(result, expected)
+ self.assertEqual(properties, {"name": "Jane Doe", "email": "[email protected]"})
- # Verify the query was called with all distinct_ids
mock_sync_execute.assert_called_once()
call_args = mock_sync_execute.call_args
self.assertEqual(call_args[0][1]["distinct_ids"], ["user123", "user456", "user789"])
diff --git a/posthog/models/person/test/test_point_in_time_properties_integration.py b/posthog/models/person/test/test_point_in_time_properties_integration.py
index 26a4ffe323b8..4d26ef12375a 100644
--- a/posthog/models/person/test/test_point_in_time_properties_integration.py
+++ b/posthog/models/person/test/test_point_in_time_properties_integration.py
@@ -1,222 +1,239 @@
"""
-Integration tests for point-in-time person properties building functionality.
+Real-ClickHouse integration tests for point-in-time person properties.
-These tests demonstrate the functionality but require ClickHouse to be available
-and may need actual event data to run properly.
+This file used to mock ``sync_execute``, which made the file's name a lie and
+let SQL typos / column-order mistakes / UNION-ALL ordering bugs sail through
+green. Each test now seeds events into ClickHouse and exercises the real query.
"""
-import json
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
-from unittest.mock import patch
-
-from django.test import TestCase
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from posthog.models.person.point_in_time_properties import build_person_properties_at_time
-class TestPointInTimePropertiesIntegration(TestCase):
- """
- Integration test examples showing how the point-in-time person properties
- building functionality would work in practice.
-
- Note: These tests use mocked ClickHouse responses to demonstrate the functionality
- without requiring a live ClickHouse instance.
- """
-
- @patch("posthog.models.person.point_in_time_properties.sync_execute")
- def test_realistic_person_properties_timeline(self, mock_sync_execute):
- """
- Test a realistic scenario where a person's properties evolve over time
- through multiple events and we want to see their state at a specific point.
- """
- # Simulate a timeline of events for user "alice123" on team 1:
- # Day 1: User signs up with basic info
- # Day 2: User completes profile with more details
- # Day 3: User's location changes
- # Day 4: User updates their preferences
-
- # ClickHouse toJSONString() returns double-encoded JSON
- mock_events = [
- # Day 1: Initial signup
- (
- json.dumps(
- json.dumps({"$set": {"email": "[email protected]", "name": "Alice", "signup_source": "google"}})
- ),
- datetime(2023, 1, 1, 10, 0, 0),
- "$set",
- ),
- # Day 2: Profile completion
- (
- json.dumps(
- json.dumps(
- {
- "$set": {
- "name": "Alice Johnson",
- "age": 28,
- "occupation": "Software Engineer",
- "profile_complete": True,
- }
- }
- )
- ),
- datetime(2023, 1, 2, 14, 30, 0),
- "$set",
- ),
- # Day 3: Location update
- (
- json.dumps(
- json.dumps({"$set": {"city": "San Francisco", "state": "CA", "timezone": "America/Los_Angeles"}})
- ),
- datetime(2023, 1, 3, 9, 15, 0),
- "$set",
- ),
- # Day 4: Preferences update
- (
- json.dumps(
- json.dumps({"$set": {"newsletter_subscribed": True, "preferred_language": "en", "theme": "dark"}})
- ),
- datetime(2023, 1, 4, 16, 45, 0),
- "$set",
- ),
- ]
-
- # Mock sync_execute to filter events based on timestamp parameter
- def mock_query_with_timestamp_filter(query, params, settings=None):
- from datetime import datetime
-
- # Parse the timestamp parameter
- timestamp_str = params["timestamp"]
- query_timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
-
- # Filter events based on the timestamp
- filtered_events = []
- for event_props, event_timestamp, event_type in mock_events:
- if event_timestamp <= query_timestamp:
- filtered_events.append((event_props, event_timestamp, event_type))
-
- return filtered_events
-
- mock_sync_execute.side_effect = mock_query_with_timestamp_filter
-
- # Test: What were Alice's properties at the end of Day 2?
- day_2_end = datetime(2023, 1, 2, 23, 59, 59, tzinfo=UTC)
- properties_day_2 = build_person_properties_at_time(1, day_2_end, ["alice123"])
-
- expected_day_2 = {
- "email": "[email protected]",
- "name": "Alice Johnson", # Updated from "Alice"
- "signup_source": "google",
- "age": 28,
- "occupation": "Software Engineer",
- "profile_complete": True,
- }
- self.assertEqual(properties_day_2, expected_day_2)
-
- # Test: What were Alice's properties at the end of Day 3?
- day_3_end = datetime(2023, 1, 3, 23, 59, 59, tzinfo=UTC)
- properties_day_3 = build_person_properties_at_time(1, day_3_end, ["alice123"])
-
- expected_day_3 = {
- **expected_day_2, # Everything from Day 2
- "city": "San Francisco",
- "state": "CA",
- "timezone": "America/Los_Angeles",
- }
- self.assertEqual(properties_day_3, expected_day_3)
-
- @patch("posthog.models.person.point_in_time_properties.sync_execute")
- def test_set_once_behavior_demonstration(self, mock_sync_execute):
- """
- Demonstrate how $set_once operations work compared to regular $set operations.
- """
-
- # Scenario: A user has both $set and $set_once events
- # $set_once should only set properties that haven't been set before
- # ClickHouse toJSONString() returns double-encoded JSON
- mock_events = [
- # Initial user creation with $set_once (common pattern)
- (
- json.dumps(
- json.dumps(
- {
- "$set_once": {
- "first_seen": "2023-01-01",
- "signup_source": "organic",
- "initial_referrer": "https://google.com",
- }
- }
- )
- ),
- datetime(2023, 1, 1, 10, 0, 0),
- "$set_once",
- ),
- # Later signup completion with $set
- (
- json.dumps(json.dumps({"$set": {"name": "Bob Smith", "email": "[email protected]"}})),
- datetime(2023, 1, 1, 10, 5, 0),
- "$set",
- ),
- # Attempt to overwrite signup_source with $set_once (should fail)
- (
- json.dumps(
- json.dumps(
- {
- "$set_once": {
- "signup_source": "facebook", # Should NOT overwrite
- "utm_campaign": "winter_2023", # Should set (new property)
- }
- }
- )
- ),
- datetime(2023, 1, 1, 10, 10, 0),
- "$set_once",
- ),
- # Update signup_source with regular $set (should work)
- (
- json.dumps(
- json.dumps(
- {
- "$set": {
- "signup_source": "facebook" # Should overwrite
- }
- }
- )
- ),
- datetime(2023, 1, 1, 10, 15, 0),
- "$set",
- ),
- ]
-
- # Mock sync_execute to filter events based on timestamp parameter
- def mock_query_with_timestamp_filter_set_once(query, params, settings=None):
- from datetime import datetime
-
- # Parse the timestamp parameter
- timestamp_str = params["timestamp"]
- query_timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
-
- # Filter events based on the timestamp
- filtered_events = []
- for event_props, event_timestamp, event_type in mock_events:
- if event_timestamp <= query_timestamp:
- filtered_events.append((event_props, event_timestamp, event_type))
-
- return filtered_events
-
- mock_sync_execute.side_effect = mock_query_with_timestamp_filter_set_once
-
- # Test the final state
- final_timestamp = datetime(2023, 1, 1, 12, 0, 0, tzinfo=UTC)
- properties = build_person_properties_at_time(1, final_timestamp, ["bob123"], include_set_once=True)
-
- expected = {
- "first_seen": "2023-01-01",
- "signup_source": "facebook", # Overwritten by $set, not $set_once
- "initial_referrer": "https://google.com",
- "name": "Bob Smith",
- "email": "[email protected]",
- "utm_campaign": "winter_2023", # Set by $set_once since it was new
- }
-
- self.assertEqual(properties, expected)
+class TestPointInTimePropertiesClickhouse(ClickhouseTestMixin, BaseTest):
+ """Hits the real ClickHouse query — guards against SQL typos and the
+ column-order / ORDER-BY-through-UNION-ALL pitfalls."""
+
+ def test_chronological_set_resolution(self):
+ distinct_id = "user-clickhouse-chrono"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ # Two $set events on the same key, written non-chronologically (later
+ # event inserted first) — the production query must sort to give the
+ # later value precedence.
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"name": "Final"}},
+ timestamp=upper_bound - timedelta(hours=1),
+ )
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"name": "Initial", "email": "[email protected]"}},
+ timestamp=upper_bound - timedelta(hours=5),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ )
+
+ self.assertEqual(properties, {"name": "Final", "email": "[email protected]"})
+
+ def test_set_once_first_write_wins(self):
+ distinct_id = "user-clickhouse-set-once"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ _create_event(
+ event="$set_once",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set_once": {"first_seen": "2024-05-01"}},
+ timestamp=upper_bound - timedelta(hours=2),
+ )
+ _create_event(
+ event="$set_once",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set_once": {"first_seen": "2024-05-15"}},
+ timestamp=upper_bound - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ include_set_once=True,
+ )
+
+ self.assertEqual(properties, {"first_seen": "2024-05-01"})
+
+ def test_set_then_set_once_interleaving(self):
+ """Mixed $set and $set_once events: $set always wins on its key, while
+ $set_once only sticks for keys never set by anything else."""
+ distinct_id = "user-clickhouse-interleave"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ _create_event(
+ event="$set_once",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={
+ "$set_once": {
+ "first_seen": "2024-05-01",
+ "signup_source": "organic",
+ }
+ },
+ timestamp=upper_bound - timedelta(hours=4),
+ )
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"name": "Bob"}},
+ timestamp=upper_bound - timedelta(hours=3),
+ )
+ # Later $set overrides signup_source set by the earlier $set_once.
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"signup_source": "facebook"}},
+ timestamp=upper_bound - timedelta(hours=2),
+ )
+ # Later $set_once attempts to overwrite signup_source — must NOT win.
+ _create_event(
+ event="$set_once",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={
+ "$set_once": {
+ "signup_source": "twitter",
+ "utm_campaign": "winter",
+ }
+ },
+ timestamp=upper_bound - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ include_set_once=True,
+ )
+
+ self.assertEqual(
+ properties,
+ {
+ "first_seen": "2024-05-01",
+ "signup_source": "facebook",
+ "name": "Bob",
+ "utm_campaign": "winter",
+ },
+ )
+
+ def test_only_non_property_events_returns_not_existed(self):
+ # ``existed`` semantics: had any property-update event at or before timestamp.
+ # A $pageview that doesn't carry a $set blob is not a property event by this
+ # definition, so ``existed`` is False even though the person had activity.
+ # Upstream existence (Postgres row) is established by the caller, not here.
+ distinct_id = "user-clickhouse-pageview-only"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ _create_event(
+ event="$pageview",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"url": "https://example.com"},
+ timestamp=upper_bound - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ )
+
+ self.assertEqual(properties, {})
+
+ def test_no_events_returns_empty_properties(self):
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ ["user-clickhouse-nonexistent"],
+ )
+
+ self.assertEqual(properties, {})
+
+ def test_row_limit_truncates_oldest_first(self):
+ """When the property row count exceeds row_limit, the inner ORDER BY ASC + LIMIT
+ keeps the earliest rows. We assert that a property only present in the tail
+ beyond the limit does NOT make it into the result."""
+ distinct_id = "user-clickhouse-rowlimit"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+ row_limit = 5
+
+ # Insert row_limit + 1 chronologically-ordered events. The newest one
+ # sets a unique key that should be dropped because the LIMIT cuts it off.
+ for i in range(row_limit):
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {f"key_{i}": f"value_{i}"}},
+ timestamp=upper_bound - timedelta(hours=row_limit - i + 1),
+ )
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"truncated_key": "should_be_missing"}},
+ timestamp=upper_bound - timedelta(minutes=1),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ row_limit=row_limit,
+ )
+
+ for i in range(row_limit):
+ self.assertEqual(properties.get(f"key_{i}"), f"value_{i}")
+ self.assertNotIn("truncated_key", properties)
+
+ def test_happy_path_with_default_row_limit(self):
+ # Happy path with no explicit row_limit — confirms the default flows through.
+ distinct_id = "user-clickhouse-default-limit"
+ upper_bound = datetime(2024, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ _create_event(
+ event="$set",
+ team=self.team,
+ distinct_id=distinct_id,
+ properties={"$set": {"hello": "world"}},
+ timestamp=upper_bound - timedelta(hours=1),
+ )
+ flush_persons_and_events()
+
+ properties = build_person_properties_at_time(
+ self.team.pk,
+ upper_bound,
+ [distinct_id],
+ )
+
+ self.assertEqual(properties, {"hello": "world"})
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 8ac53ff0bc93..b8c67e8e4554 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -769,6 +769,94 @@ export interface FeatureFlagStatusResponseApi {
reason: string
}
+export interface FeatureFlagTestEvaluationRequestApi {
+ /** User distinct ID to test against (mutually exclusive with person_id) */
+ distinct_id?: string
+ /** Person ID to test against (mutually exclusive with distinct_id) */
+ person_id?: string
+ /**
+ * Optional point-in-time to evaluate the flag against — both flag conditions and person properties are reconstructed as they existed at that timestamp. ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. Naive timestamps (no timezone) are interpreted as UTC.
+ * @nullable
+ */
+ timestamp?: string | null
+ /** Groups for feature flag evaluation (JSON object, defaults to empty dict) */
+ groups?: unknown
+}
+
+/**
+ * Person properties at the time of evaluation (for historical evaluations)
+ */
+export type FeatureFlagTestEvaluationResponseApiPersonProperties = { [key: string]: unknown }
+
+export interface FeatureFlagConditionPropertyAnalysisApi {
+ /** Property key */
+ key: string
+ /** Comparison operator */
+ operator: string
+ /** Expected property value */
+ value: unknown
+ /** Property type (person, group, etc.) */
+ type: string
+ /** Actual property value from user */
+ actual_value: unknown | null
+ /** Whether this property condition matched */
+ matched: boolean
+ /** Human-readable explanation of the match result */
+ explanation: string
+}
+
+export interface FeatureFlagConditionAnalysisApi {
+ /** Index of this condition in the feature flag */
+ index: number
+ /** True when this condition was the one that determined the flag's outcome. Use this to find the winning condition — at most one condition per flag is True. */
+ matched: boolean
+ /** True when every property in this condition evaluated to true, regardless of whether this condition was the eventual winner. */
+ properties_matched?: boolean
+ /** Human-readable explanation of why this condition matched/didn't match */
+ explanation: string
+ /** Rollout percentage for this condition (0.0-100.0) */
+ rollout_percentage: number
+ /** Whether this condition matched properties but was excluded due to rollout */
+ rollout_excluded: boolean
+ /**
+ * Variant associated with this condition
+ * @nullable
+ */
+ variant: string | null
+ /** Analysis of each property in this condition */
+ properties: FeatureFlagConditionPropertyAnalysisApi[]
+}
+
+export interface FeatureFlagTestEvaluationResponseApi {
+ /** Feature flag key */
+ flag_key: string
+ /** The evaluated value of the feature flag (boolean or variant key string) */
+ result: unknown
+ /** The reason for the evaluation result */
+ reason: string
+ /**
+ * The index of the condition that matched, if applicable
+ * @nullable
+ */
+ condition_index: number | null
+ /** Payload associated with the flag result, if any */
+ payload: unknown | null
+ /** Person properties at the time of evaluation (for historical evaluations) */
+ person_properties: FeatureFlagTestEvaluationResponseApiPersonProperties
+ /**
+ * The distinct_id used for rollout/variant bucketing. Echoes the caller-provided distinct_id when one was sent; null on the person_id path so the endpoint doesn't leak the person's other distinct_ids to a feature_flag:read-only token.
+ * @nullable
+ */
+ evaluation_distinct_id: string | null
+ /** Detailed analysis of each condition in the feature flag */
+ conditions: FeatureFlagConditionAnalysisApi[]
+}
+
+export interface ErrorResponseApi {
+ /** Error message */
+ error: string
+}
+
export type FeatureFlagVersionResponseApiFilters = { [key: string]: unknown }
/**
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 6da7bcf7c1e2..67d94c31ca3a 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -18,6 +18,8 @@ import type {
FeatureFlagApi,
FeatureFlagCreateRequestSchemaApi,
FeatureFlagStatusResponseApi,
+ FeatureFlagTestEvaluationRequestApi,
+ FeatureFlagTestEvaluationResponseApi,
FeatureFlagVersionResponseApi,
FeatureFlagsActivityRetrieveParams,
FeatureFlagsAllActivityRetrieveParams,
@@ -384,6 +386,31 @@ export const featureFlagsStatusRetrieve = async (
})
}
+/**
+ * Test feature flag evaluation against a specific user at an optional point in time.
+
+This endpoint allows testing how a feature flag would evaluate for a specific user,
+optionally at a historical timestamp. When a timestamp is provided, both the flag
+conditions and person properties are evaluated as they existed at that time.
+ */
+export const getFeatureFlagsTestEvaluationCreateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/feature_flags/${id}/test_evaluation/`
+}
+
+export const featureFlagsTestEvaluationCreate = async (
+ projectId: string,
+ id: number,
+ featureFlagTestEvaluationRequestApi: FeatureFlagTestEvaluationRequestApi,
+ options?: RequestInit
+): Promise<FeatureFlagTestEvaluationResponseApi> => {
+ return apiMutator<FeatureFlagTestEvaluationResponseApi>(getFeatureFlagsTestEvaluationCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(featureFlagTestEvaluationRequestApi),
+ })
+}
+
/**
* Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 20b9528419e2..860e406e4f3c 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -947,6 +947,31 @@ export const FeatureFlagsEnrichUsageDashboardCreateBody = /* @__PURE__ */ zod
})
.describe('Serializer mixin that handles tags for objects.')
+/**
+ * Test feature flag evaluation against a specific user at an optional point in time.
+
+This endpoint allows testing how a feature flag would evaluate for a specific user,
+optionally at a historical timestamp. When a timestamp is provided, both the flag
+conditions and person properties are evaluated as they existed at that time.
+ */
+export const FeatureFlagsTestEvaluationCreateBody = /* @__PURE__ */ zod.object({
+ distinct_id: zod
+ .string()
+ .optional()
+ .describe('User distinct ID to test against (mutually exclusive with person_id)'),
+ person_id: zod.string().optional().describe('Person ID to test against (mutually exclusive with distinct_id)'),
+ timestamp: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'Optional point-in-time to evaluate the flag against — both flag conditions and person properties are reconstructed as they existed at that timestamp. ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. Naive timestamps (no timezone) are interpreted as UTC.'
+ ),
+ groups: zod
+ .unknown()
+ .optional()
+ .describe('Groups for feature flag evaluation (JSON object, defaults to empty dict)'),
+})
+
/**
* Bulk delete feature flags by filter criteria or explicit IDs.
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 0ddc847bb9aa..54802eb87ac9 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -192,6 +192,9 @@ tools:
description: >
Check the health and evaluation status of a feature flag by ID. Returns a status (active, stale, deleted, or
unknown) and a human-readable reason explaining the status.
+ feature-flags-test-evaluation-create:
+ operation: feature_flags_test_evaluation_create
+ enabled: false
feature-flags-update:
operation: feature_flags_update
enabled: false
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index c33be0e79f6f..0d0c5cd7bb81 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -324,29 +324,6 @@ export interface PersonPropertiesAtTimeMetadataApi {
distinct_ids_count: number
}
-/**
- * The parameters passed to the query
- */
-export type PersonPropertiesAtTimeDebugApiParams = { [key: string]: unknown }
-
-export type PersonPropertiesAtTimeDebugApiEventsItem = { [key: string]: unknown }
-
-/**
- * Serializer for the debug information (only available to staff users).
- */
-export interface PersonPropertiesAtTimeDebugApi {
- /** The ClickHouse query that was executed */
- query: string
- /** The parameters passed to the query */
- params: PersonPropertiesAtTimeDebugApiParams
- /** Number of events found */
- events_found: number
- /** Raw events that were used to build the properties */
- events: PersonPropertiesAtTimeDebugApiEventsItem[]
- /** Error message if debug query failed */
- error?: string
-}
-
/**
* Serializer for the point-in-time person properties response.
*/
@@ -370,8 +347,6 @@ export interface PersonPropertiesAtTimeResponseApi {
last_seen_at: string | null
/** Metadata about the point-in-time query */
point_in_time_metadata: PersonPropertiesAtTimeMetadataApi
- /** Debug information (only available when debug=true and DEBUG=True) */
- debug?: PersonPropertiesAtTimeDebugApi
}
export type PersonsListParams = {
@@ -661,10 +636,6 @@ export const PersonsLifecycleRetrieveFormat = {
} as const
export type PersonsPropertiesAtTimeRetrieveParams = {
- /**
- * Whether to include debug information with raw events (only works when DEBUG=True, default: false)
- */
- debug?: boolean
/**
* The distinct_id of the person (mutually exclusive with person_id)
*/
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index 1c3d18350557..8a11730154ca 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -736,7 +736,6 @@ Query parameters:
- distinct_id: The distinct_id of the person
- timestamp: ISO datetime string for the point in time (e.g., "2023-06-15T14:30:00Z")
- include_set_once: Whether to handle $set_once operations (default: false)
-- debug: Whether to include debug information with raw events (default: false)
*/
export const getPersonsPropertiesAtTimeRetrieveUrl = (
projectId: string,
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 38c0c41dd2df..d9d609ec6123 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -52,7 +52,6 @@ from .repository_readiness import compute_repository_readiness
from .serializers import (
CodeInviteRedeemRequestSerializer,
ConnectionTokenResponseSerializer,
- ErrorResponseSerializer,
RepositoryReadinessQuerySerializer,
RepositoryReadinessResponseSerializer,
SandboxEnvironmentListSerializer,
@@ -477,7 +476,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskStagedArtifactsPrepareUploadResponseSerializer,
description="Prepared staged uploads for the requested artifacts",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid artifact payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
404: OpenApiResponse(description="Task not found"),
},
summary="Prepare staged direct uploads for task attachments",
@@ -508,7 +507,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if not presigned_post:
return Response(
- ErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
+ TaskRunErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -539,7 +538,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskStagedArtifactsFinalizeUploadResponseSerializer,
description="Finalized staged artifacts available for the next task run",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid artifact payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
404: OpenApiResponse(description="Task not found"),
},
summary="Finalize staged direct uploads for task attachments",
@@ -563,21 +562,21 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
storage_path = artifact["storage_path"]
if not storage_path.startswith(artifact_prefix) or f"/{artifact_id}/" not in storage_path:
return Response(
- ErrorResponseSerializer({"error": "Artifact storage path is invalid for this task"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact storage path is invalid for this task"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
s3_object = object_storage.head_object(storage_path)
if not s3_object:
return Response(
- ErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
content_length = s3_object.get("ContentLength")
if not isinstance(content_length, int):
return Response(
- ErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -590,7 +589,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if content_length > max_size_bytes:
return Response(
- ErrorResponseSerializer(
+ TaskRunErrorResponseSerializer(
{"error": build_task_run_artifact_size_error(safe_name, max_size_bytes)}
).data,
status=status.HTTP_400_BAD_REQUEST,
@@ -1025,7 +1024,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request_serializer=TaskRunStartRequestSerializer,
responses={
200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid start payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid start payload"),
404: OpenApiResponse(description="Task run not found"),
},
summary="Start task run",
@@ -1041,12 +1040,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if task_run.environment != TaskRun.Environment.CLOUD:
return Response(
- ErrorResponseSerializer({"error": "Only cloud runs can be started via this endpoint"}).data,
+ TaskRunErrorResponseSerializer({"error": "Only cloud runs can be started via this endpoint"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
if task_run.status not in startable_statuses:
return Response(
- ErrorResponseSerializer(
+ TaskRunErrorResponseSerializer(
{
"error": f"Only queued or not_started cloud runs can be started (current status: {task_run.status})"
}
@@ -1099,7 +1098,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request_serializer=TaskRunUpdateSerializer,
responses={
200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid update data"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
404: OpenApiResponse(description="Task run not found"),
},
summary="Update task run",
@@ -1113,7 +1112,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request_serializer=TaskRunUpdateSerializer,
responses={
200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid update data"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
404: OpenApiResponse(description="Task run not found"),
},
summary="Update task run",
@@ -1391,7 +1390,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
jsonschema.validate(instance=output_data, schema=task.json_schema)
except jsonschema.ValidationError as e:
return Response(
- ErrorResponseSerializer({"error": f"Output validation error: {e.message}"}).data,
+ TaskRunErrorResponseSerializer({"error": f"Output validation error: {e.message}"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
task_run.output = output_data
@@ -1408,7 +1407,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request_serializer=TaskRunAppendLogRequestSerializer,
responses={
200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run with updated log"),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid log entries"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid log entries"),
404: OpenApiResponse(description="Run not found"),
},
summary="Append log entries",
@@ -1481,7 +1480,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
extra={"run_id": str(task_run.id)},
)
return Response(
- ErrorResponseSerializer({"error": "Failed to queue Slack relay"}).data,
+ TaskRunErrorResponseSerializer({"error": "Failed to queue Slack relay"}).data,
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
return Response({"status": "accepted", "relay_id": relay_id})
@@ -1493,7 +1492,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskRunArtifactsUploadResponseSerializer,
description="Run with updated artifact manifest",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid artifact payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
404: OpenApiResponse(description="Run not found"),
},
summary="Upload artifacts for a task run",
@@ -1567,7 +1566,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskRunArtifactsPrepareUploadResponseSerializer,
description="Prepared uploads for the requested artifacts",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid artifact payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
404: OpenApiResponse(description="Run not found"),
},
summary="Prepare direct uploads for task run artifacts",
@@ -1601,7 +1600,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if not presigned_post:
return Response(
- ErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
+ TaskRunErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1632,7 +1631,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskRunArtifactsFinalizeUploadResponseSerializer,
description="Run with updated artifact manifest",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid artifact payload"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
404: OpenApiResponse(description="Run not found"),
},
summary="Finalize direct uploads for task run artifacts",
@@ -1659,7 +1658,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not storage_path.startswith(artifact_prefix) or f"/{artifact_id[:8]}_" not in storage_path:
return Response(
- ErrorResponseSerializer({"error": "Artifact storage path is invalid for this run"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact storage path is invalid for this run"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1676,7 +1675,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
s3_object = object_storage.head_object(storage_path)
if not s3_object:
return Response(
- ErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1685,7 +1684,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
content_length = s3_object.get("ContentLength")
if not isinstance(content_length, int):
return Response(
- ErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1696,7 +1695,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if content_length > max_size_bytes:
return Response(
- ErrorResponseSerializer(
+ TaskRunErrorResponseSerializer(
{"error": build_task_run_artifact_size_error(safe_name, max_size_bytes)}
).data,
status=status.HTTP_400_BAD_REQUEST,
@@ -1734,7 +1733,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
response=TaskRunArtifactPresignResponseSerializer,
description="Presigned URL for the requested artifact",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid request"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
404: OpenApiResponse(description="Artifact not found"),
},
summary="Generate presigned URL for an artifact",
@@ -1754,14 +1753,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not any(artifact.get("storage_path") == storage_path for artifact in artifacts):
return Response(
- ErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
status=status.HTTP_404_NOT_FOUND,
)
url = object_storage.get_presigned_url(storage_path)
if not url:
return Response(
- ErrorResponseSerializer({"error": "Unable to generate download URL"}).data,
+ TaskRunErrorResponseSerializer({"error": "Unable to generate download URL"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1775,7 +1774,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
200: OpenApiResponse(
description="Artifact content",
),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Invalid request"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
404: OpenApiResponse(description="Artifact not found"),
},
summary="Download an artifact through the backend",
@@ -1799,7 +1798,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if artifact is None:
return Response(
- ErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
status=status.HTTP_404_NOT_FOUND,
)
@@ -1814,13 +1813,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
},
)
return Response(
- ErrorResponseSerializer({"error": "Unable to read artifact"}).data,
+ TaskRunErrorResponseSerializer({"error": "Unable to read artifact"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
if content is None:
return Response(
- ErrorResponseSerializer({"error": "Artifact content not found"}).data,
+ TaskRunErrorResponseSerializer({"error": "Artifact content not found"}).data,
status=status.HTTP_404_NOT_FOUND,
)
@@ -1906,11 +1905,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
description="Agent server response",
),
400: OpenApiResponse(
- response=ErrorResponseSerializer,
+ response=TaskRunErrorResponseSerializer,
description="Invalid command or no active sandbox",
),
404: OpenApiResponse(description="Task run not found"),
- 502: OpenApiResponse(response=ErrorResponseSerializer, description="Agent server unreachable"),
+ 502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),
},
summary="Send command to agent server",
description="Forward a JSON-RPC command to the agent server running in the sandbox. "
@@ -1929,14 +1928,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if not run_state.sandbox_url:
return Response(
- ErrorResponseSerializer({"error": "No active sandbox for this task run"}).data,
+ TaskRunErrorResponseSerializer({"error": "No active sandbox for this task run"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
if not self._is_valid_sandbox_url(run_state.sandbox_url):
logger.warning(f"Blocked request to disallowed sandbox URL for task run {task_run.id}")
return Response(
- ErrorResponseSerializer({"error": "Invalid sandbox URL"}).data,
+ TaskRunErrorResponseSerializer({"error": "Invalid sandbox URL"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -1997,26 +1996,26 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
error_msg = error_body.get("error", f"Agent server returned {agent_response.status_code}")
return Response(
- ErrorResponseSerializer({"error": error_msg}).data,
+ TaskRunErrorResponseSerializer({"error": error_msg}).data,
status=status.HTTP_502_BAD_GATEWAY,
)
except http_requests.ConnectionError:
logger.warning(f"Agent server unreachable for task run {task_run.id}")
return Response(
- ErrorResponseSerializer({"error": "Agent server is not reachable"}).data,
+ TaskRunErrorResponseSerializer({"error": "Agent server is not reachable"}).data,
status=status.HTTP_502_BAD_GATEWAY,
)
except http_requests.Timeout:
logger.warning(f"Agent server request timed out for task run {task_run.id}")
return Response(
- ErrorResponseSerializer({"error": "Agent server request timed out"}).data,
+ TaskRunErrorResponseSerializer({"error": "Agent server request timed out"}).data,
status=status.HTTP_504_GATEWAY_TIMEOUT,
)
except Exception:
logger.exception(f"Failed to proxy command to agent server for task run {task_run.id}")
return Response(
- ErrorResponseSerializer({"error": "Failed to send command to agent server"}).data,
+ TaskRunErrorResponseSerializer({"error": "Failed to send command to agent server"}).data,
status=status.HTTP_502_BAD_GATEWAY,
)
@@ -2176,7 +2175,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@validated_request(
responses={
200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run resumed in cloud"),
- 400: OpenApiResponse(response=ErrorResponseSerializer, description="Run already active or workflow failed"),
+ 400: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Run already active or workflow failed"
+ ),
},
summary="Resume task run in cloud",
description="Resume an existing task run in a cloud sandbox. Terminates any existing workflow and starts a new one.",
@@ -2216,7 +2217,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if is_cloud_active:
return Response(
- ErrorResponseSerializer({"error": "Run is already active in cloud"}).data,
+ TaskRunErrorResponseSerializer({"error": "Run is already active in cloud"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -2283,7 +2284,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
task_run.publish_stream_state_event()
return Response(
- ErrorResponseSerializer({"error": "Failed to start cloud workflow"}).data,
+ TaskRunErrorResponseSerializer({"error": "Failed to start cloud workflow"}).data,
status=status.HTTP_502_BAD_GATEWAY,
)
@@ -2420,7 +2421,7 @@ class CodeInviteViewSet(viewsets.ViewSet):
responses={
200: OpenApiResponse(description="Invite code redeemed successfully"),
400: OpenApiResponse(
- response=ErrorResponseSerializer,
+ response=TaskRunErrorResponseSerializer,
description="Invalid or expired invite code",
),
},
@@ -2435,7 +2436,7 @@ class CodeInviteViewSet(viewsets.ViewSet):
invite_code = CodeInvite.objects.get(code__iexact=code_str)
except CodeInvite.DoesNotExist:
return Response(
- ErrorResponseSerializer({"error": "Invalid invite code"}).data,
+ TaskRunErrorResponseSerializer({"error": "Invalid invite code"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
@@ -2447,7 +2448,7 @@ class CodeInviteViewSet(viewsets.ViewSet):
if not invite_code.is_redeemable:
return Response(
- ErrorResponseSerializer({"error": "This invite code is no longer valid"}).data,
+ TaskRunErrorResponseSerializer({"error": "This invite code is no longer valid"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.py
index e852ca848d92..b3ba73e81219 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -461,10 +461,6 @@ class TaskRunSetOutputRequestSerializer(serializers.Serializer):
)
-class ErrorResponseSerializer(serializers.Serializer):
- error = serializers.CharField(help_text="Error message")
-
-
class TaskRunErrorResponseSerializer(serializers.Serializer):
detail = serializers.CharField(required=False, help_text="Human-readable validation error")
error = serializers.CharField(required=False, help_text="Human-readable error message")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 5542d5aa4b8c..9983249ca7ef 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -12,9 +12,19 @@ export interface CodeInviteRedeemRequestApi {
code: string
}
-export interface ErrorResponseApi {
- /** Error message */
- error: string
+export interface TaskRunErrorResponseApi {
+ /** Human-readable validation error */
+ detail?: string
+ /** Human-readable error message */
+ error?: string
+ /** Machine-readable error type */
+ type?: string
+ /** Machine-readable error code */
+ code?: string
+ /** Request field associated with the error */
+ attr?: string
+ /** Artifact ids that could not be resolved for the run */
+ missing_artifact_ids?: string[]
}
/**
@@ -591,21 +601,6 @@ export type TaskRunCreateRequestSchemaApi =
| CodexTaskRunCreateSchemaApi
| TaskRunResumeRequestSchemaApi
-export interface TaskRunErrorResponseApi {
- /** Human-readable validation error */
- detail?: string
- /** Human-readable error message */
- error?: string
- /** Machine-readable error type */
- type?: string
- /** Machine-readable error code */
- code?: string
- /** Request field associated with the error */
- attr?: string
- /** Artifact ids that could not be resolved for the run */
- missing_artifact_ids?: string[]
-}
-
/**
* * `plan` - plan
* `context` - context
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 663a74835437..491bb5b50c1a 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3387,6 +3387,7 @@ dependencies = [
"sha2",
"sqlx",
"strum 0.28.0",
+ "subtle",
"test-case",
"thiserror 2.0.18",
"tokio",
diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.toml
index ebc5599c7eea..484a1eece66e 100644
--- a/rust/feature-flags/Cargo.toml
+++ b/rust/feature-flags/Cargo.toml
@@ -68,6 +68,7 @@ tracing-opentelemetry = { workspace = true }
tokio-retry = "0.3"
serde-pickle = { version = "1.1.1" }
semver = "1.0.28"
+subtle = "2.6"
[features]
# Gated to keep the AWS SDK, clap, and common-s3 out of library/server builds.
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rs
index a4b9f455bd0d..3aa169c90cda 100644
--- a/rust/feature-flags/src/api/endpoint.rs
+++ b/rust/feature-flags/src/api/endpoint.rs
@@ -620,6 +620,8 @@ mod tests {
lib_version: None,
sent_at: None,
only_evaluate_survey_feature_flags: None,
+ detailed_analysis: None,
+ only_use_override_person_properties: None,
};
if params_both_none.version.is_none() && params_both_none.config.is_none() {
@@ -638,6 +640,8 @@ mod tests {
lib_version: None,
sent_at: None,
only_evaluate_survey_feature_flags: None,
+ detailed_analysis: None,
+ only_use_override_person_properties: None,
};
if params_version_missing.version.is_none() && params_version_missing.config.is_none() {
@@ -654,6 +658,8 @@ mod tests {
config: None,
compression: None,
lib_version: None,
+ detailed_analysis: None,
+ only_use_override_person_properties: None,
sent_at: None,
only_evaluate_survey_feature_flags: None,
};
diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rs
index 7aa5147e9bf0..c6f92857ee22 100644
--- a/rust/feature-flags/src/api/types.rs
+++ b/rust/feature-flags/src/api/types.rs
@@ -2,11 +2,20 @@ use crate::api::errors::FlagError;
use crate::flags::flag_match_reason::FeatureFlagMatchReason;
use crate::flags::flag_matching::FeatureFlagMatch;
use crate::flags::flag_models::FeatureFlag;
+use crate::properties::property_matching::match_property;
+use crate::properties::property_models::OperatorType;
use serde::{de, Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::{collections::HashMap, fmt, str::FromStr};
use uuid::Uuid;
+fn format_operator_explanation(key: &str, op_label: &str, value: &Option<Value>) -> String {
+ match value {
+ Some(v) => format!("Property '{}' {} {}", key, op_label, v),
+ None => format!("Property '{}' {} (empty)", key, op_label),
+ }
+}
+
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum FlagsResponseCode {
Ok = 1,
@@ -97,9 +106,20 @@ pub struct FlagsQueryParams {
/// e.g. https://us.posthog.com/flags?v=2&config=true
#[serde(default, deserialize_with = "deserialize_optional_bool")]
pub config: Option<bool>,
+ /// Optional boolean indicating whether to include detailed condition analysis in the response
+ /// When true, returns detailed information about why each condition matched or didn't match
+ /// e.g. https://us.posthog.com/flags?v=2&detailed_analysis=true
+ #[serde(default, deserialize_with = "deserialize_optional_bool")]
+ pub detailed_analysis: Option<bool>,
+ /// Optional boolean indicating whether to only use person properties from the request payload
+ /// When true, ignores person properties from the database and only uses properties from person_properties field
+ /// Useful for historical evaluation at specific timestamps
+ /// e.g. https://us.posthog.com/flags?v=2&only_use_override_person_properties=true
+ #[serde(default, deserialize_with = "deserialize_optional_bool")]
+ pub only_use_override_person_properties: Option<bool>,
}
-#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ServiceResponse {
Default(LegacyFlagsResponse),
@@ -175,7 +195,7 @@ impl ConfigResponse {
}
}
-#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FlagsResponse {
/// Whether any errors occurred while evaluating feature flags.
@@ -350,7 +370,37 @@ pub struct FlagsOptionsResponse {
pub status: FlagsResponseCode,
}
-#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
+pub struct PropertyAnalysis {
+ pub key: String,
+ pub operator: String,
+ pub value: Value,
+ pub r#type: String,
+ pub actual_value: Option<Value>,
+ pub matched: bool,
+ pub explanation: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
+pub struct ConditionAnalysis {
+ pub index: i32,
+ pub properties: Vec<PropertyAnalysis>,
+ pub rollout_percentage: f64,
+ pub variant: Option<String>,
+ /// True when this condition was the one that won (i.e. determined the
+ /// flag's enabled/variant outcome). Use this to find the winning condition
+ /// in a list — it is guaranteed to be set on at most one condition per flag.
+ pub matched: bool,
+ /// True when every property in this condition evaluated to true,
+ /// regardless of whether this condition was the eventual winner. A later
+ /// condition may have won, an earlier one may have short-circuited the
+ /// evaluation, or rollout may have excluded this condition entirely.
+ pub properties_matched: bool,
+ pub rollout_excluded: bool,
+ pub explanation: String,
+}
+
+#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct FlagDetails {
pub key: String,
pub enabled: bool,
@@ -359,6 +409,9 @@ pub struct FlagDetails {
pub failed: bool,
pub reason: FlagEvaluationReason,
pub metadata: FlagDetailsMetadata,
+ /// Optional detailed condition analysis, only included when requested
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub conditions: Option<Vec<ConditionAnalysis>>,
}
impl FlagDetails {
@@ -397,12 +450,27 @@ pub struct FlagEvaluationReason {
pub trait FromFeatureAndMatch {
fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self;
+ fn create_with_analysis(
+ flag: &FeatureFlag,
+ flag_match: &FeatureFlagMatch,
+ detailed_analysis: bool,
+ property_values: Option<&HashMap<String, Value>>,
+ ) -> Self;
fn create_error(flag: &FeatureFlag, error: &FlagError, condition_index: Option<i32>) -> Self;
fn get_reason_description(match_info: &FeatureFlagMatch) -> Option<String>;
}
impl FromFeatureAndMatch for FlagDetails {
fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self {
+ Self::create_with_analysis(flag, flag_match, false, None)
+ }
+
+ fn create_with_analysis(
+ flag: &FeatureFlag,
+ flag_match: &FeatureFlagMatch,
+ detailed_analysis: bool,
+ property_values: Option<&HashMap<String, Value>>,
+ ) -> Self {
FlagDetails {
key: flag.key.clone(),
enabled: flag_match.matches,
@@ -419,6 +487,15 @@ impl FromFeatureAndMatch for FlagDetails {
description: None,
payload: flag_match.payload.clone(),
},
+ conditions: if detailed_analysis {
+ Some(Self::build_condition_analysis(
+ flag,
+ flag_match,
+ property_values,
+ ))
+ } else {
+ None
+ },
}
}
@@ -439,6 +516,7 @@ impl FromFeatureAndMatch for FlagDetails {
description: None,
payload: None,
},
+ conditions: None,
}
}
@@ -470,6 +548,189 @@ impl FromFeatureAndMatch for FlagDetails {
}
}
+impl FlagDetails {
+ fn build_condition_analysis(
+ flag: &FeatureFlag,
+ flag_match: &FeatureFlagMatch,
+ property_values: Option<&HashMap<String, Value>>,
+ ) -> Vec<ConditionAnalysis> {
+ let mut analyses = Vec::new();
+
+ // Analyze each property group (condition)
+ for (index, group) in flag.filters.groups.iter().enumerate() {
+ let mut property_analyses = Vec::new();
+ let mut condition_matched = false;
+
+ // Determine if this condition matched based on overall flag result and condition index
+ // Only mark as matched if the flag itself matched AND this is the matching condition
+ if flag_match.matches {
+ if let Some(condition_index) = flag_match.condition_index {
+ condition_matched = index == condition_index;
+ } else if matches!(flag_match.reason, FeatureFlagMatchReason::ConditionMatch) {
+ // Fallback: assume first condition matched if we have a condition match but no index
+ condition_matched = index == 0;
+ }
+ }
+ // If flag_match.matches is false, condition_matched remains false for all conditions
+
+ // Analyze properties within this group
+ if let Some(properties) = &group.properties {
+ for property in properties {
+ let operator_str = match property.operator {
+ Some(op) => format!("{:?}", op).to_lowercase(),
+ None => "exact".to_string(),
+ };
+
+ let type_str = match property.prop_type {
+ crate::properties::property_models::PropertyType::Person => "person",
+ crate::properties::property_models::PropertyType::Group => "group",
+ crate::properties::property_models::PropertyType::Cohort => "cohort",
+ crate::properties::property_models::PropertyType::Flag => "flag",
+ }
+ .to_string();
+
+ // Generate explanation placeholder - will be updated after we know if property matched
+ let explanation_placeholder = match property.operator {
+ Some(OperatorType::IsSet) => ("is set", "is not set"),
+ Some(OperatorType::IsNotSet) => ("is not set", "is set"),
+ Some(OperatorType::Exact) => ("equals", "does not equal"),
+ Some(OperatorType::IsNot) => ("does not equal", "equals"),
+ Some(OperatorType::Icontains) => ("contains", "does not contain"),
+ Some(OperatorType::NotIcontains) => ("does not contain", "contains"),
+ Some(OperatorType::Gt) => (">", "<="),
+ Some(OperatorType::Lt) => ("<", ">="),
+ Some(OperatorType::Gte) => (">=", "<"),
+ Some(OperatorType::Lte) => ("<=", ">"),
+ Some(OperatorType::In) => ("is in", "is not in"),
+ Some(OperatorType::NotIn) => ("is not in", "is in"),
+ Some(OperatorType::Regex) => ("matches regex", "does not match regex"),
+ Some(OperatorType::NotRegex) => ("does not match regex", "matches regex"),
+ _ => (operator_str.as_str(), "does not match"),
+ };
+
+ let (property_matched, actual_value) = if let Some(props) = property_values {
+ let actual = props.get(&property.key).cloned();
+ let matched = match_property(property, props, false).unwrap_or(false);
+ (matched, actual)
+ } else {
+ // No properties available, fall back to condition-level match
+ (condition_matched, None)
+ };
+
+ // Generate the correct explanation based on whether the property matched
+ let explanation = if property_matched {
+ match property.operator {
+ Some(OperatorType::IsSet) | Some(OperatorType::IsNotSet) => {
+ format!("Property '{}' {}", property.key, explanation_placeholder.0)
+ }
+ _ => format_operator_explanation(
+ &property.key,
+ explanation_placeholder.0,
+ &property.value,
+ ),
+ }
+ } else {
+ match property.operator {
+ Some(OperatorType::IsSet) | Some(OperatorType::IsNotSet) => {
+ format!("Property '{}' {}", property.key, explanation_placeholder.1)
+ }
+ _ => format_operator_explanation(
+ &property.key,
+ explanation_placeholder.1,
+ &property.value,
+ ),
+ }
+ };
+
+ let property_analysis = PropertyAnalysis {
+ key: property.key.clone(),
+ operator: operator_str,
+ value: property.value.clone().unwrap_or(serde_json::Value::Null),
+ r#type: type_str,
+ actual_value,
+ matched: property_matched,
+ explanation,
+ };
+ property_analyses.push(property_analysis);
+ }
+ }
+
+ // Determine rollout status and properties match status
+ let rollout_percentage = group.rollout_percentage.unwrap_or(100.0);
+ let is_zero_rollout = rollout_percentage == 0.0;
+
+ // Check if this condition has properties that would need to be evaluated
+ let has_properties = group
+ .properties
+ .as_ref()
+ .map(|props| !props.is_empty())
+ .unwrap_or(false);
+
+ // Determine if all properties in this condition actually matched
+ let all_properties_matched = if has_properties {
+ property_analyses.iter().all(|prop| prop.matched)
+ } else {
+ // If no properties, consider it a match (rollout-only condition)
+ true
+ };
+
+ // Key insight: Use the overall match reason to determine what happened
+ // If reason is OutOfRolloutBound, it means properties matched but rollout failed
+ let properties_matched_but_rollout_failed =
+ matches!(flag_match.reason, FeatureFlagMatchReason::OutOfRolloutBound);
+
+ // Determine if this specific condition was the one that got excluded by rollout
+ let this_condition_rollout_excluded = if properties_matched_but_rollout_failed {
+ // If overall reason is OutOfRolloutBound, check if this condition has matching index
+ if let Some(match_condition_index) = flag_match.condition_index {
+ // This condition was the one that matched properties but failed rollout
+ index == match_condition_index && is_zero_rollout
+ } else {
+ // No specific condition index, so could be this one if it has zero rollout
+ is_zero_rollout && all_properties_matched
+ }
+ } else {
+ // Overall reason is not OutOfRolloutBound, so use simple zero rollout check
+ is_zero_rollout && all_properties_matched
+ };
+
+ let explanation = if this_condition_rollout_excluded {
+ format!(
+ "Condition {} matched properties but was excluded by {}% rollout",
+ index, rollout_percentage
+ )
+ } else if all_properties_matched && condition_matched {
+ format!(
+ "Condition {} matched and passed {}% rollout",
+ index, rollout_percentage
+ )
+ } else if all_properties_matched && !condition_matched {
+ format!(
+ "Condition {} matched properties but was not evaluated due to an earlier condition matching",
+ index
+ )
+ } else {
+ format!("Condition {} did not match properties", index)
+ };
+
+ let analysis = ConditionAnalysis {
+ index: index as i32,
+ properties: property_analyses,
+ rollout_percentage,
+ variant: group.variant.clone(),
+ matched: condition_matched,
+ properties_matched: all_properties_matched,
+ rollout_excluded: this_condition_rollout_excluded,
+ explanation,
+ };
+
+ analyses.push(analysis);
+ }
+
+ analyses
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AnalyticsConfig {
@@ -733,6 +994,7 @@ mod tests {
description: None,
payload: Some(json!({"key": "value"})),
},
+ conditions: None,
},
);
@@ -755,6 +1017,7 @@ mod tests {
description: None,
payload: None,
},
+ conditions: None,
},
);
@@ -777,6 +1040,7 @@ mod tests {
description: None,
payload: Some(Value::Null),
},
+ conditions: None,
},
);
@@ -868,4 +1132,95 @@ mod tests {
assert!(evaluated_at >= before);
assert!(evaluated_at <= after);
}
+
+ #[test]
+ fn test_condition_analysis_properties_matched_can_diverge_from_matched() {
+ use crate::flags::flag_models::FeatureFlag;
+ use std::collections::HashMap;
+
+ // Create a flag with two conditions using JSON parsing (same pattern as other tests):
+ // Condition 0: properties match but rollout_percentage = 0 (no match)
+ // Condition 1: properties match and rollout_percentage = 100 (match)
+ let flag: FeatureFlag = serde_json::from_value(json!(
+ {
+ "id": 1,
+ "team_id": 1,
+ "name": "test-flag",
+ "key": "test-flag",
+ "active": true,
+ "filters": {
+ "groups": [
+ {
+ "properties": [
+ {
+ "key": "email",
+ "value": "[email protected]",
+ "type": "person"
+ }
+ ],
+ "rollout_percentage": 0
+ },
+ {
+ "properties": [
+ {
+ "key": "email",
+ "value": "[email protected]",
+ "type": "person"
+ }
+ ],
+ "rollout_percentage": 100
+ }
+ ]
+ }
+ }
+ ))
+ .unwrap();
+
+ // Create a flag match where condition 1 matched (index 1)
+ let flag_match = FeatureFlagMatch {
+ matches: true,
+ variant: None,
+ reason: FeatureFlagMatchReason::ConditionMatch,
+ condition_index: Some(1),
+ payload: None,
+ };
+
+ // Create property values that would match both conditions
+ let mut property_values = HashMap::new();
+ property_values.insert("email".to_string(), serde_json::json!("[email protected]"));
+
+ // Build condition analysis
+ let analysis =
+ FlagDetails::build_condition_analysis(&flag, &flag_match, Some(&property_values));
+
+ // Verify we have analysis for both conditions
+ assert_eq!(analysis.len(), 2);
+
+ // Condition 0: properties matched but overall condition did not match (rollout = 0%)
+ assert!(
+ analysis[0].properties_matched,
+ "Condition 0 should have properties_matched=true"
+ );
+ assert!(
+ !analysis[0].matched,
+ "Condition 0 should have matched=false due to 0% rollout"
+ );
+ assert_eq!(analysis[0].index, 0);
+ assert!(
+ analysis[0].rollout_excluded,
+ "Condition 0 should be rollout_excluded"
+ );
+
+ // Condition 1: properties matched and overall condition matched
+ assert!(
+ analysis[1].properties_matched,
+ "Condition 1 should have properties_matched=true"
+ );
+ assert!(analysis[1].matched, "Condition 1 should have matched=true");
+ assert_eq!(analysis[1].index, 1);
+ assert!(
+ !analysis[1].rollout_excluded,
+ "Condition 1 should not be rollout_excluded"
+ );
+ }
}
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 565b97934e53..c7e8d2292393 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -617,6 +617,11 @@ pub struct Config {
#[envconfig(from = "OPTIMIZE_EXPERIENCE_CONTINUITY_LOOKUPS", default = "true")]
pub optimize_experience_continuity_lookups: FlexBool,
+ // Internal request token for non-billable requests
+ // When provided via Authorization header and matches this token, the request is not billed
+ #[envconfig(from = "INTERNAL_REQUEST_TOKEN")]
+ pub internal_request_token: Option<String>,
+
// Redis compression configuration
// When enabled, uses zstd compression for Redis values above threshold
// The `default_test_config()` sets this to true for test/development scenarios.
@@ -926,6 +931,7 @@ impl Config {
skip_pg_team_fallback: FlexBool(false),
service_mode: ServiceMode::All,
auth_token_cache_ttl_seconds: 300,
+ internal_request_token: None,
billing_aggregator_enabled: FlexBool(false),
billing_flush_interval_ms: 10_000,
billing_max_pending_entries: 500_000,
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 67a162cc3155..4eb3185d57c6 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -338,6 +338,10 @@ pub struct FeatureFlagMatcher {
/// so the matcher skips the CohortCacheManager PG query entirely.
/// `None` means no preloaded data (PG fallback or old cache) — use CohortCacheManager.
preloaded_cohorts: Option<Arc<[Cohort]>>,
+ /// Whether to include detailed condition analysis in flag evaluation results.
+ detailed_analysis: bool,
+ /// Whether to only use person properties from request payload, ignoring database properties.
+ only_use_override_person_properties: bool,
}
/// Lightweight snapshot of a flag's identity fields, saved before moving
@@ -387,6 +391,8 @@ impl FeatureFlagMatcher {
filtered_out_flag_ids: HashSet::new(),
enable_realtime_cohort_evaluation: false,
preloaded_cohorts: None,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
}
}
@@ -418,6 +424,16 @@ impl FeatureFlagMatcher {
self
}
+ pub fn with_detailed_analysis(mut self, detailed_analysis: bool) -> Self {
+ self.detailed_analysis = detailed_analysis;
+ self
+ }
+
+ pub fn with_only_use_override_person_properties(mut self, only_use_override: bool) -> Self {
+ self.only_use_override_person_properties = only_use_override;
+ self
+ }
+
/// Evaluates all feature flags for the current matcher context.
///
/// ## Arguments
@@ -810,7 +826,7 @@ impl FeatureFlagMatcher {
&self.filtered_out_flag_ids,
);
- if flags_requiring_db_preparation.is_empty() {
+ if flags_requiring_db_preparation.is_empty() || self.only_use_override_person_properties {
self.flag_evaluation_state.skip_person_properties();
return false;
}
@@ -929,6 +945,7 @@ impl FeatureFlagMatcher {
&result,
&mut level_evaluated_flags_map,
&mut errors_while_computing_flags,
+ person_property_overrides,
);
});
}
@@ -950,6 +967,7 @@ impl FeatureFlagMatcher {
result,
&mut level_evaluated_flags_map,
&mut errors_while_computing_flags,
+ person_property_overrides,
);
}
}
@@ -977,13 +995,27 @@ impl FeatureFlagMatcher {
result: &Result<FeatureFlagMatch, FlagError>,
level_evaluated_flags_map: &mut HashMap<String, FlagDetails>,
errors_while_computing_flags: &mut bool,
+ person_property_overrides: &Option<HashMap<String, Value>>,
) {
match result {
Ok(flag_match) => {
self.flag_evaluation_state
.add_flag_evaluation_result(flag.id, flag_match.get_flag_value());
- level_evaluated_flags_map
- .insert(flag.key.clone(), FlagDetails::create(flag, flag_match));
+ let flag_details = if self.detailed_analysis {
+ // Use merged person properties (DB + overrides) for condition analysis
+ let merged_person_props = self
+ .get_person_properties(person_property_overrides.as_ref())
+ .ok();
+ FlagDetails::create_with_analysis(
+ flag,
+ flag_match,
+ true,
+ merged_person_props.as_ref(),
+ )
+ } else {
+ FlagDetails::create(flag, flag_match)
+ };
+ level_evaluated_flags_map.insert(flag.key.clone(), flag_details);
}
Err(e) => {
*errors_while_computing_flags = true;
@@ -1571,7 +1603,6 @@ impl FeatureFlagMatcher {
}
}
}
-
self.check_rollout(
feature_flag,
rollout_percentage,
@@ -1664,11 +1695,15 @@ impl FeatureFlagMatcher {
&self,
property_overrides: Option<&HashMap<String, Value>>,
) -> Result<HashMap<String, Value>, FlagError> {
- // Start with DB properties (clone only when we need a mutable copy)
- let mut merged_properties = self
- .get_person_properties_from_evaluation_state()
- .cloned()
- .unwrap_or_default();
+ let mut merged_properties = if self.only_use_override_person_properties {
+ // When only_use_override_person_properties is true, ignore DB properties entirely
+ HashMap::new()
+ } else {
+ // Start with DB properties (clone only when we need a mutable copy)
+ self.get_person_properties_from_evaluation_state()
+ .cloned()
+ .unwrap_or_default()
+ };
// Merge in overrides (overrides take precedence)
if let Some(overrides) = property_overrides {
diff --git a/rust/feature-flags/src/flags/flag_request.rs b/rust/feature-flags/src/flags/flag_request.rs
index afc86e3dcc5a..814074c9c56f 100644
--- a/rust/feature-flags/src/flags/flag_request.rs
+++ b/rust/feature-flags/src/flags/flag_request.rs
@@ -86,6 +86,8 @@ pub struct FlagRequest {
pub evaluation_contexts: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evaluation_runtime: Option<EvaluationRuntime>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub override_flags_definitions: Option<HashMap<String, Value>>,
}
impl FlagRequest {
diff --git a/rust/feature-flags/src/handler/authentication.rs b/rust/feature-flags/src/handler/authentication.rs
index c329c00df6d2..8c6529d89bec 100644
--- a/rust/feature-flags/src/handler/authentication.rs
+++ b/rust/feature-flags/src/handler/authentication.rs
@@ -1,3 +1,5 @@
+use axum::http::HeaderMap;
+
use crate::{
api::errors::FlagError,
flags::{flag_request::FlagRequest, flag_service::FlagService},
@@ -23,3 +25,155 @@ pub async fn parse_and_authenticate(
Ok((distinct_id, team, request))
}
+
+/// Checks if the request is an internal request.
+/// Returns true if the Authorization header contains a Bearer token that matches
+/// the configured internal_request_token.
+pub fn is_internal_request(context: &RequestContext) -> bool {
+ is_internal_request_inner(
+ context.state.config.internal_request_token.as_deref(),
+ &context.headers,
+ )
+}
+
+fn is_internal_request_inner(internal_token: Option<&str>, headers: &HeaderMap) -> bool {
+ use subtle::ConstantTimeEq;
+
+ let Some(internal_token) = internal_token else {
+ // No internal token configured, so no requests are internal
+ return false;
+ };
+
+ // Trim the configured token so stray whitespace (common in K8s secret mounts
+ // and CI-generated env files) doesn't silently break comparison.
+ let internal_token = internal_token.trim();
+
+ // Empty token should never be considered valid
+ if internal_token.is_empty() {
+ return false;
+ }
+
+ match crate::api::auth::extract_bearer_token(headers) {
+ // Trim the wire token symmetrically with the configured one, otherwise
+ // a stray newline on either side breaks comparison silently. Use a
+ // constant-time compare to avoid leaking the configured token via
+ // response-time differences.
+ Some(auth_token) => {
+ let auth_token = auth_token.trim();
+ !auth_token.is_empty()
+ && auth_token
+ .as_bytes()
+ .ct_eq(internal_token.as_bytes())
+ .into()
+ }
+ None => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::is_internal_request_inner;
+ use axum::http::{HeaderMap, HeaderValue};
+
+ #[test]
+ fn test_no_internal_token_configured() {
+ assert!(!is_internal_request_inner(None, &HeaderMap::new()));
+ }
+
+ #[test]
+ fn test_blank_internal_token_configured() {
+ assert!(!is_internal_request_inner(Some(""), &HeaderMap::new()));
+ }
+
+ #[test]
+ fn test_whitespace_internal_token_configured() {
+ assert!(!is_internal_request_inner(Some(" "), &HeaderMap::new()));
+ }
+
+ #[test]
+ fn test_missing_authorization_header() {
+ assert!(!is_internal_request_inner(
+ Some("valid_token"),
+ &HeaderMap::new()
+ ));
+ }
+
+ #[test]
+ fn test_empty_bearer_value() {
+ let mut headers = HeaderMap::new();
+ headers.insert("authorization", HeaderValue::from_str("Bearer ").unwrap());
+ assert!(!is_internal_request_inner(Some("valid_token"), &headers));
+ }
+
+ #[test]
+ fn test_whitespace_bearer_value() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer ").unwrap(),
+ );
+ assert!(!is_internal_request_inner(Some("valid_token"), &headers));
+ }
+
+ #[test]
+ fn test_non_matching_bearer_token() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer wrong_token").unwrap(),
+ );
+ assert!(!is_internal_request_inner(Some("correct_token"), &headers));
+ }
+
+ #[test]
+ fn test_matching_bearer_token() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer secret_token").unwrap(),
+ );
+ assert!(is_internal_request_inner(Some("secret_token"), &headers));
+ }
+
+ #[test]
+ fn test_case_sensitive_token_match() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer secret_token").unwrap(),
+ );
+ // Should be case sensitive - different case means no match
+ assert!(!is_internal_request_inner(Some("Secret_Token"), &headers));
+ }
+
+ #[test]
+ fn test_malformed_authorization_header() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("NotBearer valid_token").unwrap(),
+ );
+ assert!(!is_internal_request_inner(Some("valid_token"), &headers));
+ }
+
+ #[test]
+ fn test_configured_token_with_trailing_whitespace_matches() {
+ // Simulates K8s secret mount / env file leaving a trailing newline on the configured value.
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer secret_token").unwrap(),
+ );
+ assert!(is_internal_request_inner(Some("secret_token\n"), &headers));
+ }
+
+ #[test]
+ fn test_different_length_tokens_do_not_match() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str("Bearer secret").unwrap(),
+ );
+ assert!(!is_internal_request_inner(Some("secret_token"), &headers));
+ }
+}
diff --git a/rust/feature-flags/src/handler/billing.rs b/rust/feature-flags/src/handler/billing.rs
index f8e60eb58b22..acd351611fbf 100644
--- a/rust/feature-flags/src/handler/billing.rs
+++ b/rust/feature-flags/src/handler/billing.rs
@@ -60,7 +60,8 @@ pub async fn check_limits(
/// the shadow-keyspace tee via the aggregator.
///
/// Caller is responsible for the predicate (skip_writes, billable flags,
-/// etc.) — by the time this is called the request is known to be billable.
+/// internal requests, etc.) — by the time this is called the request is
+/// known to be billable.
///
/// The shadow tee only fires when the synchronous write succeeds. Recording
/// a request the production keyspace did not capture would surface as a
@@ -116,10 +117,15 @@ pub async fn record_usage(
filtered_flags: &FeatureFlagList,
team_id: i32,
library: Library,
+ is_internal: bool,
) {
if *context.state.config.skip_writes {
return;
}
+ // Skip billing for internal requests.
+ if is_internal {
+ return;
+ }
if !contains_billable_flags(filtered_flags) {
return;
}
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index dc7d5024fa09..3db25923df8f 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -197,6 +197,8 @@ pub struct FlagsCanonicalLogLine {
pub flags_experience_continuity: usize,
pub flags_disabled: bool,
pub quota_limited: bool,
+ /// Flag keys that were overridden with custom definitions (for testing/historical evaluation)
+ pub flags_overridden: Option<Vec<String>>,
/// Source of the flags data: "Redis", "S3", or "Fallback" (PostgreSQL).
pub flags_cache_source: Option<&'static str>,
@@ -305,6 +307,7 @@ impl Default for FlagsCanonicalLogLine {
flags_experience_continuity: 0,
flags_disabled: false,
quota_limited: false,
+ flags_overridden: None,
flags_cache_source: None,
eval: EvalCounters::default(),
db_property_fetches: 0,
@@ -369,6 +372,7 @@ impl FlagsCanonicalLogLine {
flags_device_id_bucketing = self.eval.flags_device_id_bucketing,
flags_disabled = self.flags_disabled,
quota_limited = self.quota_limited,
+ flags_overridden = ?self.flags_overridden,
flags_cache_source = self.flags_cache_source,
db_property_fetches = self.db_property_fetches,
person_queries = self.person_queries,
diff --git a/rust/feature-flags/src/handler/evaluation.rs b/rust/feature-flags/src/handler/evaluation.rs
index 2099ac87857e..0afe833e7788 100644
--- a/rust/feature-flags/src/handler/evaluation.rs
+++ b/rust/feature-flags/src/handler/evaluation.rs
@@ -33,7 +33,9 @@ pub async fn evaluate_feature_flags(
.with_parallel_eval_threshold(context.parallel_eval_threshold)
.with_rayon_dispatcher(context.rayon_dispatcher)
.with_skip_writes(context.skip_writes)
- .with_realtime_cohort_evaluation(context.enable_realtime_cohort_evaluation);
+ .with_realtime_cohort_evaluation(context.enable_realtime_cohort_evaluation)
+ .with_detailed_analysis(context.detailed_analysis)
+ .with_only_use_override_person_properties(context.only_use_override_person_properties);
matcher
.evaluate_all_feature_flags(
diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rs
index 53d91f39e01b..a8a1969fa748 100644
--- a/rust/feature-flags/src/handler/flags.rs
+++ b/rust/feature-flags/src/handler/flags.rs
@@ -4,6 +4,7 @@ use crate::{
types::{FlagsQueryParams, FlagsResponse},
},
flags::{
+ feature_flag_list::PreparedFlags,
flag_analytics::SURVEY_TARGETING_FLAG_PREFIX,
flag_models::{FeatureFlag, FeatureFlagList},
flag_service::FlagService,
@@ -131,6 +132,74 @@ fn collect_excluded_by_runtime(
}
}
+/// Apply caller-supplied flag overrides to ``flags``, returning the keys that
+/// were successfully overridden.
+///
+/// The override map is keyed by flag key alone, so the override payload must
+/// re-state the resolved flag's ``id``, ``team_id``, and ``key``. Mismatches
+/// are dropped with a warning — a caller must not be able to swap one flag's
+/// identity for another (potentially cross-team) by submitting a forged
+/// override payload.
+fn apply_flag_overrides(
+ flags: &mut [FeatureFlag],
+ override_defs: &HashMap<String, Value>,
+) -> Vec<String> {
+ let mut overridden_keys = Vec::new();
+ tracing::debug!("Processing {} override definitions", override_defs.len());
+ for (flag_key, override_def) in override_defs {
+ tracing::debug!("Processing override for flag: {}", flag_key);
+ let Some(flag) = flags.iter_mut().find(|f| &f.key == flag_key) else {
+ tracing::warn!("Flag not found for override: {}", flag_key);
+ continue;
+ };
+ tracing::trace!(
+ "Found flag to override: {}, current filters: {:?}",
+ flag_key,
+ flag.filters
+ );
+ let override_flag = match serde_json::from_value::<FeatureFlag>(override_def.clone()) {
+ Ok(parsed) => parsed,
+ Err(e) => {
+ tracing::warn!(
+ "Failed to parse override definition for flag {}: {}",
+ flag_key,
+ e
+ );
+ tracing::debug!("Override definition: {:?}", override_def);
+ continue;
+ }
+ };
+ // Identity guard: a caller must not be able to use the override to
+ // swap in another flag's identity. The override is keyed by flag_key
+ // alone, so we reject payloads whose embedded key/id/team_id disagree
+ // with the flag we resolved from the team's flag list.
+ if override_flag.key != *flag_key
+ || override_flag.id != flag.id
+ || override_flag.team_id != flag.team_id
+ {
+ tracing::warn!(
+ "Override identity mismatch for flag {}: skipping (override key={:?}, id={}, team_id={}; expected key={:?}, id={}, team_id={})",
+ flag_key,
+ override_flag.key,
+ override_flag.id,
+ override_flag.team_id,
+ flag.key,
+ flag.id,
+ flag.team_id
+ );
+ continue;
+ }
+ tracing::trace!(
+ "Successfully parsed override flag: {}, new filters: {:?}",
+ flag_key,
+ override_flag.filters
+ );
+ *flag = override_flag;
+ overridden_keys.push(flag_key.clone());
+ }
+ overridden_keys
+}
+
pub async fn fetch_and_filter(
flag_service: &FlagService,
team_id: TeamId,
@@ -138,6 +207,7 @@ pub async fn fetch_and_filter(
headers: &axum::http::HeaderMap,
explicit_runtime: Option<EvaluationRuntime>,
environment_tags: Option<&Vec<String>>,
+ override_flags_definitions: Option<&HashMap<String, Value>>,
) -> Result<FeatureFlagList, FlagError> {
let flag_result = flag_service.get_flags_from_cache_or_pg(team_id).await?;
@@ -146,31 +216,47 @@ pub async fn fetch_and_filter(
let prepared = &flag_result.prepared;
+ // Apply override flag definitions if provided. Overrides require a clone
+ // because `prepared.flags` is Arc-backed and shared across requests.
+ let overridden_flags: Option<PreparedFlags> = match override_flags_definitions {
+ Some(override_defs) => {
+ let mut flags_vec: Vec<FeatureFlag> = prepared.flags.iter().cloned().collect();
+ let overridden_keys = apply_flag_overrides(&mut flags_vec, override_defs);
+ if !overridden_keys.is_empty() {
+ with_canonical_log(|log| {
+ log.flags_overridden = Some(overridden_keys);
+ });
+ }
+ Some(PreparedFlags::seal(flags_vec))
+ }
+ None => None,
+ };
+
+ let flags: &[FeatureFlag] = match &overridden_flags {
+ Some(p) => p,
+ None => &prepared.flags,
+ };
+
// Build the filtered-out set: user-disabled, deleted, survey filter, runtime/tag mismatches.
// This is the single source of truth for "should this flag be skipped during evaluation."
- let mut filtered_out_flag_ids: HashSet<i32> = prepared
- .flags
+ let mut filtered_out_flag_ids: HashSet<i32> = flags
.iter()
.filter(|f| !f.active || f.deleted)
.map(|f| f.id)
.collect();
filtered_out_flag_ids.extend(collect_excluded_by_survey_filter(
- &prepared.flags,
+ flags,
query_params
.only_evaluate_survey_feature_flags
.unwrap_or(false),
));
let current_runtime = detect_evaluation_runtime_from_request(headers, explicit_runtime);
- filtered_out_flag_ids.extend(collect_excluded_by_runtime(
- &prepared.flags,
- current_runtime,
- ));
- filtered_out_flag_ids.extend(collect_excluded_by_tags(&prepared.flags, environment_tags));
+ filtered_out_flag_ids.extend(collect_excluded_by_runtime(flags, current_runtime));
+ filtered_out_flag_ids.extend(collect_excluded_by_tags(flags, environment_tags));
if tracing::enabled!(tracing::Level::DEBUG) {
- let active_count = prepared
- .flags
+ let active_count = flags
.iter()
.filter(|f| !filtered_out_flag_ids.contains(&f.id))
.count();
@@ -178,7 +264,7 @@ pub async fn fetch_and_filter(
"Flag filtering: detected_runtime={:?}, environment_tags={:?}, total={}, active={}",
current_runtime,
environment_tags,
- prepared.flags.len(),
+ flags.len(),
active_count,
);
}
@@ -187,9 +273,10 @@ pub async fn fetch_and_filter(
// of refcount bumps rather than a deep copy of the flag slice, the
// `EvaluationMetadata` map, or the cohort vec.
let flag_list = FeatureFlagList {
- flags: crate::flags::feature_flag_list::PreparedFlags::from_arc(Arc::clone(
- prepared.flags.as_arc(),
- )),
+ flags: match overridden_flags {
+ Some(p) => p,
+ None => PreparedFlags::from_arc(Arc::clone(prepared.flags.as_arc())),
+ },
filtered_out_flag_ids,
evaluation_metadata: Arc::clone(&prepared.evaluation_metadata),
cohorts: prepared.cohorts.as_ref().map(Arc::clone),
@@ -254,6 +341,8 @@ pub async fn evaluate_for_request(
request_id: Uuid,
disable_flags: bool,
flag_keys: Option<Vec<String>>,
+ detailed_analysis: Option<bool>,
+ only_use_override_person_properties: Option<bool>,
) -> Result<FlagsResponse, FlagError> {
// If flags are disabled, return empty FlagsResponse
if disable_flags {
@@ -292,12 +381,16 @@ pub async fn evaluate_for_request(
.0,
parallel_eval_threshold: state.config.parallel_eval_threshold,
rayon_dispatcher: state.rayon_dispatcher.clone(),
- skip_writes: *state.config.skip_writes,
+ skip_writes: detailed_analysis.unwrap_or(false)
+ || only_use_override_person_properties.unwrap_or(false)
+ || *state.config.skip_writes,
cohort_membership_provider: state.cohort_membership_provider.clone(),
enable_realtime_cohort_evaluation: state
.config
.realtime_cohort_evaluation_team_ids
.includes_team(team_id),
+ detailed_analysis: detailed_analysis.unwrap_or(false),
+ only_use_override_person_properties: only_use_override_person_properties.unwrap_or(false),
};
evaluation::evaluate_feature_flags(ctx, request_id).await
@@ -810,4 +903,92 @@ mod tests {
"Without explicit runtime, should detect server from python user-agent"
);
}
+
+ fn override_payload(id: i32, team_id: i32, key: &str) -> Value {
+ serde_json::json!({
+ "id": id,
+ "team_id": team_id,
+ "name": null,
+ "key": key,
+ "filters": { "groups": [{"properties": [], "rollout_percentage": 50}] },
+ "deleted": false,
+ "active": true,
+ })
+ }
+
+ fn flag_with_team(id: i32, team_id: i32, key: &str) -> FeatureFlag {
+ mock!(FeatureFlag,
+ id: id,
+ team_id: team_id,
+ key: key.mock_into()
+ )
+ }
+
+ #[test]
+ fn test_apply_flag_overrides_matching_identity_applies() {
+ let mut flags = vec![flag_with_team(1, 100, "my-flag")];
+ let mut overrides = HashMap::new();
+ overrides.insert("my-flag".to_string(), override_payload(1, 100, "my-flag"));
+
+ let applied = apply_flag_overrides(&mut flags, &overrides);
+
+ assert_eq!(applied, vec!["my-flag".to_string()]);
+ assert_eq!(flags[0].filters.groups[0].rollout_percentage, Some(50.0));
+ }
+
+ #[test]
+ fn test_apply_flag_overrides_rejects_team_id_mismatch() {
+ let mut flags = vec![flag_with_team(1, 100, "my-flag")];
+ let mut overrides = HashMap::new();
+ // Override claims to belong to team 999 — must be rejected to stop a
+ // caller from swapping in another team's identity.
+ overrides.insert("my-flag".to_string(), override_payload(1, 999, "my-flag"));
+
+ let applied = apply_flag_overrides(&mut flags, &overrides);
+
+ assert!(applied.is_empty(), "mismatched team_id must not be applied");
+ assert_eq!(flags[0].team_id, 100, "original team_id must be preserved");
+ }
+
+ #[test]
+ fn test_apply_flag_overrides_rejects_id_mismatch() {
+ let mut flags = vec![flag_with_team(1, 100, "my-flag")];
+ let mut overrides = HashMap::new();
+ overrides.insert("my-flag".to_string(), override_payload(999, 100, "my-flag"));
+
+ let applied = apply_flag_overrides(&mut flags, &overrides);
+
+ assert!(applied.is_empty(), "mismatched id must not be applied");
+ assert_eq!(flags[0].id, 1, "original id must be preserved");
+ }
+
+ #[test]
+ fn test_apply_flag_overrides_rejects_key_mismatch() {
+ let mut flags = vec![flag_with_team(1, 100, "my-flag")];
+ let mut overrides = HashMap::new();
+ // The map is keyed by "my-flag" but the payload's embedded key is
+ // different — reject to keep the keying contract honest.
+ overrides.insert(
+ "my-flag".to_string(),
+ override_payload(1, 100, "other-flag"),
+ );
+
+ let applied = apply_flag_overrides(&mut flags, &overrides);
+
+ assert!(applied.is_empty(), "mismatched key must not be applied");
+ }
+
+ #[test]
+ fn test_apply_flag_overrides_skips_unknown_keys() {
+ let mut flags = vec![flag_with_team(1, 100, "my-flag")];
+ let mut overrides = HashMap::new();
+ overrides.insert(
+ "not-in-list".to_string(),
+ override_payload(1, 100, "not-in-list"),
+ );
+
+ let applied = apply_flag_overrides(&mut flags, &overrides);
+
+ assert!(applied.is_empty());
+ }
}
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 0e7a883fa2a6..39dc8ad8f87b 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -187,6 +187,15 @@ async fn process_request_inner(
tracing::debug!("Distinct ID resolved: {}", distinct_id);
+ // Compute auth status once to avoid repeated header parsing and allocation
+ let is_internal = authentication::is_internal_request(&context);
+
+ let override_defs = if is_internal {
+ request.override_flags_definitions.as_ref()
+ } else {
+ None
+ };
+
let filtered_flags = flags::fetch_and_filter(
&flag_service,
team.id,
@@ -194,6 +203,7 @@ async fn process_request_inner(
&context.headers,
request.evaluation_runtime,
request.evaluation_contexts.as_ref(),
+ override_defs,
)
.await?;
@@ -215,13 +225,25 @@ async fn process_request_inner(
context.request_id,
request.is_flags_disabled(),
request.flag_keys.clone(),
+ Some(is_internal && context.meta.detailed_analysis.unwrap_or(false)),
+ if is_internal {
+ context.meta.only_use_override_person_properties
+ } else {
+ None
+ },
)
.await?;
// Only record billing if flags are not disabled
if !request.is_flags_disabled() {
- billing::record_usage(&context, &filtered_flags, team.id, metrics_data.library)
- .await;
+ billing::record_usage(
+ &context,
+ &filtered_flags,
+ team.id,
+ metrics_data.library,
+ is_internal,
+ )
+ .await;
}
response
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index 0da8a3b12fe0..a9d1a3b9a154 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -219,6 +219,8 @@ async fn test_evaluate_feature_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -301,6 +303,8 @@ async fn test_evaluate_feature_flags_with_errors() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -328,6 +332,7 @@ async fn test_evaluate_feature_flags_with_errors() {
description: None,
payload: None,
},
+ conditions: None,
}
);
let legacy_response = LegacyFlagsResponse::from_response(result);
@@ -682,6 +687,8 @@ async fn test_evaluate_feature_flags_multiple_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -762,6 +769,8 @@ async fn test_evaluate_feature_flags_details() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -789,6 +798,7 @@ async fn test_evaluate_feature_flags_details() {
description: None,
payload: None,
},
+ conditions: None,
}
);
assert_eq!(
@@ -809,6 +819,7 @@ async fn test_evaluate_feature_flags_details() {
description: None,
payload: None,
},
+ conditions: None,
}
);
}
@@ -911,6 +922,8 @@ async fn test_evaluate_feature_flags_with_overrides() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -990,6 +1003,8 @@ async fn test_long_distinct_id() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
@@ -1181,6 +1196,7 @@ async fn test_fetch_and_filter_flags() {
&axum::http::HeaderMap::new(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1208,6 +1224,7 @@ async fn test_fetch_and_filter_flags() {
&axum::http::HeaderMap::new(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1222,6 +1239,7 @@ async fn test_fetch_and_filter_flags() {
&axum::http::HeaderMap::new(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1244,6 +1262,7 @@ async fn test_fetch_and_filter_flags() {
&axum::http::HeaderMap::new(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1322,6 +1341,7 @@ async fn test_fetch_and_filter_preserves_evaluation_metadata() {
&axum::http::HeaderMap::new(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1386,6 +1406,7 @@ async fn test_fetch_and_filter_shares_prepared_arcs_across_requests() {
&HeaderMap::new(),
None,
None,
+ None,
)
.await
.expect("first fetch");
@@ -1396,6 +1417,7 @@ async fn test_fetch_and_filter_shares_prepared_arcs_across_requests() {
&HeaderMap::new(),
None,
None,
+ None,
)
.await
.expect("second fetch");
@@ -1587,6 +1609,8 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let sequential_result = evaluate_feature_flags(sequential_context, Uuid::new_v4())
.await
@@ -1615,6 +1639,8 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let parallel_result = evaluate_feature_flags(parallel_context, Uuid::new_v4())
.await
@@ -1704,6 +1730,8 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_disabled.clone(),
enable_realtime_cohort_evaluation: false,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
// Test with realtime cohort evaluation ENABLED
@@ -1738,6 +1766,8 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_enabled.clone(),
enable_realtime_cohort_evaluation: true,
+ detailed_analysis: false,
+ only_use_override_person_properties: false,
};
let request_id = Uuid::new_v4();
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 2cadb11fb10f..efb129b9812b 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -75,6 +75,10 @@ pub struct FeatureFlagEvaluationContext {
pub cohort_membership_provider: Arc<dyn CohortMembershipProvider>,
/// Whether to enable realtime cohort evaluation.
pub enable_realtime_cohort_evaluation: bool,
+ /// Whether to include detailed condition analysis in flag evaluation results.
+ pub detailed_analysis: bool,
+ /// Whether to only use person properties from request payload, ignoring database properties.
+ pub only_use_override_person_properties: bool,
}
/// SDK type classification based on user-agent parsing.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3fd87824ab14..e5843db1a4ea 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18371,6 +18371,45 @@ export namespace Schemas {
readonly is_used_in_replay_settings: boolean;
}
+ export interface FeatureFlagConditionPropertyAnalysis {
+ /** Property key */
+ key: string;
+ /** Comparison operator */
+ operator: string;
+ /** Expected property value */
+ value: unknown;
+ /** Property type (person, group, etc.) */
+ type: string;
+ /** Actual property value from user */
+ actual_value: unknown | null;
+ /** Whether this property condition matched */
+ matched: boolean;
+ /** Human-readable explanation of the match result */
+ explanation: string;
+ }
+
+ export interface FeatureFlagConditionAnalysis {
+ /** Index of this condition in the feature flag */
+ index: number;
+ /** True when this condition was the one that determined the flag's outcome. Use this to find the winning condition — at most one condition per flag is True. */
+ matched: boolean;
+ /** True when every property in this condition evaluated to true, regardless of whether this condition was the eventual winner. */
+ properties_matched?: boolean;
+ /** Human-readable explanation of why this condition matched/didn't match */
+ explanation: string;
+ /** Rollout percentage for this condition (0.0-100.0) */
+ rollout_percentage: number;
+ /** Whether this condition matched properties but was excluded due to rollout */
+ rollout_excluded: boolean;
+ /**
+ * Variant associated with this condition
+ * @nullable
+ */
+ variant: string | null;
+ /** Analysis of each property in this condition */
+ properties: FeatureFlagConditionPropertyAnalysis[];
+ }
+
/**
* * `cohort` - cohort
* `person` - person
@@ -18783,6 +18822,50 @@ export namespace Schemas {
reason: string;
}
+ export interface FeatureFlagTestEvaluationRequest {
+ /** User distinct ID to test against (mutually exclusive with person_id) */
+ distinct_id?: string;
+ /** Person ID to test against (mutually exclusive with distinct_id) */
+ person_id?: string;
+ /**
+ * Optional point-in-time to evaluate the flag against — both flag conditions and person properties are reconstructed as they existed at that timestamp. ISO 8601 with timezone, e.g. ``2026-04-29T15:30:00Z`` or ``2026-04-29T15:30:00+00:00``. Naive timestamps (no timezone) are interpreted as UTC.
+ * @nullable
+ */
+ timestamp?: string | null;
+ /** Groups for feature flag evaluation (JSON object, defaults to empty dict) */
+ groups?: unknown;
+ }
+
+ /**
+ * Person properties at the time of evaluation (for historical evaluations)
+ */
+ export type FeatureFlagTestEvaluationResponsePersonProperties = { [key: string]: unknown };
+
+ export interface FeatureFlagTestEvaluationResponse {
+ /** Feature flag key */
+ flag_key: string;
+ /** The evaluated value of the feature flag (boolean or variant key string) */
+ result: unknown;
+ /** The reason for the evaluation result */
+ reason: string;
+ /**
+ * The index of the condition that matched, if applicable
+ * @nullable
+ */
+ condition_index: number | null;
+ /** Payload associated with the flag result, if any */
+ payload: unknown | null;
+ /** Person properties at the time of evaluation (for historical evaluations) */
+ person_properties: FeatureFlagTestEvaluationResponsePersonProperties;
+ /**
+ * The distinct_id used for rollout/variant bucketing. Echoes the caller-provided distinct_id when one was sent; null on the person_id path so the endpoint doesn't leak the person's other distinct_ids to a feature_flag:read-only token.
+ * @nullable
+ */
+ evaluation_distinct_id: string | null;
+ /** Detailed analysis of each condition in the feature flag */
+ conditions: FeatureFlagConditionAnalysis[];
+ }
+
export type FeatureFlagVersionResponseFilters = { [key: string]: unknown };
/**
@@ -32573,29 +32656,6 @@ export namespace Schemas {
$unset: string;
}
- /**
- * The parameters passed to the query
- */
- export type PersonPropertiesAtTimeDebugParams = { [key: string]: unknown };
-
- export type PersonPropertiesAtTimeDebugEventsItem = { [key: string]: unknown };
-
- /**
- * Serializer for the debug information (only available to staff users).
- */
- export interface PersonPropertiesAtTimeDebug {
- /** The ClickHouse query that was executed */
- query: string;
- /** The parameters passed to the query */
- params: PersonPropertiesAtTimeDebugParams;
- /** Number of events found */
- events_found: number;
- /** Raw events that were used to build the properties */
- events: PersonPropertiesAtTimeDebugEventsItem[];
- /** Error message if debug query failed */
- error?: string;
- }
-
/**
* Serializer for the point-in-time query metadata.
*/
@@ -32650,8 +32710,6 @@ export namespace Schemas {
last_seen_at: string | null;
/** Metadata about the point-in-time query */
point_in_time_metadata: PersonPropertiesAtTimeMetadata;
- /** Debug information (only available when debug=true and DEBUG=True) */
- debug?: PersonPropertiesAtTimeDebug;
}
export interface PersonUpdatePropertyRequest {
@@ -41365,10 +41423,6 @@ export namespace Schemas {
} as const;
export type EnvironmentsPersonsPropertiesAtTimeRetrieveParams = {
- /**
- * Whether to include debug information with raw events (only works when DEBUG=True, default: false)
- */
- debug?: boolean;
/**
* The distinct_id of the person (mutually exclusive with person_id)
*/
@@ -46193,10 +46247,6 @@ export namespace Schemas {
} as const;
export type PersonsPropertiesAtTimeRetrieveParams = {
- /**
- * Whether to include debug information with raw events (only works when DEBUG=True, default: false)
- */
- debug?: boolean;
/**
* The distinct_id of the person (mutually exclusive with person_id)
*/