-
Notifications
You must be signed in to change notification settings - Fork 526
feat(experimentation): environment-scoped metrics & experiment results #7674
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
Draft
gagantrivedi
wants to merge
1
commit into
main
Choose a base branch
from
feat/experiment-metrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,013
−5
Draft
Changes from all commits
Commits
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
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
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 |
|---|---|---|
| @@ -1,10 +1,15 @@ | ||
| from rest_framework.routers import DefaultRouter | ||
| from rest_framework_nested import routers # type: ignore[import-untyped] | ||
|
|
||
| from experimentation.views import ExperimentViewSet | ||
| from experimentation.views import ExperimentMetricViewSet, ExperimentViewSet | ||
|
|
||
| app_name = "experiments" | ||
|
|
||
| router = DefaultRouter() | ||
| router = routers.DefaultRouter() | ||
| router.register(r"", ExperimentViewSet, basename="experiments") | ||
|
|
||
| urlpatterns = router.urls | ||
| experiments_router = routers.NestedSimpleRouter(router, r"", lookup="experiment") | ||
| experiments_router.register( | ||
| r"metrics", ExperimentMetricViewSet, basename="experiment-metrics" | ||
| ) | ||
|
|
||
| urlpatterns = router.urls + experiments_router.urls |
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,10 @@ | ||
| from rest_framework.routers import DefaultRouter | ||
|
|
||
| from experimentation.views import MetricViewSet | ||
|
|
||
| app_name = "experiment_metrics" | ||
|
|
||
| router = DefaultRouter() | ||
| router.register(r"", MetricViewSet, basename="metrics") | ||
|
|
||
| urlpatterns = router.urls |
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,124 @@ | ||
| # Generated by Django 5.2.14 on 2026-06-02 10:47 | ||
|
|
||
| import django.db.models.deletion | ||
| import uuid | ||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ("environments", "0037_add_uuid_field"), | ||
| ("experimentation", "0004_experiment"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.CreateModel( | ||
| name="Metric", | ||
| fields=[ | ||
| ( | ||
| "id", | ||
| models.AutoField( | ||
| auto_created=True, | ||
| primary_key=True, | ||
| serialize=False, | ||
| verbose_name="ID", | ||
| ), | ||
| ), | ||
| ( | ||
| "deleted_at", | ||
| models.DateTimeField( | ||
| blank=True, | ||
| db_index=True, | ||
| default=None, | ||
| editable=False, | ||
| null=True, | ||
| ), | ||
| ), | ||
| ( | ||
| "uuid", | ||
| models.UUIDField(default=uuid.uuid4, editable=False, unique=True), | ||
| ), | ||
| ("name", models.CharField(max_length=255)), | ||
| ("description", models.TextField(blank=True, default="")), | ||
| ( | ||
| "aggregation", | ||
| models.CharField( | ||
| choices=[ | ||
| ("count", "Count"), | ||
| ("sum", "Sum"), | ||
| ("mean", "Mean"), | ||
| ("occurrence", "Occurrence (event happened at least once)"), | ||
| ], | ||
| default="mean", | ||
| max_length=20, | ||
| ), | ||
| ), | ||
| ("definition", models.JSONField()), | ||
| ("created_at", models.DateTimeField(auto_now_add=True)), | ||
| ("updated_at", models.DateTimeField(auto_now=True)), | ||
| ( | ||
| "environment", | ||
| models.ForeignKey( | ||
| on_delete=django.db.models.deletion.CASCADE, | ||
| related_name="metrics", | ||
| to="environments.environment", | ||
| ), | ||
| ), | ||
| ], | ||
| options={ | ||
| "abstract": False, | ||
| }, | ||
| ), | ||
| migrations.CreateModel( | ||
| name="ExperimentMetric", | ||
| fields=[ | ||
| ( | ||
| "id", | ||
| models.AutoField( | ||
| auto_created=True, | ||
| primary_key=True, | ||
| serialize=False, | ||
| verbose_name="ID", | ||
| ), | ||
| ), | ||
| ( | ||
| "expected_direction", | ||
| models.CharField( | ||
| choices=[ | ||
| ("increase", "Increase"), | ||
| ("decrease", "Decrease"), | ||
| ("not_increase", "Should not increase"), | ||
| ("not_decrease", "Should not decrease"), | ||
| ], | ||
| max_length=20, | ||
| ), | ||
| ), | ||
| ("created_at", models.DateTimeField(auto_now_add=True)), | ||
| ( | ||
| "experiment", | ||
| models.ForeignKey( | ||
| on_delete=django.db.models.deletion.CASCADE, | ||
| related_name="experiment_metrics", | ||
| to="experimentation.experiment", | ||
| ), | ||
| ), | ||
| ( | ||
| "metric", | ||
| models.ForeignKey( | ||
| on_delete=django.db.models.deletion.CASCADE, | ||
| related_name="experiment_metrics", | ||
| to="experimentation.metric", | ||
| ), | ||
| ), | ||
| ], | ||
| options={ | ||
| "constraints": [ | ||
| models.UniqueConstraint( | ||
| fields=("experiment", "metric"), | ||
| name="metric_attached_once_per_experiment", | ||
| ) | ||
| ], | ||
| }, | ||
| ), | ||
| ] |
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
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
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 |
|---|---|---|
|
|
@@ -5,6 +5,8 @@ | |
| from environments.models import Environment | ||
| from experimentation.models import ( | ||
| Experiment, | ||
| ExperimentMetric, | ||
| Metric, | ||
| WarehouseConnection, | ||
| WarehouseType, | ||
| ) | ||
|
|
@@ -76,6 +78,84 @@ def _validate_snowflake_config(config: dict[str, Any]) -> SnowflakeConfig: | |
| return merged | ||
|
|
||
|
|
||
| class MetricSerializer(serializers.ModelSerializer): # type: ignore[type-arg] | ||
| class Meta: | ||
| model = Metric | ||
| fields = ( | ||
| "id", | ||
| "name", | ||
| "description", | ||
| "aggregation", | ||
| "definition", | ||
| "created_at", | ||
| "updated_at", | ||
| ) | ||
| read_only_fields = ( | ||
| "id", | ||
| "created_at", | ||
| "updated_at", | ||
| ) | ||
|
|
||
| def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: | ||
| definition: Any = attrs.get( | ||
| "definition", getattr(self.instance, "definition", None) | ||
| ) | ||
| error = self._validate_definition(definition) | ||
| if error: | ||
| raise serializers.ValidationError({"definition": error}) | ||
| return attrs | ||
|
|
||
| @staticmethod | ||
| def _validate_definition(definition: Any) -> str | None: | ||
| if not isinstance(definition, dict): | ||
| return "Definition must be an object." | ||
|
|
||
| event = definition.get("event") | ||
| if not event or not isinstance(event, str): | ||
| return "Definition must specify a non-empty 'event'." | ||
|
|
||
| return None | ||
|
|
||
|
|
||
| class ExperimentMetricSerializer(serializers.ModelSerializer): # type: ignore[type-arg] | ||
| metric = serializers.PrimaryKeyRelatedField( # type: ignore[var-annotated] | ||
| queryset=Metric.objects.all(), | ||
| ) | ||
| metric_name = serializers.CharField(source="metric.name", read_only=True) | ||
| aggregation = serializers.CharField(source="metric.aggregation", read_only=True) | ||
|
|
||
|
Comment on lines
+120
to
+126
|
||
| class Meta: | ||
| model = ExperimentMetric | ||
| fields = ( | ||
| "id", | ||
| "metric", | ||
| "metric_name", | ||
| "aggregation", | ||
| "expected_direction", | ||
| "created_at", | ||
| ) | ||
| read_only_fields = ("id", "created_at") | ||
|
|
||
| def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: | ||
| experiment: Experiment = self.context["experiment"] | ||
| metric: Metric = attrs.get("metric", getattr(self.instance, "metric", None)) | ||
|
|
||
| if metric.environment_id != experiment.environment_id: | ||
| raise serializers.ValidationError( | ||
| {"metric": "Metric must belong to the experiment's environment."} | ||
| ) | ||
|
|
||
| attached = experiment.experiment_metrics.all() | ||
| if isinstance(self.instance, ExperimentMetric): | ||
| attached = attached.exclude(pk=self.instance.pk) | ||
|
|
||
| if "metric" in attrs and attached.filter(metric=metric).exists(): | ||
| raise serializers.ValidationError( | ||
| {"metric": "Metric is already attached to this experiment."} | ||
| ) | ||
| return attrs | ||
|
Comment on lines
+139
to
+156
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should add defensive checks and business logic validation to
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
experiment: Experiment = self.context["experiment"]
if experiment.status == "completed":
raise serializers.ValidationError(
"Cannot modify metrics of a completed experiment."
)
metric: Metric = attrs.get("metric", getattr(self.instance, "metric", None))
if not metric:
raise serializers.ValidationError({"metric": "Metric is required."})
if metric.deleted_at is not None:
raise serializers.ValidationError({"metric": "Cannot attach a deleted metric."})
if metric.environment_id != experiment.environment_id:
raise serializers.ValidationError(
{"metric": "Metric must belong to the experiment's environment."}
)
attached = experiment.experiment_metrics.all()
if isinstance(self.instance, ExperimentMetric):
attached = attached.exclude(pk=self.instance.pk)
if "metric" in attrs and attached.filter(metric=metric).exists():
raise serializers.ValidationError(
{"metric": "Metric is already attached to this experiment."}
)
return attrs |
||
|
|
||
|
|
||
| class ExperimentSerializer(serializers.ModelSerializer): # type: ignore[type-arg] | ||
| class Meta: | ||
| model = Experiment | ||
|
|
||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Interesting. So you see it in the relation Experiment x Metrics. I could see it too there although i'm wondering if that's a reality.
Let's say we have those metrics:
Is there a world in which we'd want an experiment to push it in the other direction ? If not i'd stick it to the metrics and maybe have the possibility to override it in an experiment (in v2)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok I think i'm actually mixing 2 things:
expected_directionthat we should keep