Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"PostHog.AspNetCore": patch
---

Picks up the `PostHog` fix for a `group` property filter without `group_type_index` in a person-aggregated condition. With local evaluation, the PostHog feature manager no longer matches such a filter against person properties. The flag falls back to the server instead.
5 changes: 5 additions & 0 deletions .changeset/index-less-group-filter-person-condition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"PostHog": patch
---

Local evaluation now leaves a flag unresolved with the `unsupported_definition` reason when a person-aggregated condition has a `group` property filter without `group_type_index`, so the flag falls back to the server. Before, the filter was matched against person properties and could return a local result that the server contradicts.
23 changes: 19 additions & 4 deletions src/PostHog/Features/LocalEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,18 @@ public StringOrValue<bool> EvaluateFeatureFlag(
return UnresolvedFlagReason.UnsupportedDefinition;
}

var flagAggregation = flag.Filters?.AggregationGroupTypeIndex;
var visitedCohortIds = new HashSet<long>();
// Evaluation can't use a group placed directly in a condition, so it counts as unsupported here too.
var usesUnsupportedFilter = (flag.Filters?.Groups ?? [])
.SelectMany(condition => condition.Properties ?? [])
.Any(filter => filter is not PropertyFilter || IsUnsupportedFilter(filter, visitedCohortIds, inCohort: false));
// Evaluation can't use a group placed directly in a condition, or an index-less group filter in a person
// condition, so both count as unsupported here too.
var usesUnsupportedFilter = (flag.Filters?.Groups ?? []).Any(condition =>
{
var isPersonCondition = condition.EffectiveAggregation(flagAggregation) is null;
return (condition.Properties ?? []).Any(filter =>
filter is not PropertyFilter
|| (isPersonCondition && filter is PropertyFilter { Type: FilterType.Group, GroupTypeIndex: null })
|| IsUnsupportedFilter(filter, visitedCohortIds, inCohort: false));
});
return usesUnsupportedFilter ? UnresolvedFlagReason.UnsupportedDefinition : null;
}

Expand Down Expand Up @@ -589,6 +596,14 @@ ConditionMatchResult EvaluateConditionMatch(
continue;
}

if (property is { Type: FilterType.Group, GroupTypeIndex: null } && absentKeysGroupTypeIndex is null)
Comment thread
marandaneto marked this conversation as resolved.
Resolved
{
// In a person condition, the flags service reads no properties for this filter, so its result can
// differ from any local read. Checked before known absence, so a listing can't resolve it either.
inconclusiveReason = UnresolvedFlagReasonExtensions.Pick(inconclusiveReason, UnresolvedFlagReason.UnsupportedDefinition);
continue;
}

var (filterProperties, filterAbsentKeys, filterAbsentKeysGroupTypeIndex) =
ResolveFilterContext(property, properties, absentKeys, absentKeysGroupTypeIndex, context);
try
Expand Down
151 changes: 151 additions & 0 deletions tests/UnitTests/Features/IndexLessGroupFilterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using PostHog;
using PostHog.Api;
using PostHog.Features;
using UnitTests.Fakes;

namespace LocalEvaluatorTests;

public class TheIndexLessGroupFilter
{
const string TierEnterprise = """{"key": "tier", "type": "group", "operator": "exact", "value": "enterprise"}""";
const string TierNotSet = """{"key": "tier", "type": "group", "operator": "is_not_set"}""";

// conditionAggregation is the condition's aggregation_group_type_index JSON, or empty to omit it.
static string Definitions(string filter, string flagAggregation, string conditionAggregation) => $$$"""
{
"flags": [{"key": "legacy-tier", "active": true, "filters": {
{{{flagAggregation}}}
"groups": [{ {{{conditionAggregation}}} "properties": [{{{filter}}}], "rollout_percentage": 100}]
}}],
"group_type_mapping": {"0": "organization"}
}
""";

sealed record Evaluation(bool? Flag, IReadOnlyDictionary<string, UnresolvedFlagReason> UnresolvedFlags, int RemoteRequests);

static async Task<Evaluation> EvaluateAsync(string definitions, FeatureFlagOptions options)
{
var container = new TestContainer("fake-personal-api-key");
container.FakeHttpMessageHandler.AddLocalEvaluationResponseWithETag(definitions, "\"definitions\"");
var remoteHandler = container.FakeHttpMessageHandler.AddFlagsResponse(
"""{"featureFlags": {"legacy-tier": false}}""");
await using var client = container.Activate<PostHogClient>();

var snapshot = await client.EvaluateFlagsAsync("user", options, CancellationToken.None);

return new Evaluation(
snapshot.GetFlag("legacy-tier")?.IsEnabled,
snapshot.UnresolvedFlags.ToDictionary(pair => pair.Key, pair => pair.Value),
remoteHandler.ReceivedRequests.Count);
}

static GroupCollection Acme(Dictionary<string, object?>? properties = null)
=> [new Group("organization", "acme", properties ?? [])];

static FeatureFlagOptions BothSetToEnterprise(bool onlyEvaluateLocally) => new()
{
OnlyEvaluateLocally = onlyEvaluateLocally,
PersonProperties = new() { ["tier"] = "enterprise" },
Groups = Acme(new() { ["tier"] = "enterprise" })
};

static FeatureFlagOptions BothListedKnownAbsent(bool onlyEvaluateLocally) => new()
{
OnlyEvaluateLocally = onlyEvaluateLocally,
Groups = Acme(),
PersonPropertyKeysKnownAbsent = ["tier"],
GroupPropertyKeysKnownAbsent = new Dictionary<string, IReadOnlyCollection<string>> { ["organization"] = ["tier"] }
};

// A person flag with the condition aggregation omitted, and a group flag whose condition sets it to null.
public static TheoryData<string, string> PersonConditions() => new()
{
{ "", "" },
{ "\"aggregation_group_type_index\": 0,", "\"aggregation_group_type_index\": null," }
};

[Theory]
[MemberData(nameof(PersonConditions))]
public async Task IsUnresolvedInAPersonConditionWhenPropertiesAreSupplied(string flagAggregation, string conditionAggregation)
{
foreach (var filter in new[] { TierEnterprise, TierNotSet })
{
var result = await EvaluateAsync(
Definitions(filter, flagAggregation, conditionAggregation),
BothSetToEnterprise(onlyEvaluateLocally: true));

Assert.Null(result.Flag);
Assert.Equal(UnresolvedFlagReason.UnsupportedDefinition, result.UnresolvedFlags["legacy-tier"]);
Assert.Equal(0, result.RemoteRequests);
}
}

[Theory]
[MemberData(nameof(PersonConditions))]
public async Task IsUnresolvedInAPersonConditionWhenTheKeyIsKnownAbsent(string flagAggregation, string conditionAggregation)
{
foreach (var filter in new[] { TierEnterprise, TierNotSet })
{
var result = await EvaluateAsync(
Definitions(filter, flagAggregation, conditionAggregation),
BothListedKnownAbsent(onlyEvaluateLocally: true));

Assert.Null(result.Flag);
Assert.Equal(UnresolvedFlagReason.UnsupportedDefinition, result.UnresolvedFlags["legacy-tier"]);
}
}

[Theory]
[MemberData(nameof(PersonConditions))]
public async Task FallsBackToTheServerInAPersonCondition(string flagAggregation, string conditionAggregation)
{
var result = await EvaluateAsync(
Definitions(TierEnterprise, flagAggregation, conditionAggregation),
BothSetToEnterprise(onlyEvaluateLocally: false));

Assert.False(result.Flag);
Assert.Equal(1, result.RemoteRequests);
}

[Theory]
[MemberData(nameof(PersonConditions))]
public async Task ReportsAPersonConditionInTheDefinitionReason(string flagAggregation, string conditionAggregation)
{
var evaluator = await CreateEvaluatorAsync(Definitions(TierEnterprise, flagAggregation, conditionAggregation));

Assert.Equal(
UnresolvedFlagReason.UnsupportedDefinition,
evaluator.GetDefinitionUnresolvedReason(evaluator.LocalEvaluationApiResult.Flags[0]));
}

[Theory]
[InlineData("\"aggregation_group_type_index\": 0,", "")]
[InlineData("", "\"aggregation_group_type_index\": 0,")]
public async Task DoesNotReportAGroupConditionInTheDefinitionReason(string flagAggregation, string conditionAggregation)
{
var evaluator = await CreateEvaluatorAsync(Definitions(TierEnterprise, flagAggregation, conditionAggregation));

Assert.Null(evaluator.GetDefinitionUnresolvedReason(evaluator.LocalEvaluationApiResult.Flags[0]));
}

static async Task<LocalEvaluator> CreateEvaluatorAsync(string definitions) =>
new((await PostHog.Json.JsonSerializerHelper.DeserializeFromCamelCaseJsonStringAsync<LocalEvaluationApiResult>(definitions))!);

[Theory]
[InlineData("\"aggregation_group_type_index\": 0,", "")]
[InlineData("", "\"aggregation_group_type_index\": 0,")]
public async Task ReadsTheConditionGroupTypeInAGroupCondition(string flagAggregation, string conditionAggregation)
{
var result = await EvaluateAsync(
Definitions(TierEnterprise, flagAggregation, conditionAggregation),
new FeatureFlagOptions
{
OnlyEvaluateLocally = true,
PersonProperties = new() { ["tier"] = "free" },
Groups = Acme(new() { ["tier"] = "enterprise" })
});

Assert.True(result.Flag);
Assert.Empty(result.UnresolvedFlags);
}
}
7 changes: 7 additions & 0 deletions tests/UnitTests/Features/LocalEvaluatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3468,6 +3468,9 @@ public class TheUnresolvedFlagReasons
const string DistinctIdIsUser = """{"key": "distinct_id", "type": "person", "value": "user-123", "operator": "exact"}""";
const string DistinctIdIsSomeoneElse = """{"key": "distinct_id", "type": "person", "value": "user-456", "operator": "exact"}""";
const string InCohortThatMatchesBeforeUnknownOperator = """{"key": "id", "type": "cohort", "value": 1}""";
const string IndexLessGroupFilter = """{"key": "tier", "type": "group", "operator": "exact", "value": "enterprise"}""";
const string GroupConditionWithIndexLessGroupFilter =
"""{"aggregation_group_type_index": 0, "properties": [""" + IndexLessGroupFilter + """], "rollout_percentage": 100}""";

const string CheckoutWithExperienceContinuity = """
{"id": 2, "key": "checkout", "active": true, "ensure_experience_continuity": true,
Expand Down Expand Up @@ -3525,6 +3528,10 @@ public static IEnumerable<object[]> PrecedenceCases()
yield return [new[] { Condition(DependsOnMembers), Condition(UnknownOperator) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(UnknownOperator), Condition(DependsOnMembers) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(DistinctIdIsSomeoneElse, UnknownOperator), Condition(DependsOnMembers) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(IndexLessGroupFilter), Condition(DependsOnMembers) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(DependsOnMembers), Condition(IndexLessGroupFilter) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(DistinctIdIsSomeoneElse, IndexLessGroupFilter), Condition(DependsOnMembers) }, UnresolvedFlagReason.UnsupportedDefinition];
yield return [new[] { Condition(DependsOnMembers), GroupConditionWithIndexLessGroupFilter }, UnresolvedFlagReason.UnresolvedDependency];
// Within one condition.
yield return [new[] { Condition(PlanIsPro, DependsOnCheckout) }, UnresolvedFlagReason.UnresolvedDependency];
yield return [new[] { Condition(DependsOnCheckout, PlanIsPro) }, UnresolvedFlagReason.UnresolvedDependency];
Expand Down