-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
metrics.py
1738 lines (1479 loc) · 58.3 KB
/
metrics.py
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
import logging
from collections import defaultdict
from collections.abc import Callable, Collection, Mapping, Sequence
from datetime import datetime, timedelta, timezone
from typing import Any, Literal, TypeVar
from snuba_sdk import Column, Condition, Direction, Op
from snuba_sdk.expressions import Granularity, Limit, Offset
from sentry.models.environment import Environment
from sentry.models.project import Project
from sentry.release_health.base import (
AllowedResolution,
CrashFreeBreakdown,
CurrentAndPreviousCrashFreeRates,
EnvironmentName,
OrganizationId,
OverviewStat,
ProjectId,
ProjectOrRelease,
ProjectRelease,
ProjectReleaseSessionStats,
ProjectReleaseUserStats,
ProjectWithCount,
ReleaseAdoption,
ReleaseHealthBackend,
ReleaseHealthOverview,
ReleaseName,
ReleasesAdoption,
ReleaseSessionsTimeBounds,
SessionsQueryConfig,
SessionsQueryResult,
StatsPeriod,
)
from sentry.release_health.metrics_sessions_v2 import run_sessions_query
from sentry.sentry_metrics import indexer
from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.snuba.metrics import (
MetricField,
MetricGroupByField,
MetricOrderByField,
MetricsQuery,
get_series,
)
from sentry.snuba.metrics.naming_layer.mri import SessionMRI
from sentry.snuba.sessions import _make_stats, get_rollup_starts_and_buckets
from sentry.snuba.sessions_v2 import QueryDefinition
from sentry.utils import json
from sentry.utils.dates import to_datetime
from sentry.utils.safe import get_path
from sentry.utils.snuba import QueryOutsideRetentionError
SMALLEST_METRICS_BUCKET = 10
SENTRY_FIRST_COMMIT_DATE = datetime(2008, 5, 8, tzinfo=timezone.utc)
# Whenever a snuba query agains the old sessions table is done without both 1)
# an explicit rollup 2) a groupby some timestamp/bucket, Snuba will pick a
# default rollup of 3600 and pick sessions_hourly_dist over sessions_raw_dist,
# regardless of the timerange chosen.
#
# In order to make functional comparison easier, the metrics implementation
# (explicitly) chooses the same rollup in the equivalent queries, and uses this
# constant to denote that case.
MINUTE = 60 # 60 seconds
HOUR = MINUTE * 60
DAY = HOUR * 24
LEGACY_SESSIONS_DEFAULT_ROLLUP = HOUR
USE_CASE_ID = UseCaseID.SESSIONS
logger = logging.getLogger(__name__)
_V = TypeVar("_V")
def filter_projects_by_project_release(project_releases: Sequence[ProjectRelease]) -> Condition:
return Condition(Column("project_id"), Op.IN, [proj for proj, _rel in project_releases])
def filter_releases_by_project_release(project_releases: Sequence[ProjectRelease]) -> Condition:
return Condition(
lhs=Column(name="tags[release]"),
op=Op.IN,
rhs=[rel for _proj, rel in project_releases],
)
def _model_environment_ids_to_environment_names(
environment_ids: Sequence[int],
) -> Mapping[int, str | None]:
"""
Maps Environment Model ids to the environment name
Note: this does a Db lookup
"""
empty_string_to_none: Callable[[Any], Any | None] = lambda v: None if v == "" else v
id_to_name: Mapping[int, str | None] = {
k: empty_string_to_none(v)
for k, v in Environment.objects.filter(id__in=environment_ids).values_list("id", "name")
}
return defaultdict(lambda: None, id_to_name)
class MetricsReleaseHealthBackend(ReleaseHealthBackend):
"""
Implementation of the ReleaseHealthBackend using the MetricsLayer API
"""
@staticmethod
def _get_org_id(project_ids: Sequence[int]) -> int:
return MetricsReleaseHealthBackend._get_projects_and_org_id(project_ids)[1]
@staticmethod
def _get_projects(project_ids: Sequence[int]) -> Sequence[Project]:
return MetricsReleaseHealthBackend._get_projects_and_org_id(project_ids)[0]
@staticmethod
def _get_projects_and_org_id(project_ids: Sequence[int]) -> tuple[Sequence[Project], int]:
projects = Project.objects.get_many_from_cache(project_ids)
org_ids: set[int] = {project.organization_id for project in projects}
if len(org_ids) != 1:
raise ValueError("Expected projects to be from the same organization")
return projects, org_ids.pop()
@staticmethod
def _get_crash_free_rate_data(
org_id: int,
projects: Sequence[Project],
start: datetime,
end: datetime,
rollup: int,
) -> dict[int, float]:
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.CRASH_FREE_RATE.value, alias="rate", op=None),
]
groupby = [
MetricGroupByField(field="project_id"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(rollup),
groupby=groupby,
include_series=False,
include_totals=True,
)
result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
groups = get_path(result, "groups", default=[])
ret_val = {}
for group in groups:
project_id = get_path(group, "by", "project_id")
assert project_id is not None
totals = get_path(group, "totals", "rate", should_log=True)
try:
if totals is None:
logger.info(
"sentry.release_health.metrics._get_crash_free_rate_data.totals_is_none",
extra={
"group": json.dumps(group),
"project_id": json.dumps(project_id),
"organization_id": org_id,
"timeseries_for_query": json.dumps(result),
},
)
except Exception as e:
logger.exception("Unable to log; %s", e)
assert totals is not None
ret_val[project_id] = totals * 100
return ret_val
def is_metrics_based(self) -> bool:
return True
def get_current_and_previous_crash_free_rates(
self,
project_ids: Sequence[int],
current_start: datetime,
current_end: datetime,
previous_start: datetime,
previous_end: datetime,
rollup: int,
org_id: int | None = None,
) -> CurrentAndPreviousCrashFreeRates:
projects, proj_org_id = self._get_projects_and_org_id(project_ids)
if org_id is None:
org_id = proj_org_id
else:
if org_id != proj_org_id:
# the specified org_id is not the projects' organization
raise ValueError("Expected projects to be from the specified organization")
projects_crash_free_rate_dict: CurrentAndPreviousCrashFreeRates = {
prj: {"currentCrashFreeRate": None, "previousCrashFreeRate": None}
for prj in project_ids
}
previous = self._get_crash_free_rate_data(
org_id,
projects,
previous_start,
previous_end,
rollup,
)
current = self._get_crash_free_rate_data(
org_id,
projects,
current_start,
current_end,
rollup,
)
for project_id, project_data in projects_crash_free_rate_dict.items():
project_data["previousCrashFreeRate"] = previous.get(project_id)
project_data["currentCrashFreeRate"] = current.get(project_id)
return projects_crash_free_rate_dict
def get_release_adoption(
self,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
now: datetime | None = None,
org_id: OrganizationId | None = None,
) -> ReleasesAdoption:
project_ids = list({x[0] for x in project_releases})
if org_id is None:
org_id = self._get_org_id(project_ids)
if now is None:
now = datetime.now(timezone.utc)
return self._get_release_adoption_impl(now, org_id, project_releases, environments)
@staticmethod
def _get_release_adoption_impl(
now: datetime,
org_id: int,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
) -> ReleasesAdoption:
start = now - timedelta(days=1)
project_ids = [proj for proj, _rel in project_releases]
projects = MetricsReleaseHealthBackend._get_projects(project_ids)
def _get_common_where(total: bool) -> list[Condition]:
where_common: list[Condition] = [
filter_projects_by_project_release(project_releases),
]
if environments is not None:
where_common.append(
Condition(
lhs=Column("tags[environment]"),
op=Op.IN,
rhs=environments,
)
)
if not total:
where_common.append(filter_releases_by_project_release(project_releases))
return where_common
def _get_common_groupby(total: bool) -> list[MetricGroupByField]:
if total:
return [MetricGroupByField(field="project_id")]
else:
return [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
def _convert_results(groups: Any, total: bool) -> dict[Any, int]:
"""
Converts the result groups into an array of values:
from [{ "by": {"project_id": 123, "release": "r1"}, "totals": {"init": 23.3}},...]
to:
{ 123: 23.3, ...} // for totals
{ (123, "r1"): 23.3, ...} // for details
"""
ret_val = {}
for group in groups:
if total:
idx = get_path(group, "by", "project_id")
else:
by = group.get("by", {})
idx = by.get("project_id"), by.get("release")
ret_val[idx] = get_path(group, "totals", "value")
return ret_val
def _count_sessions(
total: bool, project_ids: Sequence[int], referrer: str
) -> dict[Any, int]:
select = [
MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None),
]
query = MetricsQuery(
org_id=org_id,
start=start,
end=now,
project_ids=project_ids,
select=select,
groupby=_get_common_groupby(total),
where=_get_common_where(total),
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
return _convert_results(raw_result["groups"], total=total)
def _count_users(total: bool, referrer: str) -> dict[Any, int]:
select = [
MetricField(metric_mri=SessionMRI.RAW_USER.value, alias="value", op="count_unique")
]
query = MetricsQuery(
org_id=org_id,
start=start,
end=now,
project_ids=project_ids,
select=select,
groupby=_get_common_groupby(total),
where=_get_common_where(total),
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(projects=projects, metrics_query=query, use_case_id=USE_CASE_ID)
return _convert_results(raw_result["groups"], total)
# XXX(markus): Four queries are quite horrible for this... the old code
# sufficed with two. From what I understand, ClickHouse would have to
# gain a function uniqCombined64MergeIf, i.e. a conditional variant of
# what we already use.
#
# Alternatively we may want to use a threadpool here to send the
# queries in parallel.
# NOTE: referrers are spelled out as single static string literal so
# S&S folks can search for it more easily. No string formatting
# business please!
# Count of sessions/users for given list of environments and timerange, per-project
sessions_per_project: dict[int, int] = _count_sessions(
total=True,
project_ids=project_ids,
referrer="release_health.metrics.get_release_adoption.total_sessions",
)
users_per_project: dict[int, int] = _count_users(
total=True, referrer="release_health.metrics.get_release_adoption.total_users"
)
# Count of sessions/users for given list of environments and timerange AND GIVEN RELEASES, per-project
sessions_per_release: dict[tuple[int, str], int] = _count_sessions(
total=False,
project_ids=project_ids,
referrer="release_health.metrics.get_release_adoption.releases_sessions",
)
users_per_release: dict[tuple[int, str], int] = _count_users(
total=False, referrer="release_health.metrics.get_release_adoption.releases_users"
)
rv = {}
for project_id, release in project_releases:
release_tag_value = indexer.resolve(USE_CASE_ID, org_id, release)
if release_tag_value is None:
# Don't emit empty releases -- for exact compatibility with
# sessions table backend.
continue
release_sessions = sessions_per_release.get((project_id, release), 0.0)
release_users = users_per_release.get((project_id, release), 0.0)
total_sessions = sessions_per_project.get(project_id, 0.0)
total_users = users_per_project.get(project_id, 0.0)
adoption: ReleaseAdoption = {
"adoption": release_users / total_users * 100
if release_users and total_users
else None,
"sessions_adoption": release_sessions / total_sessions * 100
if release_sessions and total_sessions
else None,
"users_24h": int(release_users),
"sessions_24h": int(release_sessions),
"project_users_24h": int(total_users),
"project_sessions_24h": int(total_sessions),
}
rv[project_id, release] = adoption
return rv
def sessions_query_config(self, organization: Any) -> SessionsQueryConfig:
return SessionsQueryConfig(
allowed_resolution=AllowedResolution.ten_seconds,
allow_session_status_query=True,
restrict_date_range=False,
)
def run_sessions_query(
self,
org_id: int,
query: QueryDefinition,
span_op: str,
) -> SessionsQueryResult:
return run_sessions_query(org_id, query, span_op)
def get_release_sessions_time_bounds(
self,
project_id: ProjectId,
release: ReleaseName,
org_id: OrganizationId,
environments: Sequence[EnvironmentName] | None = None,
) -> ReleaseSessionsTimeBounds:
projects, org_id = self._get_projects_and_org_id([project_id])
select = [
MetricField(
metric_mri=SessionMRI.RAW_SESSION.value,
alias="min_counter_date",
op="min_timestamp",
),
MetricField(
metric_mri=SessionMRI.RAW_SESSION.value,
alias="max_counter_date",
op="max_timestamp",
),
MetricField(
metric_mri=SessionMRI.RAW_DURATION.value, alias="min_dist_date", op="min_timestamp"
),
MetricField(
metric_mri=SessionMRI.RAW_DURATION.value, alias="max_dist_date", op="max_timestamp"
),
]
where = []
if release:
where.append(
Condition(
lhs=Column(name="tags[release]"),
op=Op.EQ,
rhs=release,
)
)
if environments:
where.append(
Condition(
lhs=Column(name="tags[environment]"),
op=Op.IN,
rhs=list(environments),
)
)
query = MetricsQuery(
org_id=org_id,
project_ids=[project_id],
select=select,
start=SENTRY_FIRST_COMMIT_DATE,
end=datetime.now(timezone.utc) + timedelta(seconds=10),
where=where,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
def iso_format_snuba_datetime(date: str) -> str:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00").isoformat()[:19] + "Z"
formatted_unix_start_time = datetime.fromtimestamp(0).strftime("%Y-%m-%dT%H:%M:%S+00:00")
def clean_date_string(d: str | None) -> str | None:
# This check is added because if there are no sessions found, then the
# aggregation queries return both the sessions_lower_bound and the
# sessions_upper_bound as `0` timestamp, and we do not want that behaviour
# by default
# P.S. To avoid confusion the `0` timestamp which is '1970-01-01 00:00:00'
# is rendered as '0000-00-00 00:00:00' in clickhouse shell
# sets and Unix start time dates to None
if d == formatted_unix_start_time:
return None
return d
min_date = None
max_date = None
if groups:
totals = groups[0]["totals"]
min_date = clean_date_string(totals.get("min_counter_date"))
max_date = clean_date_string(totals.get("max_counter_date"))
min_date2 = clean_date_string(totals.get("min_dist_date"))
max_date2 = clean_date_string(totals.get("max_dist_date"))
if min_date is None or (min_date2 is not None and min_date > min_date2):
min_date = min_date2
if max_date is None or (max_date2 is not None and max_date < max_date2):
max_date = max_date2
if min_date is not None and max_date is not None:
return {
"sessions_lower_bound": iso_format_snuba_datetime(min_date),
"sessions_upper_bound": iso_format_snuba_datetime(max_date),
}
else:
return {
"sessions_lower_bound": None,
"sessions_upper_bound": None,
}
def check_has_health_data(
self,
projects_list: Collection[ProjectOrRelease],
now: datetime | None = None,
) -> set[ProjectOrRelease]:
if now is None:
now = datetime.now(timezone.utc)
start = now - timedelta(days=90)
projects_list = list(projects_list)
if len(projects_list) == 0:
return set()
includes_releases = isinstance(projects_list[0], tuple)
if includes_releases:
project_ids: list[ProjectId] = [x[0] for x in projects_list] # type: ignore[index]
else:
project_ids = projects_list # type: ignore[assignment]
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.RAW_SESSION.value, alias="value", op="sum")]
where_clause = []
groupby = [
MetricGroupByField(field="project_id"),
]
if includes_releases:
where_clause.append(filter_releases_by_project_release(projects_list)) # type: ignore[arg-type]
groupby.append(MetricGroupByField(field="release"))
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=now,
granularity=Granularity(DAY),
groupby=groupby,
where=where_clause,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = set()
for group in groups:
if includes_releases:
by = group.get("by", {})
idx = by.get("project_id"), by.get("release")
ret_val.add(idx)
else:
proj_id = get_path(group, "by", "project_id")
ret_val.add(proj_id)
return ret_val # type: ignore[return-value]
def check_releases_have_health_data(
self,
organization_id: OrganizationId,
project_ids: Sequence[ProjectId],
release_versions: Sequence[ReleaseName],
start: datetime,
end: datetime,
) -> set[ReleaseName]:
"""
Returns a set of all release versions that have health data within a given period of time.
"""
projects, org_id = self._get_projects_and_org_id(project_ids)
select = [MetricField(metric_mri=SessionMRI.RAW_SESSION.value, alias="value", op="sum")]
groupby = [MetricGroupByField(field="release")]
where_clause = [
Condition(
lhs=Column(name="tags[release]"),
op=Op.IN,
rhs=release_versions,
)
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(LEGACY_SESSIONS_DEFAULT_ROLLUP),
groupby=groupby,
where=where_clause,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = set()
for group in groups:
by = group.get("by", {})
release = by.get("release")
if release is not None:
ret_val.add(release)
return ret_val
@staticmethod
def _get_session_duration_data_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str], Any]:
"""
Percentiles of session duration
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.DURATION.value, alias="p50", op="p50"),
MetricField(metric_mri=SessionMRI.DURATION.value, alias="p90", op="p90"),
]
session_status_cond = Condition(lhs=Column("tags[session.status]"), op=Op.EQ, rhs="exited")
where = [*where, session_status_cond]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
p50 = totals.get("p50")
p90 = totals.get("p90")
ret_val[(proj_id, release)] = {"duration_p50": p50, "duration_p90": p90}
return ret_val
@staticmethod
def _get_errored_sessions_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str], int]:
"""
Count of errored sessions, incl fatal (abnormal, crashed) sessions,
excl errored *preaggregated* sessions
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ERRORED_SET.value, alias="value", op=None),
]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
value = get_path(group, "totals", "value")
ret_val[(proj_id, release)] = value
return ret_val
@staticmethod
def _get_session_by_status_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str, str], int]:
"""
Counts of init, abnormal and crashed sessions, purpose-built for overview
"""
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ABNORMAL.value, alias="abnormal", op=None),
MetricField(metric_mri=SessionMRI.CRASHED.value, alias="crashed", op=None),
MetricField(metric_mri=SessionMRI.ALL.value, alias="init", op=None),
MetricField(
metric_mri=SessionMRI.ERRORED_PREAGGREGATED.value,
alias="errored_preaggr",
op=None,
),
]
groupby = [
MetricGroupByField(field="project_id"),
MetricGroupByField(field="release"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
for status in ["abnormal", "crashed", "init", "errored_preaggr"]:
value = totals.get(status)
if value is not None and value != 0.0:
ret_val[(proj_id, release, status)] = value
return ret_val
@staticmethod
def _get_users_and_crashed_users_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
granularity: int,
start: datetime,
end: datetime,
) -> Mapping[tuple[int, str, str], int]:
project_ids = [p.id for p in projects]
select = [
MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="all_users", op=None),
MetricField(metric_mri=SessionMRI.CRASHED_USER.value, alias="crashed_users", op=None),
]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=select,
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=False,
include_totals=True,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val = {}
for group in groups:
by = group.get("by", {})
proj_id = by.get("project_id")
release = by.get("release")
totals = group.get("totals", {})
for status in ["all_users", "crashed_users"]:
value = totals.get(status)
if value is not None:
ret_val[(proj_id, release, status)] = value
return ret_val
@staticmethod
def _get_health_stats_for_overview(
projects: Sequence[Project],
where: list[Condition],
org_id: int,
stat: OverviewStat,
granularity: int,
start: datetime,
end: datetime,
buckets: int,
) -> Mapping[ProjectRelease, list[list[int]]]:
project_ids = [p.id for p in projects]
metric_field = {
"users": MetricField(metric_mri=SessionMRI.ALL_USER.value, alias="value", op=None),
"sessions": MetricField(metric_mri=SessionMRI.ALL.value, alias="value", op=None),
}[stat]
groupby = [
MetricGroupByField(field="release"),
MetricGroupByField(field="project_id"),
]
query = MetricsQuery(
org_id=org_id,
project_ids=project_ids,
select=[metric_field],
start=start,
end=end,
granularity=Granularity(granularity),
groupby=groupby,
where=where,
include_series=True,
include_totals=False,
)
raw_result = get_series(
projects=projects,
metrics_query=query,
use_case_id=USE_CASE_ID,
)
groups = raw_result["groups"]
ret_val: dict[ProjectRelease, list[list[int]]] = defaultdict(
lambda: _make_stats(start, granularity, buckets)
)
timestamps = [int(dt.timestamp()) for dt in raw_result["intervals"]]
for group in groups:
proj_id = get_path(group, "by", "project_id")
release = get_path(group, "by", "release")
series = get_path(group, "series", "value")
assert len(timestamps)
data = zip(timestamps, series)
as_array = [[ts, dt] for ts, dt in data]
ret_val[(proj_id, release)] = as_array
return ret_val
def get_release_health_data_overview(
self,
project_releases: Sequence[ProjectRelease],
environments: Sequence[EnvironmentName] | None = None,
summary_stats_period: StatsPeriod | None = None,
health_stats_period: StatsPeriod | None = None,
stat: Literal["users", "sessions"] | None = None,
now: datetime | None = None,
) -> Mapping[ProjectRelease, ReleaseHealthOverview]:
"""Checks quickly for which of the given project releases we have
health data available. The argument is a tuple of `(project_id, release_name)`
tuples. The return value is a set of all the project releases that have health
data.
"""
if stat is None:
stat = "sessions"
assert stat in ("sessions", "users")
if now is None:
now = datetime.now(timezone.utc)
project_ids = [proj_id for proj_id, _release in project_releases]
projects, org_id = self._get_projects_and_org_id(project_ids)
granularity, summary_start, stats_buckets = get_rollup_starts_and_buckets(
summary_stats_period or "24h", now=now
)
# NOTE: for backward compatibility with previous implementation some queries use the granularity calculated from
# stats_period and others use the legacy_session_rollup
rollup = LEGACY_SESSIONS_DEFAULT_ROLLUP
where = [filter_projects_by_project_release(project_releases)]
if health_stats_period:
health_stats_data = self._get_health_stats_for_overview(
projects=projects,
where=where,
org_id=org_id,
stat=stat,
granularity=granularity,
start=summary_start,
end=now,
buckets=stats_buckets,
)
else:
health_stats_data = {}
rv_durations = self._get_session_duration_data_for_overview(
projects, where, org_id, rollup, summary_start, now
)
rv_errored_sessions = self._get_errored_sessions_for_overview(
projects, where, org_id, rollup, summary_start, now
)
rv_sessions = self._get_session_by_status_for_overview(
projects, where, org_id, rollup, summary_start, now