-
Notifications
You must be signed in to change notification settings - Fork 573
Expand file tree
/
Copy pathservices.py
More file actions
1298 lines (1150 loc) · 43.8 KB
/
Copy pathservices.py
File metadata and controls
1298 lines (1150 loc) · 43.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import json
import time
import typing
from dataclasses import replace
from functools import lru_cache
import structlog
from clickhouse_connect.driver.exceptions import ClickHouseError
from clickhouse_driver import Client
from clickhouse_driver.util.helpers import parse_url
from django.conf import settings
from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils import timezone
from flag_engine.segments.constants import ALL_RULE, PERCENTAGE_SPLIT
from rest_framework.exceptions import ValidationError
from audit.models import AuditLog
from audit.related_object_type import RelatedObjectType
from core.dataclasses import AuthorData
from environments.tasks import rebuild_environment_document
from experimentation import warehouse_delivery_service
from experimentation.constants import (
CONTROL_VARIANT_KEY,
EXPERIMENT_FLAG,
EXPOSURE_EVENT_NAME,
EXPOSURE_HOURLY_BUCKET_MAX_WINDOW,
RESULTS_MIN_CONVERSIONS_PER_VARIANT,
RESULTS_MIN_IDENTITIES_PER_VARIANT,
SRM_MIN_TOTAL_IDENTITIES,
WAREHOUSE_CONNECTION_FLAG,
)
from experimentation.dataclasses import (
ExposureBucket,
ExposuresSummary,
ExposuresTimeseries,
ExposuresTimeseriesPoint,
MetricResult,
MetricSpec,
ResultsAggregates,
ResultsSummary,
RolloutSpec,
WarehouseEventNames,
WarehouseEventStats,
)
from experimentation.metrics import (
flagsmith_experimentation_warehouse_connection_verifications_total,
flagsmith_experimentation_warehouse_delivery_objects_total,
flagsmith_experimentation_warehouse_delivery_runs_total,
)
from experimentation.models import (
VALID_STATUS_TRANSITIONS,
Experiment,
ExperimentStatus,
MetricAggregation,
MetricDirection,
WarehouseConnection,
WarehouseConnectionStatus,
WarehouseDeliveryLog,
WarehouseDeliveryOutcome,
WarehouseType,
)
from experimentation.results_query import _EXPOSURES_CTE, ResultsQueryBuilder
from experimentation.stats import (
Inference,
VariantStats,
compare_to_control,
srm_p_value,
)
from features.feature_states.models import API_VALUE_TYPES
from features.models import FeatureState
from features.value_types import BOOLEAN, STRING
from features.versioning.dataclasses import FlagChangeSet, MultivariateValueChangeSet
from features.versioning.versioning_service import (
get_environment_flags_list,
update_flag,
update_multivariate_values,
)
from integrations.flagsmith.client import get_openfeature_client
from segments.models import Condition, Segment, SegmentRule
# TODO: Delete alias as per https://github.com/Flagsmith/flagsmith/issues/7818
from segments.types import SegmentRule as SegmentRuleType
if typing.TYPE_CHECKING:
from collections.abc import Sequence
from datetime import datetime
from clickhouse_connect.driver.client import Client as ClickHouseHTTPClient
from environments.models import Environment
from experimentation.models import Metric
from experimentation.types import ExposureGranularity
from features.feature_states.models import FeatureValueType
from features.models import FeatureStateValue
from organisations.models import Organisation
from users.models import FFAdminUser
logger = structlog.get_logger("warehouse")
CLICKHOUSE_CONNECT_TIMEOUT_SECONDS = 5
CLICKHOUSE_QUERY_TIMEOUT_SECONDS = 30
CLICKHOUSE_BACKGROUND_QUERY_TIMEOUT_SECONDS = 120
CLICKHOUSE_VERIFY_TIMEOUT_SECONDS = 5
CLICKHOUSE_EVENT_NAMES_TIMEOUT_SECONDS = 15
CUSTOMER_EVENT_STATS_CACHE_SECONDS = 60
EVENT_NAMES_CACHE_SECONDS = 300
CUSTOMER_EVENT_NAMES_FAILURE_CACHE_SECONDS = 60
WAREHOUSE_EVENT_NAMES_LIMIT = 500
_CUSTOMER_EVENT_UNAVAILABLE = "unavailable"
def _customer_cache_key(kind: str, connection: "WarehouseConnection") -> str:
"""Key cached warehouse reads by the connection's non-secret details, so a
config or type change can neither serve nor store stale reads. Credentials
stay out of the key material: they don't determine what the warehouse
holds, so rotating them keeps the cache valid."""
details = json.dumps(
[connection.warehouse_type, connection.config],
sort_keys=True,
)
digest = hashlib.sha256(details.encode()).hexdigest()[:12]
return f"experimentation:customer_{kind}:{connection.id}:{digest}"
# A delivery run stops taking on new objects after this long, leaving room for
# the slowest possible in-flight insert to still land inside the task timeout.
DELIVERY_TIME_BUDGET_SECONDS = 210
def is_warehouse_feature_enabled(organisation: Organisation) -> bool:
return get_openfeature_client().get_boolean_value(
WAREHOUSE_CONNECTION_FLAG,
default_value=False,
evaluation_context=organisation.openfeature_evaluation_context,
)
def is_experiment_feature_enabled(organisation: Organisation) -> bool:
return get_openfeature_client().get_boolean_value(
EXPERIMENT_FLAG,
default_value=False,
evaluation_context=organisation.openfeature_evaluation_context,
)
def get_experiment_flag_config(
organisation: Organisation,
) -> dict[str, object]:
if not is_experiment_feature_enabled(organisation):
return {}
raw = get_openfeature_client().get_string_value(
EXPERIMENT_FLAG,
default_value="{}",
evaluation_context=organisation.openfeature_evaluation_context,
)
try:
parsed = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return {}
return parsed if isinstance(parsed, dict) else {}
def ensure_flagsmith_warehouse_connection(
environment: Environment,
) -> WarehouseConnection | None:
config = get_experiment_flag_config(environment.project.organisation)
if not config.get("auto_connect_warehouse"):
return None
if WarehouseConnection.objects.filter(
environment=environment,
deleted_at__isnull=True,
).exists():
return None
try:
connection: WarehouseConnection = WarehouseConnection.objects.create(
environment=environment,
warehouse_type=WarehouseType.FLAGSMITH,
name="Flagsmith",
)
return connection
except IntegrityError:
return None
@lru_cache(maxsize=2)
def _get_clickhouse_client(
send_receive_timeout: int = CLICKHOUSE_QUERY_TIMEOUT_SECONDS,
) -> Client:
"""Build a clickhouse-driver client for the experimentation event store.
The database is taken from the DSN path, so queries can reference the
`events` table unqualified. Connect and query timeouts are bounded unless the
DSN overrides them. One client is cached per requested timeout.
"""
host, kwargs = parse_url(settings.EXPERIMENTATION_CLICKHOUSE_URL)
kwargs.setdefault("connect_timeout", CLICKHOUSE_CONNECT_TIMEOUT_SECONDS)
kwargs.setdefault("send_receive_timeout", send_receive_timeout)
kwargs.setdefault("client_name", settings.CLICKHOUSE_CONNECTION_CLIENT_NAME)
return Client(host, **kwargs)
_CLICKHOUSE_EVENT_NAMES_QUERY = (
"SELECT event FROM events "
"WHERE environment_key = %(environment_key)s "
"GROUP BY event ORDER BY max(timestamp) DESC LIMIT %(limit)s"
)
def _event_names_query_params(environment_key: str) -> dict[str, str | int]:
# Fetch one row past the limit so truncation is detectable.
return {
"environment_key": environment_key,
"limit": WAREHOUSE_EVENT_NAMES_LIMIT + 1,
}
def _build_event_names(
rows: "Sequence[Sequence[typing.Any]]",
) -> WarehouseEventNames:
names = [event for (event,) in rows]
return WarehouseEventNames(
events=names[:WAREHOUSE_EVENT_NAMES_LIMIT],
is_truncated=len(names) > WAREHOUSE_EVENT_NAMES_LIMIT,
)
EVENT_NAMES_SUPPORTED_WAREHOUSE_TYPES = (
WarehouseType.FLAGSMITH,
WarehouseType.CLICKHOUSE,
)
def get_warehouse_event_names(
connection: "WarehouseConnection",
environment_key: str,
) -> WarehouseEventNames | None:
if connection.warehouse_type == WarehouseType.CLICKHOUSE:
return _get_customer_clickhouse_event_names(connection, environment_key)
if connection.warehouse_type == WarehouseType.FLAGSMITH:
return _get_flagsmith_clickhouse_event_names(environment_key)
raise ValueError(f"Unsupported warehouse type: {connection.warehouse_type}")
def _get_flagsmith_clickhouse_event_names(
environment_key: str,
) -> WarehouseEventNames | None:
if not settings.EXPERIMENTATION_CLICKHOUSE_URL:
return None
cache_key = f"experimentation:event_names:{environment_key}"
cached = cache.get(cache_key)
if isinstance(cached, WarehouseEventNames):
return cached
try:
rows = _get_clickhouse_client().execute(
_CLICKHOUSE_EVENT_NAMES_QUERY,
_event_names_query_params(environment_key),
)
except Exception:
logger.warning(
"connection.event_names_failed",
environment__key=environment_key,
exc_info=True,
)
return None
event_names = _build_event_names(rows)
cache.set(cache_key, event_names, EVENT_NAMES_CACHE_SECONDS)
return event_names
_EVENT_STATS_QUERY = (
"SELECT count() AS total, uniqExact(event) AS unique "
"FROM events WHERE environment_key = %(environment_key)s"
)
def _build_event_stats(
rows: Sequence[Sequence[typing.Any]],
) -> WarehouseEventStats:
total, unique = rows[0] if rows else (0, 0)
return WarehouseEventStats(
total_events_received=int(total),
unique_events_count=int(unique),
)
def get_warehouse_event_stats(environment_key: str) -> WarehouseEventStats:
"""Return event counts recorded for `environment_key` in the warehouse."""
rows = _get_clickhouse_client().execute(
_EVENT_STATS_QUERY,
{"environment_key": environment_key},
)
return _build_event_stats(rows)
EXPOSURE_BUCKETS_QUERY = (
_EXPOSURES_CTE
+ """
SELECT
quarantined,
variant,
{bucket_function}(first_exposure, 'UTC') AS bucket,
count() AS first_exposed_identities
FROM exposures
GROUP BY quarantined, variant, bucket
ORDER BY bucket
"""
)
_EXPOSURE_BUCKET_FUNCTIONS: dict[str, str] = {
"hour": "toStartOfHour",
"day": "toStartOfDay",
}
def compute_exposures_summary(
*,
environment_key: str,
feature_name: str,
window_start: datetime,
window_end: datetime,
) -> ExposuresSummary:
granularity = _select_exposure_granularity(window_start, window_end)
buckets = get_exposure_buckets(
environment_key=environment_key,
feature_name=feature_name,
window_start=window_start,
window_end=window_end,
granularity=granularity,
)
return build_exposures_summary(buckets, granularity=granularity)
def build_exposures_summary(
buckets: Sequence[ExposureBucket],
*,
granularity: ExposureGranularity,
) -> ExposuresSummary:
return ExposuresSummary(
excluded_identities=sum(
b.first_exposed_identities for b in buckets if b.quarantined
),
timeseries=ExposuresTimeseries(
granularity=granularity,
points=_timeseries_points([b for b in buckets if not b.quarantined]),
),
)
def _timeseries_points(
buckets: Sequence[ExposureBucket],
) -> list[ExposuresTimeseriesPoint]:
new_identities_by_bucket: dict[datetime, dict[str, int]] = {}
for b in buckets:
new_identities_by_bucket.setdefault(b.bucket, {})[b.variant] = (
b.first_exposed_identities
)
return [
ExposuresTimeseriesPoint(
bucket=bucket_start.isoformat(),
new_identities=new_identities_by_bucket[bucket_start],
)
for bucket_start in sorted(new_identities_by_bucket)
]
def _select_exposure_granularity(
window_start: datetime,
window_end: datetime,
) -> ExposureGranularity:
if window_end - window_start <= EXPOSURE_HOURLY_BUCKET_MAX_WINDOW:
return "hour"
return "day"
def get_exposure_buckets(
*,
environment_key: str,
feature_name: str,
window_start: datetime,
window_end: datetime,
granularity: ExposureGranularity,
) -> list[ExposureBucket]:
rows = _get_clickhouse_client(
send_receive_timeout=CLICKHOUSE_BACKGROUND_QUERY_TIMEOUT_SECONDS,
).execute(
EXPOSURE_BUCKETS_QUERY.format(
bucket_function=_EXPOSURE_BUCKET_FUNCTIONS[granularity]
),
{
"environment_key": environment_key,
"exposure_event": EXPOSURE_EVENT_NAME,
"feature_name": feature_name,
"window_start": window_start,
"window_end": window_end,
},
)
return [
ExposureBucket(
variant=variant,
bucket=bucket,
first_exposed_identities=int(first_exposed_identities),
quarantined=bool(quarantined),
)
for quarantined, variant, bucket, first_exposed_identities in rows
]
def get_metric_variant_stats(
*,
environment_key: str,
feature_name: str,
window_start: datetime,
window_end: datetime,
specs: Sequence[MetricSpec],
) -> ResultsAggregates:
"""Run the warehouse query, returning per-variant identity counts and, per
metric, per-variant sufficient statistics."""
builder = ResultsQueryBuilder(specs)
params: dict[str, object] = {
"environment_key": environment_key,
"exposure_event": EXPOSURE_EVENT_NAME,
"feature_name": feature_name,
"window_start": window_start,
"window_end": window_end,
}
builder.add_metric_params(params)
rows, columns = _get_clickhouse_client(
send_receive_timeout=CLICKHOUSE_BACKGROUND_QUERY_TIMEOUT_SECONDS,
).execute(builder.build_query(), params, with_column_types=True)
exposure_counts, metric_stats = builder.decode_rows(
rows, [name for name, _type in columns]
)
return ResultsAggregates(
specs=list(specs),
exposure_counts=exposure_counts,
metric_stats=metric_stats,
)
def build_results_summary(
aggregates: ResultsAggregates,
*,
expected_shares: dict[str, float],
) -> ResultsSummary:
exposure_counts = aggregates.exposure_counts
total = sum(exposure_counts.values())
if expected_shares and total >= SRM_MIN_TOTAL_IDENTITIES:
srm = srm_p_value(
[exposure_counts.get(variant, 0) for variant in expected_shares],
list(expected_shares.values()),
)
else:
srm = None
return ResultsSummary(
srm_p_value=srm,
metrics=[
MetricResult(
metric_id=spec.metric_id,
variants=aggregates.metric_stats.get(spec.metric_id, {}),
inference=_metric_inference(
spec, aggregates.metric_stats.get(spec.metric_id, {})
),
)
for spec in aggregates.specs
],
)
def compute_results_summary(
experiment: "Experiment",
*,
window_start: "datetime",
window_end: "datetime",
) -> ResultsSummary:
"""Gather an experiment's metric statistics from the warehouse and reduce
them to the stored results payload."""
specs = _experiment_metric_specs(experiment)
aggregates = get_metric_variant_stats(
environment_key=experiment.environment.api_key,
feature_name=experiment.feature.name,
window_start=window_start,
window_end=window_end,
specs=specs,
)
return build_results_summary(
aggregates,
expected_shares=_expected_variant_shares(experiment),
)
def _experiment_metric_specs(experiment: "Experiment") -> list[MetricSpec]:
return [
MetricSpec(
metric_id=experiment_metric.metric_id,
event=experiment_metric.metric.definition["event"],
aggregation=experiment_metric.metric.aggregation,
lower_is_better=(
experiment_metric.metric.direction == MetricDirection.DOWN
),
)
for experiment_metric in experiment.experiment_metrics.select_related("metric")
]
def _expected_variant_shares(experiment: "Experiment") -> dict[str, float]:
"""The traffic split SRM tests against: each multivariate option's
environment allocation, with ``control`` taking the unallocated remainder.
Empty when the feature has no usable allocations, skipping the SRM check."""
# TODO: read the split from the percentage-split segment override feature
# state once that's implemented, rather than the environment default.
feature_state = (
FeatureState.objects.get_live_feature_states(
environment=experiment.environment,
additional_filters=Q(feature_segment__isnull=True, identity__isnull=True),
feature_id=experiment.feature_id,
)
.prefetch_related(
"multivariate_feature_state_values__multivariate_feature_option"
)
# Highest id is the current version, matching how Environment selects
# active feature states (Max("id")); the default ordering is ascending.
.order_by("-id")
.first()
)
if feature_state is None:
return {}
shares: dict[str, float] = {}
allocated = 0.0
for mv_value in feature_state.multivariate_feature_state_values.all():
key = mv_value.multivariate_feature_option.key
if key is None:
# An unkeyed option's traffic can't be attributed to a variant;
# counting it as control would inflate control's expected share and
# raise a false SRM alarm, so skip the check entirely.
logger.error(
"srm.unkeyed_variant",
experiment__id=experiment.id,
environment__id=experiment.environment_id,
feature__id=experiment.feature_id,
)
return {}
shares[key] = mv_value.percentage_allocation / 100
allocated += mv_value.percentage_allocation
if not shares:
return {}
if allocated > 100:
# A misconfigured feature whose options over-allocate; control's share
# would be negative, so there's no valid split to test against.
logger.error(
"srm.overallocated",
experiment__id=experiment.id,
environment__id=experiment.environment_id,
feature__id=experiment.feature_id,
)
return {}
shares[CONTROL_VARIANT_KEY] = (100 - allocated) / 100
return shares
def _metric_inference(
spec: MetricSpec,
variants: dict[str, VariantStats],
) -> dict[str, Inference | None]:
control = variants.get(CONTROL_VARIANT_KEY)
return {
variant_key: _infer_treatment(spec, control, treatment)
for variant_key, treatment in variants.items()
if variant_key != CONTROL_VARIANT_KEY
}
def _infer_treatment(
spec: MetricSpec,
control: VariantStats | None,
treatment: VariantStats,
) -> Inference | None:
# Product floor for showing a result at all; compare_to_control applies its
# own independent guards (e.g. zero control mean) on top of this.
if (
control is None
or control.n < RESULTS_MIN_IDENTITIES_PER_VARIANT
or treatment.n < RESULTS_MIN_IDENTITIES_PER_VARIANT
):
return None
if spec.aggregation == MetricAggregation.OCCURRENCE and (
control.sum < RESULTS_MIN_CONVERSIONS_PER_VARIANT
or treatment.sum < RESULTS_MIN_CONVERSIONS_PER_VARIANT
):
return None
inference = compare_to_control(control, treatment)
if inference is not None and spec.lower_is_better:
# "Winning" means moving the metric the good way; for a lower-is-better
# metric that's a fall, so the chance of winning is the chance lift < 0.
inference = replace(inference, chance_to_win=1.0 - inference.chance_to_win)
return inference
def _resolve_audit_log_author(
user: FFAdminUser,
) -> dict[str, int | None]:
if getattr(user, "is_master_api_key_user", False):
return {"author_id": None, "master_api_key_id": user.key.id}
return {"author_id": user.pk, "master_api_key_id": None}
def create_warehouse_audit_log(
connection: WarehouseConnection,
user: FFAdminUser,
*,
action: str,
) -> None:
AuditLog.objects.create(
environment=connection.environment,
project=connection.environment.project,
**_resolve_audit_log_author(user),
related_object_id=connection.id,
related_object_type=RelatedObjectType.WAREHOUSE_CONNECTION.name,
log=(
f"Warehouse connection {action} for environment "
f"{connection.environment.name}"
),
)
def create_metric_audit_log(
metric: Metric,
user: FFAdminUser,
*,
action: str,
) -> None:
AuditLog.objects.create(
environment=metric.environment,
project=metric.environment.project,
**_resolve_audit_log_author(user),
related_object_id=metric.id,
related_object_type=RelatedObjectType.METRIC.name,
log=f"Metric '{metric.name}' {action}",
)
def create_experiment_audit_log(
experiment: Experiment,
user: FFAdminUser,
*,
action: str,
) -> None:
AuditLog.objects.create(
environment=experiment.environment,
project=experiment.environment.project,
**_resolve_audit_log_author(user),
related_object_id=experiment.id,
related_object_type=RelatedObjectType.EXPERIMENT.name,
log=(
f"Experiment '{experiment.name}' {action} for environment "
f"{experiment.environment.name}"
),
)
def transition_experiment_status(
experiment: Experiment,
target_status: str,
user: FFAdminUser,
) -> Experiment:
valid_targets = VALID_STATUS_TRANSITIONS.get(experiment.status, set())
if target_status not in valid_targets:
raise ValueError(
f"Cannot transition from '{experiment.status}' to '{target_status}'."
)
experiment.status = target_status
if target_status == ExperimentStatus.RUNNING and not experiment.started_at:
experiment.started_at = timezone.now()
elif target_status == ExperimentStatus.COMPLETED:
experiment.ended_at = timezone.now()
experiment.save()
create_experiment_audit_log(experiment, user, action=target_status)
return experiment
def _rollout_segment_rules(rollout_percentage: float) -> list[SegmentRuleType]:
return [
{
"type": ALL_RULE,
"conditions": [
{
"property": "$.identity.key",
"operator": PERCENTAGE_SPLIT,
"value": str(rollout_percentage),
"description": None,
}
],
"rules": [],
}
]
def _create_rollout_segment(
experiment: Experiment, rollout_percentage: float
) -> Segment:
segment: Segment = Segment.objects.create(
name=f"experiment-{experiment.id}-rollout",
project=experiment.feature.project,
is_system_segment=True,
rules_data=_rollout_segment_rules(rollout_percentage),
)
# TODO: Delete as per https://github.com/Flagsmith/flagsmith/issues/7818
rule = SegmentRule.objects.create(segment=segment, type=SegmentRule.ALL_RULE)
Condition.objects.create(
rule=rule,
operator=PERCENTAGE_SPLIT,
property="$.identity.key",
value=str(rollout_percentage),
)
return segment
def validate_rollout_spec(experiment: Experiment, spec: RolloutSpec) -> None:
option_ids = [v.multivariate_feature_option_id for v in spec.multivariate_values]
if len(option_ids) != len(set(option_ids)):
raise ValidationError("Multivariate options must be unique")
valid_option_ids = set(
experiment.feature.multivariate_options.values_list("id", flat=True)
)
if invalid := set(option_ids) - valid_option_ids:
raise ValidationError(
f"Multivariate options {sorted(invalid)} do not belong to the feature"
)
total = sum(v.percentage_allocation for v in spec.multivariate_values)
if total > 100:
raise ValidationError(
f"Multivariate allocations must not exceed 100%, got {total}%."
)
def _sync_rollout_segment(experiment: Experiment, rollout_percentage: float) -> Segment:
segment = experiment.rollout_segment
if segment is not None:
segment.rules_data = _rollout_segment_rules(rollout_percentage)
segment.save(update_fields=["rules_data"])
# TODO: Delete as per https://github.com/Flagsmith/flagsmith/issues/7818
condition = Condition.objects.get(
rule__segment=segment, operator=PERCENTAGE_SPLIT
)
condition.value = str(rollout_percentage)
condition.save()
return segment
segment = _create_rollout_segment(experiment, rollout_percentage)
experiment.rollout_segment = segment
experiment.save()
return segment
def _get_live_rollout_override(experiment: Experiment) -> FeatureState | None:
flags = get_environment_flags_list(
environment=experiment.environment,
additional_filters=Q(
feature_id=experiment.feature_id,
feature_segment__segment_id=experiment.rollout_segment_id,
identity__isnull=True,
),
)
return flags[0] if flags else None
def _update_live_feature_state(
feature_state: FeatureState, change_set: FlagChangeSet
) -> None:
feature_state.enabled = change_set.enabled
feature_state.save()
feature_state.feature_state_value.set_value(
change_set.feature_state_value, change_set.type_
)
feature_state.feature_state_value.save()
update_multivariate_values(feature_state, change_set.multivariate_values)
def _update_rollout_in_place(experiment: Experiment, change_set: FlagChangeSet) -> None:
"""Write the rollout-segment override, keeping variant assignment stable.
Under v2 versioning, ``update_flag`` clones the override into a fresh feature
state on every call. Since the multivariate split is salted on the feature
state id, that would re-randomise control/variant for already-enrolled
identities on each rollout update. Once the override exists, mutate it in
place instead (no version is published). Creating the override, and v1
versioning, still go through ``update_flag``, which already reuses the
feature state.
This is a temporary solution until we find a permanent fix for the
underlying salting issue: https://github.com/Flagsmith/flagsmith/issues/7913
"""
if experiment.environment.use_v2_feature_versioning and (
override := _get_live_rollout_override(experiment)
):
_update_live_feature_state(override, change_set)
return
update_flag(experiment.environment, experiment.feature, change_set)
def _reset_default_allocations_to_control(
experiment: Experiment, author: AuthorData
) -> None:
"""Zero every variant's allocation on the feature's environment-default
feature state, leaving control (the unallocated remainder) at 100%.
Run once, when the rollout segment is first created: identities outside the
rollout cohort should all receive control while the experiment runs.
"""
(default_state,) = get_environment_flags_list(
environment=experiment.environment,
additional_filters=Q(
feature_id=experiment.feature_id,
feature_segment__isnull=True,
identity__isnull=True,
),
)
str_value, value_type = _serialize_feature_state_value(
default_state.feature_state_value
)
update_flag(
experiment.environment,
experiment.feature,
FlagChangeSet(
author=author,
enabled=default_state.enabled,
feature_state_value=str_value,
type_=value_type,
multivariate_values=[
MultivariateValueChangeSet(
multivariate_feature_option_id=option_id,
percentage_allocation=0,
)
for option_id in experiment.feature.multivariate_options.values_list(
"id", flat=True
)
],
),
)
def apply_experiment_rollout(experiment: Experiment, spec: RolloutSpec) -> None:
validate_rollout_spec(experiment, spec)
environment_id = experiment.environment_id
with transaction.atomic():
experiment.refresh_from_db(from_queryset=Experiment.objects.select_for_update())
if experiment.status == ExperimentStatus.COMPLETED:
raise ValidationError(
f"Cannot change the rollout of a {experiment.status} experiment."
)
is_first_rollout = experiment.rollout_segment_id is None
segment = _sync_rollout_segment(experiment, spec.rollout_percentage)
if is_first_rollout:
_reset_default_allocations_to_control(experiment, spec.author)
_update_rollout_in_place(
experiment,
FlagChangeSet(
author=spec.author,
enabled=spec.enabled,
feature_state_value=spec.feature_state_value,
type_=spec.value_type,
segment_id=segment.id,
multivariate_values=spec.multivariate_values,
),
)
# Segment condition changes don't trigger a rebuild on their own.
transaction.on_commit(
lambda: rebuild_environment_document.delay(
kwargs={"environment_id": environment_id}
)
)
def _serialize_feature_state_value(
value: FeatureStateValue,
) -> tuple[str, FeatureValueType]:
"""Render a stored feature state value as the (string, API type) pair that
a `FlagChangeSet` expects."""
if value.value is None:
return "", "string"
return (
str(value.value).lower() if value.type == BOOLEAN else str(value.value),
API_VALUE_TYPES.get(value.type or STRING, "string"),
)
def get_experiment_rollout(experiment: Experiment) -> dict[str, typing.Any] | None:
segment_id = experiment.rollout_segment_id
if segment_id is None:
return None
feature_state = FeatureState.objects.get_live_feature_states(
environment=experiment.environment,
additional_filters=Q(
feature_segment__segment_id=segment_id, identity__isnull=True
),
feature_id=experiment.feature_id,
).latest("id")
condition = Condition.objects.get(
rule__segment_id=segment_id, operator=PERCENTAGE_SPLIT
)
str_value, value_type = _serialize_feature_state_value(
feature_state.feature_state_value
)
return {
"enabled": feature_state.enabled,
"rollout_percentage": float(condition.value or 0),
"feature_state_value": {"type": value_type, "value": str_value},
"multivariate_feature_state_values": [
{
"multivariate_feature_option": mv.multivariate_feature_option_id,
"percentage_allocation": mv.percentage_allocation,
}
for mv in feature_state.multivariate_feature_state_values.all()
],
}
def enable_experiment_rollout(experiment: Experiment, author: AuthorData) -> None:
rollout = get_experiment_rollout(experiment)
if rollout is None or rollout["enabled"]:
return
value = rollout["feature_state_value"]
_update_rollout_in_place(
experiment,
FlagChangeSet(
author=author,
enabled=True,
feature_state_value=value["value"],
type_=value["type"],
segment_id=experiment.rollout_segment_id,
),
)
def mark_warehouse_pending_connection(
connection: WarehouseConnection,
) -> WarehouseConnection:
"""Move a connection from created to pending_connection. No-op for any
other status."""
if connection.status != WarehouseConnectionStatus.CREATED:
return connection
connection.status = WarehouseConnectionStatus.PENDING_CONNECTION
connection.save(update_fields=["status"])
logger.info(
"connection.test_event_sent",
environment__id=connection.environment_id,
organisation__id=connection.environment.project.organisation_id,
)
return connection
def mark_warehouse_delivery_failed(
connection: WarehouseConnection,
detail: str,
) -> None:
connection.status = WarehouseConnectionStatus.ERRORED
connection.status_detail = detail[:255]
connection.save(update_fields=["status", "status_detail"])
def mark_warehouse_delivery_succeeded(connection: WarehouseConnection) -> None:
if connection.status == WarehouseConnectionStatus.CONNECTED:
return
connection.status = WarehouseConnectionStatus.CONNECTED
connection.status_detail = None
connection.save(update_fields=["status", "status_detail"])
def _deliver_pending_objects(
client: ClickHouseHTTPClient,
*,
bucket_name: str,
pending: list[str],
connection: WarehouseConnection,
) -> tuple[int, int, int]:
log = logger.bind(
connection__id=connection.id,
environment__id=connection.environment_id,
organisation__id=connection.environment.project.organisation_id,