-
Notifications
You must be signed in to change notification settings - Fork 571
feat(Flag Dependency): Index flag references #8525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
a819d0c
maybe the chicken came first
emyller ec3f473
index prerequisites
emyller d61176b
you can't depend on the unknown
emyller b37eac5
unindex
emyller c402599
reindex
emyller 7d5c504
don't touch the hen
emyller c5ccaa2
fix logging
emyller 3608b5e
or maybe the egg
emyller 640bffd
more queries!
emyller 219a407
feature segments
emyller b7eb928
coverage 💯
emyller d0df9a4
uma questão de ordem 🧑⚖️
emyller 3e9efe0
prepare for the future
emyller 6f54c4d
feature versioning v2 strikes again
emyller eae3ff8
even cycles needs an environment
emyller edf3616
Merge remote-tracking branch 'github/main' into feat/segment-dependen…
emyller 175dbe6
typing grrr
emyller 8e2728a
coverage 💯 part 2
emyller b25eecd
can't depend on a mystery
emyller ed3decf
less hops
emyller 0d6e3cb
Merge remote-tracking branch 'github/main' into feat/segment-dependen…
emyller f7b8ac7
fix test coverage
emyller 22199e1
short-circuit
emyller File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| from core.apps import BaseAppConfig | ||
|
|
||
|
|
||
| class FeatureDependenciesConfig(BaseAppConfig): | ||
| name = "features.dependencies" | ||
| label = "feature_dependencies" | ||
| default = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| from typing import TypedDict | ||
|
|
||
| from rest_framework import status | ||
| from rest_framework.exceptions import APIException | ||
|
|
||
| from features.dependencies.types import DependencyPath, ReferencingEnvironment | ||
|
|
||
|
|
||
| class _CircularDependencyDetail(TypedDict): | ||
| """The body served where a feature is refused for depending on itself.""" | ||
|
|
||
| code: str | ||
| environment: ReferencingEnvironment | ||
| path: DependencyPath | ||
|
|
||
|
|
||
| class CircularDependencyError(APIException): | ||
| """Raised where a feature would end up depending on itself.""" | ||
|
|
||
| status_code = status.HTTP_400_BAD_REQUEST | ||
| default_code = "circular_dependency" | ||
|
|
||
| def __init__( | ||
| self, environment: ReferencingEnvironment, path: DependencyPath | ||
| ) -> None: | ||
| super().__init__() | ||
| detail: _CircularDependencyDetail = { | ||
| "code": self.default_code, | ||
| "environment": environment, | ||
| "path": path, | ||
| } | ||
| self.detail = detail # type: ignore[assignment] | ||
|
|
||
|
|
||
| class PrerequisiteFeatureNotFoundError(APIException): | ||
| """Raised where a segment condition names a feature that does not exist.""" | ||
|
|
||
| status_code = status.HTTP_400_BAD_REQUEST | ||
| default_code = "prerequisite_feature_not_found" | ||
|
|
||
| def __init__(self, prerequisite_feature: str, condition_json_path: str) -> None: | ||
| super().__init__( | ||
| { | ||
| "code": self.default_code, | ||
| "prerequisite_feature": prerequisite_feature, | ||
| "condition_json_path": condition_json_path, | ||
| } | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import jsonpath_rfc9535 | ||
| from jsonpath_rfc9535.exceptions import JSONPathError | ||
| from jsonpath_rfc9535.segments import JSONPathChildSegment, JSONPathSegment | ||
| from jsonpath_rfc9535.selectors import NameSelector | ||
|
|
||
| from features.dependencies.types import FeatureName, JSONPathStr | ||
| from segments.types import SegmentRule | ||
|
|
||
|
|
||
| def map_rules_to_prerequisite_feature_names( | ||
| rules: list[SegmentRule], | ||
| ) -> dict[JSONPathStr, FeatureName]: | ||
| """Returns the feature names keyed by the condition $.flags JSONPath""" | ||
| return { | ||
| f"{rule_json_path}.conditions[{condition_index}]": feature_name | ||
| for rule_json_path, rule in _get_rules_by_json_path(rules).items() | ||
| for condition_index, condition in enumerate(rule["conditions"]) | ||
| if (condition_property := condition["property"]) | ||
| and (feature_name := _get_prerequisite_feature_name(condition_property)) | ||
| is not None | ||
| } | ||
|
|
||
|
|
||
| def _get_rules_by_json_path( | ||
| rules: list[SegmentRule], | ||
| ) -> dict[JSONPathStr, SegmentRule]: | ||
| rules_by_json_path: dict[JSONPathStr, SegmentRule] = {} | ||
| for rule_index, rule in enumerate(rules): | ||
| rule_json_path = f"$[{rule_index}]" | ||
| rules_by_json_path[rule_json_path] = rule | ||
| for nested_index, nested_rule in enumerate(rule.get("rules", [])): | ||
| rules_by_json_path[f"{rule_json_path}.rules[{nested_index}]"] = nested_rule | ||
| return rules_by_json_path | ||
|
|
||
|
|
||
| def _get_prerequisite_feature_name(condition_property: str) -> FeatureName | None: | ||
| """Return the feature name a `$.flags.<feature>` condition points at, if it does.""" | ||
| # Because of historical decisions, `$['flags']` can be a trait. | ||
| if not condition_property.startswith("$.flags"): | ||
| return None | ||
| try: | ||
| query_segments = jsonpath_rfc9535.compile(condition_property).segments | ||
| except JSONPathError: | ||
| return None | ||
| if len(query_segments) < 2 or _get_selected_name(query_segments[0]) != "flags": | ||
| return None | ||
| return _get_selected_name(query_segments[1]) | ||
|
|
||
|
|
||
| def _get_selected_name(query_segment: JSONPathSegment) -> str | None: | ||
| if ( | ||
| not isinstance(query_segment, JSONPathChildSegment) | ||
| or len(query_segment.selectors) != 1 | ||
| ): | ||
| return None | ||
| selector = query_segment.selectors[0] | ||
| return selector.name if isinstance(selector, NameSelector) else None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| # Generated by Django 5.2.17 on 2026-09-14 18:40 | ||
|
|
||
| import django.db.models.deletion | ||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| initial = True | ||
|
|
||
| dependencies = [ | ||
| ("features", "0067_add_feature_state_mv_hashing_salt"), | ||
| ("segments", "0032_add_segment_rules_data"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.CreateModel( | ||
| name="SegmentFlagReference", | ||
| fields=[ | ||
| ( | ||
| "id", | ||
| models.AutoField( | ||
| auto_created=True, | ||
| primary_key=True, | ||
| serialize=False, | ||
| verbose_name="ID", | ||
| ), | ||
| ), | ||
| ("condition_json_path", models.TextField()), | ||
| ( | ||
| "prerequisite_feature", | ||
| models.ForeignKey( | ||
| on_delete=django.db.models.deletion.CASCADE, | ||
| related_name="segment_references", | ||
| to="features.feature", | ||
| ), | ||
| ), | ||
| ( | ||
| "segment", | ||
| models.ForeignKey( | ||
| on_delete=django.db.models.deletion.CASCADE, | ||
| related_name="flag_references", | ||
| to="segments.segment", | ||
| ), | ||
| ), | ||
| ], | ||
| ), | ||
| ] |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| from django.db import models | ||
|
|
||
|
|
||
| class SegmentFlagReference(models.Model): | ||
| """A reference to a pre-requisite flag from the segment | ||
|
|
||
| When a segment rule points to a feature as a pre-requisite, an object of | ||
| this type must exist to materialise the relationship and enable easier | ||
| backreferencing, e.g. for validating circular dependencies, and querying | ||
| without inferring from JSON rules. | ||
| """ | ||
|
|
||
| segment = models.ForeignKey( | ||
| "segments.Segment", | ||
| on_delete=models.CASCADE, | ||
| related_name="flag_references", | ||
| ) | ||
|
|
||
| prerequisite_feature = models.ForeignKey( | ||
| "features.Feature", | ||
| on_delete=models.CASCADE, | ||
| related_name="segment_references", | ||
| ) | ||
|
|
||
| # JSONPath (RFC 9535) locating the rule condition | ||
| condition_json_path = models.TextField() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| import typing | ||
| from collections import defaultdict | ||
| from collections.abc import Collection | ||
|
|
||
| import structlog | ||
|
|
||
| from environments.models import Environment | ||
| from features.dependencies.exceptions import ( | ||
| CircularDependencyError, | ||
| PrerequisiteFeatureNotFoundError, | ||
| ) | ||
| from features.dependencies.mappers import map_rules_to_prerequisite_feature_names | ||
| from features.dependencies.models import SegmentFlagReference | ||
| from features.dependencies.types import DependencyEdge, DependencyPath, FeatureName | ||
| from features.models import Feature, FeatureSegment | ||
| from segments.services import get_all_live_or_scheduled_overrides | ||
|
|
||
| if typing.TYPE_CHECKING: | ||
| from segments.models import Segment | ||
|
|
||
| logger = structlog.get_logger("features") | ||
|
|
||
|
|
||
| def index_segment_flag_references(segment: "Segment") -> None: | ||
| """Materialise the segment's `$.flags` conditions as SegmentFlagReference rows.""" | ||
| feature_names_by_json_path = map_rules_to_prerequisite_feature_names( | ||
| segment.rules_data or [] | ||
| ) | ||
| feature_ids_by_name = dict( | ||
| Feature.objects.filter( | ||
| project_id=segment.project_id, | ||
| name__in=set(feature_names_by_json_path.values()), | ||
| ).values_list("name", "id") | ||
| ) | ||
| for condition_json_path, feature_name in feature_names_by_json_path.items(): | ||
| if feature_name not in feature_ids_by_name: | ||
| raise PrerequisiteFeatureNotFoundError( | ||
| prerequisite_feature=feature_name, | ||
| condition_json_path=condition_json_path, | ||
| ) | ||
| references = SegmentFlagReference.objects.filter(segment=segment) | ||
| previous_feature_names = set( | ||
| references.values_list("prerequisite_feature__name", flat=True) | ||
| ) | ||
| references.delete() | ||
| SegmentFlagReference.objects.bulk_create( | ||
| SegmentFlagReference( | ||
| segment=segment, | ||
| prerequisite_feature_id=feature_ids_by_name[feature_name], | ||
| condition_json_path=condition_json_path, | ||
| ) | ||
| for condition_json_path, feature_name in feature_names_by_json_path.items() | ||
| ) | ||
| for override in FeatureSegment.objects.filter(segment=segment).select_related( | ||
| "environment__project", "feature" | ||
| ): | ||
| report_flag_dependencies( | ||
| environment=override.environment, | ||
| feature=override.feature, | ||
| created=feature_ids_by_name.keys() - previous_feature_names, | ||
| deleted=previous_feature_names - feature_ids_by_name.keys(), | ||
| ) | ||
|
|
||
|
|
||
| def delete_segment_flag_references(segment: "Segment") -> None: | ||
| """Drop the segment's index rows, reporting every dependency lost.""" | ||
| references = SegmentFlagReference.objects.filter(segment=segment).select_related( | ||
| "prerequisite_feature" | ||
| ) | ||
| overrides = FeatureSegment.objects.filter(segment=segment).select_related( | ||
| "environment", "feature" | ||
| ) | ||
| for override in overrides: | ||
| for reference in references: | ||
| logger.info( | ||
| "dependencies.deleted", | ||
| organisation__id=segment.project.organisation_id, | ||
| project__id=segment.project_id, | ||
| environment__key=override.environment.api_key, | ||
| feature__name=override.feature.name, | ||
| prerequisite_feature__name=reference.prerequisite_feature.name, | ||
| ) | ||
| references.delete() | ||
|
|
||
|
|
||
| def report_flag_dependencies( | ||
| *, | ||
| environment: Environment, | ||
| feature: Feature, | ||
| created: Collection[FeatureName], | ||
| deleted: Collection[FeatureName], | ||
| ) -> None: | ||
| """Report the prerequisites a feature gains and loses in an environment.""" | ||
| log = logger.bind( | ||
| organisation__id=environment.project.organisation_id, | ||
| project__id=environment.project_id, | ||
| environment__key=environment.api_key, | ||
| feature__name=feature.name, | ||
| ) | ||
| for feature_name in deleted: | ||
| log.info("dependencies.deleted", prerequisite_feature__name=feature_name) | ||
| for feature_name in created: | ||
| log.info("dependencies.created", prerequisite_feature__name=feature_name) | ||
|
|
||
|
|
||
| def validate_segment_flag_dependencies(segment: "Segment") -> None: | ||
| """Raise if any feature the segment overrides ends up depending on itself.""" | ||
| existing_references = SegmentFlagReference.objects.filter(segment=segment) | ||
| if not existing_references.exists(): | ||
| return | ||
| edges_by_environment_id: dict[int, dict[FeatureName, list[DependencyEdge]]] = {} | ||
| for override in ( | ||
| get_all_live_or_scheduled_overrides() | ||
| .filter(segment=segment) | ||
| .select_related("environment", "feature") | ||
|
khvn26 marked this conversation as resolved.
|
||
| ): | ||
| if override.environment_id not in edges_by_environment_id: | ||
| edges_by_environment_id[override.environment_id] = _get_dependency_edges( | ||
| override.environment | ||
| ) | ||
| edges = edges_by_environment_id[override.environment_id] | ||
| pending: list[DependencyPath] = [ | ||
| [edge] for edge in edges[override.feature.name] | ||
| ] | ||
| visited: set[str] = set() | ||
| while pending: | ||
| path = pending.pop() | ||
| if (prerequisite_feature_name := path[-1]["needs"]) in visited: | ||
| continue | ||
| if prerequisite_feature_name == override.feature.name: | ||
| logger.info( | ||
| "dependencies.create_failed", | ||
| organisation__id=segment.project.organisation_id, | ||
| project__id=segment.project_id, | ||
| environment__key=override.environment.api_key, | ||
| feature__name=override.feature.name, | ||
| prerequisite_feature__name=path[0]["needs"], | ||
| ) | ||
| raise CircularDependencyError( | ||
| environment={ | ||
| "key": override.environment.api_key, | ||
| "name": override.environment.name, | ||
| }, | ||
| path=path, | ||
| ) | ||
| visited.add(prerequisite_feature_name) | ||
| pending += [[*path, edge] for edge in edges[prerequisite_feature_name]] | ||
|
|
||
|
|
||
| def _get_dependency_edges( | ||
| environment: Environment, | ||
| ) -> dict[FeatureName, list[DependencyEdge]]: | ||
| edges: dict[FeatureName, list[DependencyEdge]] = defaultdict(list) | ||
| for ( | ||
| feature_name, | ||
| prerequisite_feature_name, | ||
| segment_id, | ||
| segment_name, | ||
| condition_json_path, | ||
| ) in ( | ||
| get_all_live_or_scheduled_overrides() | ||
| .filter( | ||
| environment=environment, | ||
| segment__flag_references__isnull=False, | ||
| ) | ||
| .values_list( | ||
| "feature__name", | ||
| "segment__flag_references__prerequisite_feature__name", | ||
| "segment_id", | ||
| "segment__name", | ||
| "segment__flag_references__condition_json_path", | ||
| ) | ||
| ): | ||
| edges[feature_name].append( | ||
| { | ||
| "feature": feature_name, | ||
| "needs": prerequisite_feature_name, | ||
| "segment": { | ||
| "id": segment_id, | ||
| "name": segment_name, | ||
| "condition_json_path": condition_json_path, | ||
| }, | ||
| } | ||
| ) | ||
| return edges | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.