test_organization_events_stats_mep.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239
  1. from __future__ import annotations
  2. from datetime import timedelta
  3. from typing import Any
  4. from unittest import mock
  5. import pytest
  6. from django.urls import reverse
  7. from rest_framework.response import Response
  8. from sentry.discover.models import DatasetSourcesTypes
  9. from sentry.models.dashboard_widget import DashboardWidget, DashboardWidgetTypes
  10. from sentry.models.environment import Environment
  11. from sentry.sentry_metrics.use_case_id_registry import UseCaseID
  12. from sentry.snuba.metrics.extraction import MetricSpecType, OnDemandMetricSpec
  13. from sentry.testutils.cases import MetricsEnhancedPerformanceTestCase
  14. from sentry.testutils.helpers.datetime import before_now, iso_format
  15. from sentry.testutils.helpers.on_demand import create_widget
  16. from sentry.utils.samples import load_data
  17. pytestmark = pytest.mark.sentry_metrics
  18. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest(
  19. MetricsEnhancedPerformanceTestCase
  20. ):
  21. endpoint = "sentry-api-0-organization-events-stats"
  22. METRIC_STRINGS = [
  23. "foo_transaction",
  24. "d:transactions/measurements.datacenter_memory@pebibyte",
  25. ]
  26. def setUp(self):
  27. super().setUp()
  28. self.login_as(user=self.user)
  29. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  30. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  31. self.url = reverse(
  32. "sentry-api-0-organization-events-stats",
  33. kwargs={"organization_id_or_slug": self.project.organization.slug},
  34. )
  35. self.features = {
  36. "organizations:performance-use-metrics": True,
  37. }
  38. self.additional_params = dict()
  39. # These throughput tests should roughly match the ones in OrganizationEventsStatsEndpointTest
  40. @pytest.mark.querybuilder
  41. def test_throughput_epm_hour_rollup(self):
  42. # Each of these denotes how many events to create in each hour
  43. event_counts = [6, 0, 6, 3, 0, 3]
  44. for hour, count in enumerate(event_counts):
  45. for minute in range(count):
  46. self.store_transaction_metric(
  47. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  48. )
  49. for axis in ["epm()", "tpm()"]:
  50. response = self.do_request(
  51. data={
  52. "start": iso_format(self.day_ago),
  53. "end": iso_format(self.day_ago + timedelta(hours=6)),
  54. "interval": "1h",
  55. "yAxis": axis,
  56. "project": self.project.id,
  57. "dataset": "metricsEnhanced",
  58. **self.additional_params,
  59. },
  60. )
  61. assert response.status_code == 200, response.content
  62. data = response.data["data"]
  63. assert len(data) == 6
  64. assert response.data["isMetricsData"]
  65. rows = data[0:6]
  66. for test in zip(event_counts, rows):
  67. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  68. def test_throughput_epm_day_rollup(self):
  69. # Each of these denotes how many events to create in each minute
  70. event_counts = [6, 0, 6, 3, 0, 3]
  71. for hour, count in enumerate(event_counts):
  72. for minute in range(count):
  73. self.store_transaction_metric(
  74. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  75. )
  76. for axis in ["epm()", "tpm()"]:
  77. response = self.do_request(
  78. data={
  79. "start": iso_format(self.day_ago),
  80. "end": iso_format(self.day_ago + timedelta(hours=24)),
  81. "interval": "24h",
  82. "yAxis": axis,
  83. "project": self.project.id,
  84. "dataset": "metricsEnhanced",
  85. **self.additional_params,
  86. },
  87. )
  88. assert response.status_code == 200, response.content
  89. data = response.data["data"]
  90. assert len(data) == 2
  91. assert response.data["isMetricsData"]
  92. assert data[0][1][0]["count"] == sum(event_counts) / (86400.0 / 60.0)
  93. def test_throughput_epm_hour_rollup_offset_of_hour(self):
  94. # Each of these denotes how many events to create in each hour
  95. event_counts = [6, 0, 6, 3, 0, 3]
  96. for hour, count in enumerate(event_counts):
  97. for minute in range(count):
  98. self.store_transaction_metric(
  99. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute + 30)
  100. )
  101. for axis in ["tpm()", "epm()"]:
  102. response = self.do_request(
  103. data={
  104. "start": iso_format(self.day_ago + timedelta(minutes=30)),
  105. "end": iso_format(self.day_ago + timedelta(hours=6, minutes=30)),
  106. "interval": "1h",
  107. "yAxis": axis,
  108. "project": self.project.id,
  109. "dataset": "metricsEnhanced",
  110. **self.additional_params,
  111. },
  112. )
  113. assert response.status_code == 200, response.content
  114. data = response.data["data"]
  115. assert len(data) == 6
  116. assert response.data["isMetricsData"]
  117. rows = data[0:6]
  118. for test in zip(event_counts, rows):
  119. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  120. def test_throughput_eps_minute_rollup(self):
  121. # Each of these denotes how many events to create in each minute
  122. event_counts = [6, 0, 6, 3, 0, 3]
  123. for minute, count in enumerate(event_counts):
  124. for second in range(count):
  125. self.store_transaction_metric(
  126. 1, timestamp=self.day_ago + timedelta(minutes=minute, seconds=second)
  127. )
  128. for axis in ["eps()", "tps()"]:
  129. response = self.do_request(
  130. data={
  131. "start": iso_format(self.day_ago),
  132. "end": iso_format(self.day_ago + timedelta(minutes=6)),
  133. "interval": "1m",
  134. "yAxis": axis,
  135. "project": self.project.id,
  136. "dataset": "metricsEnhanced",
  137. **self.additional_params,
  138. },
  139. )
  140. assert response.status_code == 200, response.content
  141. data = response.data["data"]
  142. assert len(data) == 6
  143. assert response.data["isMetricsData"]
  144. rows = data[0:6]
  145. for test in zip(event_counts, rows):
  146. assert test[1][1][0]["count"] == test[0] / 60.0
  147. def test_failure_rate(self):
  148. for hour in range(6):
  149. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  150. self.store_transaction_metric(1, tags={"transaction.status": "ok"}, timestamp=timestamp)
  151. if hour < 3:
  152. self.store_transaction_metric(
  153. 1, tags={"transaction.status": "internal_error"}, timestamp=timestamp
  154. )
  155. response = self.do_request(
  156. data={
  157. "start": iso_format(self.day_ago),
  158. "end": iso_format(self.day_ago + timedelta(hours=6)),
  159. "interval": "1h",
  160. "yAxis": ["failure_rate()"],
  161. "project": self.project.id,
  162. "dataset": "metricsEnhanced",
  163. **self.additional_params,
  164. },
  165. )
  166. assert response.status_code == 200, response.content
  167. data = response.data["data"]
  168. assert len(data) == 6
  169. assert response.data["isMetricsData"]
  170. assert [attrs for time, attrs in response.data["data"]] == [
  171. [{"count": 0.5}],
  172. [{"count": 0.5}],
  173. [{"count": 0.5}],
  174. [{"count": 0}],
  175. [{"count": 0}],
  176. [{"count": 0}],
  177. ]
  178. def test_percentiles_multi_axis(self):
  179. for hour in range(6):
  180. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  181. self.store_transaction_metric(111, timestamp=timestamp)
  182. self.store_transaction_metric(222, metric="measurements.lcp", timestamp=timestamp)
  183. response = self.do_request(
  184. data={
  185. "start": iso_format(self.day_ago),
  186. "end": iso_format(self.day_ago + timedelta(hours=6)),
  187. "interval": "1h",
  188. "yAxis": ["p75(measurements.lcp)", "p75(transaction.duration)"],
  189. "project": self.project.id,
  190. "dataset": "metricsEnhanced",
  191. **self.additional_params,
  192. },
  193. )
  194. assert response.status_code == 200, response.content
  195. lcp = response.data["p75(measurements.lcp)"]
  196. duration = response.data["p75(transaction.duration)"]
  197. assert len(duration["data"]) == 6
  198. assert duration["isMetricsData"]
  199. assert len(lcp["data"]) == 6
  200. assert lcp["isMetricsData"]
  201. for item in duration["data"]:
  202. assert item[1][0]["count"] == 111
  203. for item in lcp["data"]:
  204. assert item[1][0]["count"] == 222
  205. @mock.patch("sentry.snuba.metrics_enhanced_performance.timeseries_query", return_value={})
  206. def test_multiple_yaxis_only_one_query(self, mock_query):
  207. self.do_request(
  208. data={
  209. "project": self.project.id,
  210. "start": iso_format(self.day_ago),
  211. "end": iso_format(self.day_ago + timedelta(hours=2)),
  212. "interval": "1h",
  213. "yAxis": ["epm()", "eps()", "tpm()", "p50(transaction.duration)"],
  214. "dataset": "metricsEnhanced",
  215. **self.additional_params,
  216. },
  217. )
  218. assert mock_query.call_count == 1
  219. def test_aggregate_function_user_count(self):
  220. self.store_transaction_metric(
  221. 1, metric="user", timestamp=self.day_ago + timedelta(minutes=30)
  222. )
  223. self.store_transaction_metric(
  224. 1, metric="user", timestamp=self.day_ago + timedelta(hours=1, minutes=30)
  225. )
  226. response = self.do_request(
  227. data={
  228. "start": iso_format(self.day_ago),
  229. "end": iso_format(self.day_ago + timedelta(hours=2)),
  230. "interval": "1h",
  231. "yAxis": "count_unique(user)",
  232. "dataset": "metricsEnhanced",
  233. **self.additional_params,
  234. },
  235. )
  236. assert response.status_code == 200, response.content
  237. assert response.data["isMetricsData"]
  238. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 1}]]
  239. meta = response.data["meta"]
  240. assert meta["isMetricsData"] == response.data["isMetricsData"]
  241. def test_non_mep_query_fallsback(self):
  242. def get_mep(query):
  243. response = self.do_request(
  244. data={
  245. "project": self.project.id,
  246. "start": iso_format(self.day_ago),
  247. "end": iso_format(self.day_ago + timedelta(hours=2)),
  248. "interval": "1h",
  249. "query": query,
  250. "yAxis": ["epm()"],
  251. "dataset": "metricsEnhanced",
  252. **self.additional_params,
  253. },
  254. )
  255. assert response.status_code == 200, response.content
  256. return response.data["isMetricsData"]
  257. assert get_mep(""), "empty query"
  258. assert get_mep("event.type:transaction"), "event type transaction"
  259. assert not get_mep("event.type:error"), "event type error"
  260. assert not get_mep("transaction.duration:<15min"), "outlier filter"
  261. assert get_mep("epm():>0.01"), "throughput filter"
  262. assert not get_mep(
  263. "event.type:transaction OR event.type:error"
  264. ), "boolean with non-mep filter"
  265. assert get_mep(
  266. "event.type:transaction OR transaction:foo_transaction"
  267. ), "boolean with mep filter"
  268. def test_having_condition_with_preventing_aggregates(self):
  269. response = self.do_request(
  270. data={
  271. "project": self.project.id,
  272. "start": iso_format(self.day_ago),
  273. "end": iso_format(self.day_ago + timedelta(hours=2)),
  274. "interval": "1h",
  275. "query": "p95():<5s",
  276. "yAxis": ["epm()"],
  277. "dataset": "metricsEnhanced",
  278. "preventMetricAggregates": "1",
  279. **self.additional_params,
  280. },
  281. )
  282. assert response.status_code == 200, response.content
  283. assert not response.data["isMetricsData"]
  284. meta = response.data["meta"]
  285. assert meta["isMetricsData"] == response.data["isMetricsData"]
  286. def test_explicit_not_mep(self):
  287. response = self.do_request(
  288. data={
  289. "project": self.project.id,
  290. "start": iso_format(self.day_ago),
  291. "end": iso_format(self.day_ago + timedelta(hours=2)),
  292. "interval": "1h",
  293. # Should be a mep able query
  294. "query": "",
  295. "yAxis": ["epm()"],
  296. "metricsEnhanced": "0",
  297. **self.additional_params,
  298. },
  299. )
  300. assert response.status_code == 200, response.content
  301. assert not response.data["isMetricsData"]
  302. meta = response.data["meta"]
  303. assert meta["isMetricsData"] == response.data["isMetricsData"]
  304. def test_sum_transaction_duration(self):
  305. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  306. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  307. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  308. response = self.do_request(
  309. data={
  310. "start": iso_format(self.day_ago),
  311. "end": iso_format(self.day_ago + timedelta(hours=2)),
  312. "interval": "1h",
  313. "yAxis": "sum(transaction.duration)",
  314. "dataset": "metricsEnhanced",
  315. **self.additional_params,
  316. },
  317. )
  318. assert response.status_code == 200, response.content
  319. assert response.data["isMetricsData"]
  320. assert [attrs for time, attrs in response.data["data"]] == [
  321. [{"count": 123}],
  322. [{"count": 1245}],
  323. ]
  324. meta = response.data["meta"]
  325. assert meta["isMetricsData"] == response.data["isMetricsData"]
  326. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  327. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  328. def test_sum_transaction_duration_with_comparison(self):
  329. # We store the data for the previous day (in order to have values for the comparison).
  330. self.store_transaction_metric(
  331. 1, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  332. )
  333. self.store_transaction_metric(
  334. 2, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  335. )
  336. # We store the data for today.
  337. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  338. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(minutes=30))
  339. response = self.do_request(
  340. data={
  341. "start": iso_format(self.day_ago),
  342. "end": iso_format(self.day_ago + timedelta(days=1)),
  343. "interval": "1d",
  344. "yAxis": "sum(transaction.duration)",
  345. "comparisonDelta": 86400,
  346. "dataset": "metricsEnhanced",
  347. **self.additional_params,
  348. },
  349. )
  350. assert response.status_code == 200, response.content
  351. assert response.data["isMetricsData"]
  352. # For some reason, if all tests run, there is some shared state that makes this test have data in the second
  353. # time bucket, which is filled automatically by the zerofilling. In order to avoid this flaky failure, we will
  354. # only check that the first bucket contains the actual data.
  355. assert [attrs for time, attrs in response.data["data"]][0] == [
  356. {"comparisonCount": 3.0, "count": 579.0}
  357. ]
  358. meta = response.data["meta"]
  359. assert meta["isMetricsData"] == response.data["isMetricsData"]
  360. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  361. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  362. def test_custom_measurement(self):
  363. self.store_transaction_metric(
  364. 123,
  365. metric="measurements.bytes_transfered",
  366. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  367. entity="metrics_distributions",
  368. tags={"transaction": "foo_transaction"},
  369. timestamp=self.day_ago + timedelta(minutes=30),
  370. )
  371. self.store_transaction_metric(
  372. 456,
  373. metric="measurements.bytes_transfered",
  374. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  375. entity="metrics_distributions",
  376. tags={"transaction": "foo_transaction"},
  377. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  378. )
  379. self.store_transaction_metric(
  380. 789,
  381. metric="measurements.bytes_transfered",
  382. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  383. entity="metrics_distributions",
  384. tags={"transaction": "foo_transaction"},
  385. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  386. )
  387. response = self.do_request(
  388. data={
  389. "start": iso_format(self.day_ago),
  390. "end": iso_format(self.day_ago + timedelta(hours=2)),
  391. "interval": "1h",
  392. "yAxis": "sum(measurements.datacenter_memory)",
  393. "dataset": "metricsEnhanced",
  394. **self.additional_params,
  395. },
  396. )
  397. assert response.status_code == 200, response.content
  398. assert response.data["isMetricsData"]
  399. assert [attrs for time, attrs in response.data["data"]] == [
  400. [{"count": 123}],
  401. [{"count": 1245}],
  402. ]
  403. meta = response.data["meta"]
  404. assert meta["isMetricsData"] == response.data["isMetricsData"]
  405. assert meta["fields"] == {"time": "date", "sum_measurements_datacenter_memory": "size"}
  406. assert meta["units"] == {"time": None, "sum_measurements_datacenter_memory": "pebibyte"}
  407. def test_does_not_fallback_if_custom_metric_is_out_of_request_time_range(self):
  408. self.store_transaction_metric(
  409. 123,
  410. timestamp=self.day_ago + timedelta(hours=1),
  411. internal_metric="d:transactions/measurements.custom@kibibyte",
  412. entity="metrics_distributions",
  413. )
  414. response = self.do_request(
  415. data={
  416. "start": iso_format(self.day_ago),
  417. "end": iso_format(self.day_ago + timedelta(hours=2)),
  418. "interval": "1h",
  419. "yAxis": "p99(measurements.custom)",
  420. "dataset": "metricsEnhanced",
  421. **self.additional_params,
  422. },
  423. )
  424. meta = response.data["meta"]
  425. assert response.status_code == 200, response.content
  426. assert response.data["isMetricsData"]
  427. assert meta["isMetricsData"]
  428. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  429. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  430. def test_multi_yaxis_custom_measurement(self):
  431. self.store_transaction_metric(
  432. 123,
  433. metric="measurements.bytes_transfered",
  434. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  435. entity="metrics_distributions",
  436. tags={"transaction": "foo_transaction"},
  437. timestamp=self.day_ago + timedelta(minutes=30),
  438. )
  439. self.store_transaction_metric(
  440. 456,
  441. metric="measurements.bytes_transfered",
  442. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  443. entity="metrics_distributions",
  444. tags={"transaction": "foo_transaction"},
  445. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  446. )
  447. self.store_transaction_metric(
  448. 789,
  449. metric="measurements.bytes_transfered",
  450. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  451. entity="metrics_distributions",
  452. tags={"transaction": "foo_transaction"},
  453. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  454. )
  455. response = self.do_request(
  456. data={
  457. "start": iso_format(self.day_ago),
  458. "end": iso_format(self.day_ago + timedelta(hours=2)),
  459. "interval": "1h",
  460. "yAxis": [
  461. "sum(measurements.datacenter_memory)",
  462. "p50(measurements.datacenter_memory)",
  463. ],
  464. "dataset": "metricsEnhanced",
  465. **self.additional_params,
  466. },
  467. )
  468. assert response.status_code == 200, response.content
  469. sum_data = response.data["sum(measurements.datacenter_memory)"]
  470. p50_data = response.data["p50(measurements.datacenter_memory)"]
  471. assert sum_data["isMetricsData"]
  472. assert p50_data["isMetricsData"]
  473. assert [attrs for time, attrs in sum_data["data"]] == [
  474. [{"count": 123}],
  475. [{"count": 1245}],
  476. ]
  477. assert [attrs for time, attrs in p50_data["data"]] == [
  478. [{"count": 123}],
  479. [{"count": 622.5}],
  480. ]
  481. sum_meta = sum_data["meta"]
  482. assert sum_meta["isMetricsData"] == sum_data["isMetricsData"]
  483. assert sum_meta["fields"] == {
  484. "time": "date",
  485. "sum_measurements_datacenter_memory": "size",
  486. "p50_measurements_datacenter_memory": "size",
  487. }
  488. assert sum_meta["units"] == {
  489. "time": None,
  490. "sum_measurements_datacenter_memory": "pebibyte",
  491. "p50_measurements_datacenter_memory": "pebibyte",
  492. }
  493. p50_meta = p50_data["meta"]
  494. assert p50_meta["isMetricsData"] == p50_data["isMetricsData"]
  495. assert p50_meta["fields"] == {
  496. "time": "date",
  497. "sum_measurements_datacenter_memory": "size",
  498. "p50_measurements_datacenter_memory": "size",
  499. }
  500. assert p50_meta["units"] == {
  501. "time": None,
  502. "sum_measurements_datacenter_memory": "pebibyte",
  503. "p50_measurements_datacenter_memory": "pebibyte",
  504. }
  505. def test_dataset_metrics_does_not_fallback(self):
  506. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  507. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  508. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  509. response = self.do_request(
  510. data={
  511. "start": iso_format(self.day_ago),
  512. "end": iso_format(self.day_ago + timedelta(hours=2)),
  513. "interval": "1h",
  514. "query": "transaction.duration:<5s",
  515. "yAxis": "sum(transaction.duration)",
  516. "dataset": "metrics",
  517. **self.additional_params,
  518. },
  519. )
  520. assert response.status_code == 400, response.content
  521. def test_title_filter(self):
  522. self.store_transaction_metric(
  523. 123,
  524. tags={"transaction": "foo_transaction"},
  525. timestamp=self.day_ago + timedelta(minutes=30),
  526. )
  527. response = self.do_request(
  528. data={
  529. "start": iso_format(self.day_ago),
  530. "end": iso_format(self.day_ago + timedelta(hours=2)),
  531. "interval": "1h",
  532. "query": "title:foo_transaction",
  533. "yAxis": [
  534. "sum(transaction.duration)",
  535. ],
  536. "dataset": "metricsEnhanced",
  537. **self.additional_params,
  538. },
  539. )
  540. assert response.status_code == 200, response.content
  541. data = response.data["data"]
  542. assert [attrs for time, attrs in data] == [
  543. [{"count": 123}],
  544. [{"count": 0}],
  545. ]
  546. def test_transaction_status_unknown_error(self):
  547. self.store_transaction_metric(
  548. 123,
  549. tags={"transaction.status": "unknown"},
  550. timestamp=self.day_ago + timedelta(minutes=30),
  551. )
  552. response = self.do_request(
  553. data={
  554. "start": iso_format(self.day_ago),
  555. "end": iso_format(self.day_ago + timedelta(hours=2)),
  556. "interval": "1h",
  557. "query": "transaction.status:unknown_error",
  558. "yAxis": [
  559. "sum(transaction.duration)",
  560. ],
  561. "dataset": "metricsEnhanced",
  562. **self.additional_params,
  563. },
  564. )
  565. assert response.status_code == 200, response.content
  566. data = response.data["data"]
  567. assert [attrs for time, attrs in data] == [
  568. [{"count": 123}],
  569. [{"count": 0}],
  570. ]
  571. def test_custom_performance_metric_meta_contains_field_and_unit_data(self):
  572. self.store_transaction_metric(
  573. 123,
  574. timestamp=self.day_ago + timedelta(hours=1),
  575. internal_metric="d:transactions/measurements.custom@kibibyte",
  576. entity="metrics_distributions",
  577. )
  578. response = self.do_request(
  579. data={
  580. "start": iso_format(self.day_ago),
  581. "end": iso_format(self.day_ago + timedelta(hours=2)),
  582. "interval": "1h",
  583. "yAxis": "p99(measurements.custom)",
  584. "query": "",
  585. **self.additional_params,
  586. },
  587. )
  588. assert response.status_code == 200
  589. meta = response.data["meta"]
  590. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  591. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  592. def test_multi_series_custom_performance_metric_meta_contains_field_and_unit_data(self):
  593. self.store_transaction_metric(
  594. 123,
  595. timestamp=self.day_ago + timedelta(hours=1),
  596. internal_metric="d:transactions/measurements.custom@kibibyte",
  597. entity="metrics_distributions",
  598. )
  599. self.store_transaction_metric(
  600. 123,
  601. timestamp=self.day_ago + timedelta(hours=1),
  602. internal_metric="d:transactions/measurements.another.custom@pebibyte",
  603. entity="metrics_distributions",
  604. )
  605. response = self.do_request(
  606. data={
  607. "start": iso_format(self.day_ago),
  608. "end": iso_format(self.day_ago + timedelta(hours=2)),
  609. "interval": "1h",
  610. "yAxis": [
  611. "p95(measurements.custom)",
  612. "p99(measurements.custom)",
  613. "p99(measurements.another.custom)",
  614. ],
  615. "query": "",
  616. **self.additional_params,
  617. },
  618. )
  619. assert response.status_code == 200
  620. meta = response.data["p95(measurements.custom)"]["meta"]
  621. assert meta["fields"] == {
  622. "time": "date",
  623. "p95_measurements_custom": "size",
  624. "p99_measurements_custom": "size",
  625. "p99_measurements_another_custom": "size",
  626. }
  627. assert meta["units"] == {
  628. "time": None,
  629. "p95_measurements_custom": "kibibyte",
  630. "p99_measurements_custom": "kibibyte",
  631. "p99_measurements_another_custom": "pebibyte",
  632. }
  633. assert meta == response.data["p99(measurements.custom)"]["meta"]
  634. assert meta == response.data["p99(measurements.another.custom)"]["meta"]
  635. def test_no_top_events_with_project_field(self):
  636. project = self.create_project()
  637. response = self.do_request(
  638. data={
  639. # make sure to query the project with 0 events
  640. "project": project.id,
  641. "start": iso_format(self.day_ago),
  642. "end": iso_format(self.day_ago + timedelta(hours=2)),
  643. "interval": "1h",
  644. "yAxis": "count()",
  645. "orderby": ["-count()"],
  646. "field": ["count()", "project"],
  647. "topEvents": 5,
  648. "dataset": "metrics",
  649. **self.additional_params,
  650. },
  651. )
  652. assert response.status_code == 200, response.content
  653. # When there are no top events, we do not return an empty dict.
  654. # Instead, we return a single zero-filled series for an empty graph.
  655. data = response.data["data"]
  656. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  657. def test_top_events_with_transaction(self):
  658. transaction_spec = [("foo", 100), ("bar", 200), ("baz", 300)]
  659. for offset in range(5):
  660. for transaction, duration in transaction_spec:
  661. self.store_transaction_metric(
  662. duration,
  663. tags={"transaction": f"{transaction}_transaction"},
  664. timestamp=self.day_ago + timedelta(hours=offset, minutes=30),
  665. )
  666. response = self.do_request(
  667. data={
  668. # make sure to query the project with 0 events
  669. "project": self.project.id,
  670. "start": iso_format(self.day_ago),
  671. "end": iso_format(self.day_ago + timedelta(hours=5)),
  672. "interval": "1h",
  673. "yAxis": "p75(transaction.duration)",
  674. "orderby": ["-p75(transaction.duration)"],
  675. "field": ["p75(transaction.duration)", "transaction"],
  676. "topEvents": 5,
  677. "dataset": "metrics",
  678. **self.additional_params,
  679. },
  680. )
  681. assert response.status_code == 200, response.content
  682. for position, (transaction, duration) in enumerate(transaction_spec):
  683. data = response.data[f"{transaction}_transaction"]
  684. chart_data = data["data"]
  685. assert data["order"] == 2 - position
  686. assert [attrs for time, attrs in chart_data] == [[{"count": duration}]] * 5
  687. def test_top_events_with_project(self):
  688. self.store_transaction_metric(
  689. 100,
  690. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  691. )
  692. response = self.do_request(
  693. data={
  694. # make sure to query the project with 0 events
  695. "project": self.project.id,
  696. "start": iso_format(self.day_ago),
  697. "end": iso_format(self.day_ago + timedelta(hours=5)),
  698. "interval": "1h",
  699. "yAxis": "p75(transaction.duration)",
  700. "orderby": ["-p75(transaction.duration)"],
  701. "field": ["p75(transaction.duration)", "project"],
  702. "topEvents": 5,
  703. "dataset": "metrics",
  704. **self.additional_params,
  705. },
  706. )
  707. assert response.status_code == 200, response.content
  708. data = response.data[f"{self.project.slug}"]
  709. assert data["order"] == 0
  710. def test_split_decision_for_errors_widget(self):
  711. error_data = load_data("python", timestamp=before_now(minutes=1))
  712. self.store_event(
  713. data={
  714. **error_data,
  715. "exception": {"values": [{"type": "blah", "data": {"values": []}}]},
  716. },
  717. project_id=self.project.id,
  718. )
  719. _, widget, __ = create_widget(
  720. ["count()", "error.type"], "error.type:blah", self.project, discover_widget_split=None
  721. )
  722. response = self.do_request(
  723. {
  724. "field": ["count()", "error.type"],
  725. "query": "error.type:blah",
  726. "dataset": "metricsEnhanced",
  727. "per_page": 50,
  728. "dashboardWidgetId": widget.id,
  729. }
  730. )
  731. assert response.status_code == 200, response.content
  732. assert response.data.get("meta").get(
  733. "discoverSplitDecision"
  734. ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS)
  735. widget.refresh_from_db()
  736. assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
  737. assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value
  738. def test_split_decision_for_transactions_widget(self):
  739. self.store_transaction_metric(
  740. 100,
  741. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  742. )
  743. _, widget, __ = create_widget(
  744. ["count()", "transaction.name"], "", self.project, discover_widget_split=None
  745. )
  746. assert widget.discover_widget_split is None
  747. response = self.do_request(
  748. {
  749. "field": ["count()", "transaction.name"],
  750. "query": "",
  751. "dataset": "metricsEnhanced",
  752. "per_page": 50,
  753. "dashboardWidgetId": widget.id,
  754. }
  755. )
  756. assert response.status_code == 200, response.content
  757. assert response.data.get("meta").get(
  758. "discoverSplitDecision"
  759. ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.TRANSACTION_LIKE)
  760. widget.refresh_from_db()
  761. assert widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE
  762. assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value
  763. def test_split_decision_for_top_events_errors_widget(self):
  764. error_data = load_data("python", timestamp=before_now(minutes=1))
  765. self.store_event(
  766. data={
  767. **error_data,
  768. "exception": {"values": [{"type": "test_error", "data": {"values": []}}]},
  769. },
  770. project_id=self.project.id,
  771. )
  772. _, widget, __ = create_widget(
  773. ["count()", "error.type"],
  774. "error.type:test_error",
  775. self.project,
  776. discover_widget_split=None,
  777. )
  778. response = self.do_request(
  779. {
  780. "field": ["count()", "error.type"],
  781. "query": "error.type:test_error",
  782. "dataset": "metricsEnhanced",
  783. "per_page": 50,
  784. "dashboardWidgetId": widget.id,
  785. "topEvents": 5,
  786. }
  787. )
  788. assert response.status_code == 200, response.content
  789. # Only a singular result for the test_error event
  790. assert len(response.data) == 1
  791. # Results are grouped by the error type
  792. assert response.data.get("test_error").get("meta").get(
  793. "discoverSplitDecision"
  794. ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS)
  795. widget.refresh_from_db()
  796. assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
  797. assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value
  798. def test_split_decision_for_top_events_transactions_widget(self):
  799. self.store_transaction_metric(
  800. 100,
  801. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  802. tags={"transaction": "foo_transaction"},
  803. )
  804. _, widget, __ = create_widget(
  805. ["count()", "transaction"], "", self.project, discover_widget_split=None
  806. )
  807. assert widget.discover_widget_split is None
  808. response = self.do_request(
  809. {
  810. "field": ["count()", "transaction"],
  811. "query": "",
  812. "dataset": "metricsEnhanced",
  813. "per_page": 50,
  814. "dashboardWidgetId": widget.id,
  815. "topEvents": 5,
  816. }
  817. )
  818. assert response.status_code == 200, response.content
  819. # Only a singular result for the transaction
  820. assert len(response.data) == 1
  821. # Results are grouped by the transaction
  822. assert response.data.get("foo_transaction").get("meta").get(
  823. "discoverSplitDecision"
  824. ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.TRANSACTION_LIKE)
  825. widget.refresh_from_db()
  826. assert widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE
  827. assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value
  828. def test_split_decision_for_ambiguous_widget_without_data(self):
  829. _, widget, __ = create_widget(
  830. ["count()", "transaction.name", "error.type"],
  831. "",
  832. self.project,
  833. discover_widget_split=None,
  834. )
  835. assert widget.discover_widget_split is None
  836. response = self.do_request(
  837. {
  838. "field": ["count()", "transaction.name", "error.type"],
  839. "query": "",
  840. "dataset": "metricsEnhanced",
  841. "per_page": 50,
  842. "dashboardWidgetId": widget.id,
  843. },
  844. features={"organizations:performance-discover-dataset-selector": True},
  845. )
  846. assert response.status_code == 200, response.content
  847. assert response.data.get("meta").get(
  848. "discoverSplitDecision"
  849. ) == DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS)
  850. widget.refresh_from_db()
  851. assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
  852. assert widget.dataset_source == DatasetSourcesTypes.FORCED.value
  853. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithMetricLayer(
  854. OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest
  855. ):
  856. def setUp(self):
  857. super().setUp()
  858. self.features["organizations:use-metrics-layer"] = True
  859. self.additional_params = {"forceMetricsLayer": "true"}
  860. def test_counter_standard_metric(self):
  861. mri = "c:transactions/usage@none"
  862. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  863. self.store_transaction_metric(
  864. value,
  865. metric=mri,
  866. internal_metric=mri,
  867. entity="metrics_counters",
  868. timestamp=self.day_ago + timedelta(minutes=index),
  869. use_case_id=UseCaseID.CUSTOM,
  870. )
  871. response = self.do_request(
  872. data={
  873. "start": iso_format(self.day_ago),
  874. "end": iso_format(self.day_ago + timedelta(hours=6)),
  875. "interval": "1m",
  876. "yAxis": [f"sum({mri})"],
  877. "project": self.project.id,
  878. "dataset": "metricsEnhanced",
  879. **self.additional_params,
  880. },
  881. )
  882. assert response.status_code == 200, response.content
  883. data = response.data["data"]
  884. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  885. assert value[0]["count"] == expected_value # type: ignore[index]
  886. def test_counter_custom_metric(self):
  887. mri = "c:custom/sentry.process_profile.track_outcome@second"
  888. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  889. self.store_transaction_metric(
  890. value,
  891. metric=mri,
  892. internal_metric=mri,
  893. entity="metrics_counters",
  894. timestamp=self.day_ago + timedelta(hours=index),
  895. use_case_id=UseCaseID.CUSTOM,
  896. )
  897. response = self.do_request(
  898. data={
  899. "start": iso_format(self.day_ago),
  900. "end": iso_format(self.day_ago + timedelta(hours=6)),
  901. "interval": "1h",
  902. "yAxis": [f"sum({mri})"],
  903. "project": self.project.id,
  904. "dataset": "metricsEnhanced",
  905. **self.additional_params,
  906. },
  907. )
  908. assert response.status_code == 200, response.content
  909. data = response.data["data"]
  910. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  911. assert value[0]["count"] == expected_value # type: ignore[index]
  912. def test_distribution_custom_metric(self):
  913. mri = "d:custom/sentry.process_profile.track_outcome@second"
  914. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  915. for multiplier in (1, 2, 3):
  916. self.store_transaction_metric(
  917. value * multiplier,
  918. metric=mri,
  919. internal_metric=mri,
  920. entity="metrics_distributions",
  921. timestamp=self.day_ago + timedelta(hours=index),
  922. use_case_id=UseCaseID.CUSTOM,
  923. )
  924. response = self.do_request(
  925. data={
  926. "start": iso_format(self.day_ago),
  927. "end": iso_format(self.day_ago + timedelta(hours=6)),
  928. "interval": "1h",
  929. "yAxis": [f"min({mri})", f"max({mri})", f"p90({mri})"],
  930. "project": self.project.id,
  931. "dataset": "metricsEnhanced",
  932. **self.additional_params,
  933. },
  934. )
  935. assert response.status_code == 200, response.content
  936. data = response.data
  937. min = data[f"min({mri})"]["data"]
  938. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  939. assert value[0]["count"] == expected_value # type: ignore[index]
  940. max = data[f"max({mri})"]["data"]
  941. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  942. assert value[0]["count"] == expected_value # type: ignore[index]
  943. p90 = data[f"p90({mri})"]["data"]
  944. for (_, value), expected_value in zip(p90, [28.0, 56.0, 84.0, 112.0, 140.0, 168.0]):
  945. assert value[0]["count"] == expected_value # type: ignore[index]
  946. def test_set_custom_metric(self):
  947. mri = "s:custom/sentry.process_profile.track_outcome@second"
  948. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  949. # We store each value a second time, since we want to check the de-duplication of sets.
  950. for i in range(0, 2):
  951. self.store_transaction_metric(
  952. value,
  953. metric=mri,
  954. internal_metric=mri,
  955. entity="metrics_sets",
  956. timestamp=self.day_ago + timedelta(hours=index),
  957. use_case_id=UseCaseID.CUSTOM,
  958. )
  959. response = self.do_request(
  960. data={
  961. "start": iso_format(self.day_ago),
  962. "end": iso_format(self.day_ago + timedelta(hours=6)),
  963. "interval": "1h",
  964. "yAxis": [f"count_unique({mri})"],
  965. "project": self.project.id,
  966. "dataset": "metricsEnhanced",
  967. **self.additional_params,
  968. },
  969. )
  970. assert response.status_code == 200, response.content
  971. data = response.data["data"]
  972. for (_, value), expected_value in zip(data, [1, 1, 1, 1, 1, 1]):
  973. assert value[0]["count"] == expected_value # type: ignore[index]
  974. def test_gauge_custom_metric(self):
  975. mri = "g:custom/sentry.process_profile.track_outcome@second"
  976. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  977. for multiplier in (1, 3):
  978. self.store_transaction_metric(
  979. value * multiplier,
  980. metric=mri,
  981. internal_metric=mri,
  982. entity="metrics_gauges",
  983. # When multiple gauges are merged, in order to make the `last` merge work deterministically it's
  984. # better to have the gauges with different timestamps so that the last value is always the same.
  985. timestamp=self.day_ago + timedelta(hours=index, minutes=multiplier),
  986. use_case_id=UseCaseID.CUSTOM,
  987. )
  988. response = self.do_request(
  989. data={
  990. "start": iso_format(self.day_ago),
  991. "end": iso_format(self.day_ago + timedelta(hours=6)),
  992. "interval": "1h",
  993. "yAxis": [
  994. f"min({mri})",
  995. f"max({mri})",
  996. f"last({mri})",
  997. f"sum({mri})",
  998. f"count({mri})",
  999. ],
  1000. "project": self.project.id,
  1001. "dataset": "metricsEnhanced",
  1002. **self.additional_params,
  1003. },
  1004. )
  1005. assert response.status_code == 200, response.content
  1006. data = response.data
  1007. min = data[f"min({mri})"]["data"]
  1008. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  1009. assert value[0]["count"] == expected_value # type: ignore[index]
  1010. max = data[f"max({mri})"]["data"]
  1011. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  1012. assert value[0]["count"] == expected_value # type: ignore[index]
  1013. last = data[f"last({mri})"]["data"]
  1014. for (_, value), expected_value in zip(last, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  1015. assert value[0]["count"] == expected_value # type: ignore[index]
  1016. sum = data[f"sum({mri})"]["data"]
  1017. for (_, value), expected_value in zip(sum, [40.0, 80.0, 120.0, 160.0, 200.0, 240.0]):
  1018. assert value[0]["count"] == expected_value # type: ignore[index]
  1019. count = data[f"count({mri})"]["data"]
  1020. for (_, value), expected_value in zip(count, [40, 80, 120, 160, 200, 240]):
  1021. assert value[0]["count"] == expected_value # type: ignore[index]
  1022. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithOnDemandWidgets(
  1023. MetricsEnhancedPerformanceTestCase
  1024. ):
  1025. endpoint = "sentry-api-0-organization-events-stats"
  1026. def setUp(self):
  1027. super().setUp()
  1028. self.login_as(user=self.user)
  1029. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  1030. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  1031. Environment.get_or_create(self.project, "production")
  1032. self.url = reverse(
  1033. "sentry-api-0-organization-events-stats",
  1034. kwargs={"organization_id_or_slug": self.project.organization.slug},
  1035. )
  1036. self.features = {
  1037. "organizations:on-demand-metrics-extraction-widgets": True,
  1038. "organizations:on-demand-metrics-extraction": True,
  1039. }
  1040. def _make_on_demand_request(
  1041. self, params: dict[str, Any], extra_features: dict[str, bool] | None = None
  1042. ) -> Response:
  1043. """Ensures that the required parameters for an on-demand request are included."""
  1044. # Expected parameters for this helper function
  1045. params["dataset"] = "metricsEnhanced"
  1046. params["useOnDemandMetrics"] = "true"
  1047. params["onDemandType"] = "dynamic_query"
  1048. _features = {**self.features, **(extra_features or {})}
  1049. return self.do_request(params, features=_features)
  1050. def test_top_events_wrong_on_demand_type(self):
  1051. query = "transaction.duration:>=100"
  1052. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1053. response = self.do_request(
  1054. data={
  1055. "project": self.project.id,
  1056. "start": iso_format(self.day_ago),
  1057. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1058. "interval": "1h",
  1059. "orderby": ["-count()"],
  1060. "environment": "production",
  1061. "query": query,
  1062. "yAxis": yAxis,
  1063. "field": [
  1064. "count()",
  1065. ],
  1066. "topEvents": 5,
  1067. "dataset": "metrics",
  1068. "useOnDemandMetrics": "true",
  1069. "onDemandType": "not_real",
  1070. },
  1071. )
  1072. assert response.status_code == 400, response.content
  1073. def test_top_events_works_without_on_demand_type(self):
  1074. query = "transaction.duration:>=100"
  1075. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1076. response = self.do_request(
  1077. data={
  1078. "project": self.project.id,
  1079. "start": iso_format(self.day_ago),
  1080. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1081. "interval": "1h",
  1082. "orderby": ["-count()"],
  1083. "environment": "production",
  1084. "query": query,
  1085. "yAxis": yAxis,
  1086. "field": [
  1087. "count()",
  1088. ],
  1089. "topEvents": 5,
  1090. "dataset": "metrics",
  1091. "useOnDemandMetrics": "true",
  1092. },
  1093. )
  1094. assert response.status_code == 200, response.content
  1095. def test_top_events_with_transaction_on_demand(self):
  1096. field = "count()"
  1097. field_two = "count_web_vitals(measurements.lcp, good)"
  1098. groupbys = ["customtag1", "customtag2"]
  1099. query = "transaction.duration:>=100"
  1100. spec = OnDemandMetricSpec(
  1101. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1102. )
  1103. spec_two = OnDemandMetricSpec(
  1104. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1105. )
  1106. for hour in range(0, 5):
  1107. self.store_on_demand_metric(
  1108. hour * 62 * 24,
  1109. spec=spec,
  1110. additional_tags={
  1111. "customtag1": "foo",
  1112. "customtag2": "red",
  1113. "environment": "production",
  1114. },
  1115. timestamp=self.day_ago + timedelta(hours=hour),
  1116. )
  1117. self.store_on_demand_metric(
  1118. hour * 60 * 24,
  1119. spec=spec_two,
  1120. additional_tags={
  1121. "customtag1": "bar",
  1122. "customtag2": "blue",
  1123. "environment": "production",
  1124. },
  1125. timestamp=self.day_ago + timedelta(hours=hour),
  1126. )
  1127. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1128. response = self.do_request(
  1129. data={
  1130. "project": self.project.id,
  1131. "start": iso_format(self.day_ago),
  1132. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1133. "interval": "1h",
  1134. "orderby": ["-count()"],
  1135. "environment": "production",
  1136. "query": query,
  1137. "yAxis": yAxis,
  1138. "field": [
  1139. "count()",
  1140. "count_web_vitals(measurements.lcp, good)",
  1141. "customtag1",
  1142. "customtag2",
  1143. ],
  1144. "topEvents": 5,
  1145. "dataset": "metricsEnhanced",
  1146. "useOnDemandMetrics": "true",
  1147. "onDemandType": "dynamic_query",
  1148. },
  1149. )
  1150. assert response.status_code == 200, response.content
  1151. groups = [
  1152. ("foo,red", "count()", 0.0, 1488.0),
  1153. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1154. ("bar,blue", "count()", 0.0, 0.0),
  1155. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1156. ]
  1157. assert len(response.data.keys()) == 2
  1158. for group_count in groups:
  1159. group, agg, row1, row2 = group_count
  1160. row_data = response.data[group][agg]["data"][:2]
  1161. assert [attrs for _, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1162. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1163. assert response.data[group]["isMetricsExtractedData"]
  1164. def test_top_events_with_transaction_on_demand_and_no_environment(self):
  1165. field = "count()"
  1166. field_two = "count_web_vitals(measurements.lcp, good)"
  1167. groupbys = ["customtag1", "customtag2"]
  1168. query = "transaction.duration:>=100"
  1169. spec = OnDemandMetricSpec(
  1170. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1171. )
  1172. spec_two = OnDemandMetricSpec(
  1173. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1174. )
  1175. for hour in range(0, 5):
  1176. self.store_on_demand_metric(
  1177. hour * 62 * 24,
  1178. spec=spec,
  1179. additional_tags={
  1180. "customtag1": "foo",
  1181. "customtag2": "red",
  1182. "environment": "production",
  1183. },
  1184. timestamp=self.day_ago + timedelta(hours=hour),
  1185. )
  1186. self.store_on_demand_metric(
  1187. hour * 60 * 24,
  1188. spec=spec_two,
  1189. additional_tags={
  1190. "customtag1": "bar",
  1191. "customtag2": "blue",
  1192. "environment": "production",
  1193. },
  1194. timestamp=self.day_ago + timedelta(hours=hour),
  1195. )
  1196. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1197. response = self.do_request(
  1198. data={
  1199. "project": self.project.id,
  1200. "start": iso_format(self.day_ago),
  1201. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1202. "interval": "1h",
  1203. "orderby": ["-count()"],
  1204. "query": query,
  1205. "yAxis": yAxis,
  1206. "field": [
  1207. "count()",
  1208. "count_web_vitals(measurements.lcp, good)",
  1209. "customtag1",
  1210. "customtag2",
  1211. ],
  1212. "topEvents": 5,
  1213. "dataset": "metricsEnhanced",
  1214. "useOnDemandMetrics": "true",
  1215. "onDemandType": "dynamic_query",
  1216. },
  1217. )
  1218. assert response.status_code == 200, response.content
  1219. groups = [
  1220. ("foo,red", "count()", 0.0, 1488.0),
  1221. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1222. ("bar,blue", "count()", 0.0, 0.0),
  1223. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1224. ]
  1225. assert len(response.data.keys()) == 2
  1226. for group_count in groups:
  1227. group, agg, row1, row2 = group_count
  1228. row_data = response.data[group][agg]["data"][:2]
  1229. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1230. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1231. assert response.data[group]["isMetricsExtractedData"]
  1232. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_transaction_only(self):
  1233. field = "count()"
  1234. field_two = "count_web_vitals(measurements.lcp, good)"
  1235. groupbys = ["customtag1", "customtag2"]
  1236. query = "transaction.duration:>=100"
  1237. spec = OnDemandMetricSpec(
  1238. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1239. )
  1240. spec_two = OnDemandMetricSpec(
  1241. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1242. )
  1243. _, widget, __ = create_widget(
  1244. ["count()"],
  1245. "",
  1246. self.project,
  1247. discover_widget_split=None,
  1248. )
  1249. for hour in range(0, 2):
  1250. self.store_on_demand_metric(
  1251. hour * 62 * 24,
  1252. spec=spec,
  1253. additional_tags={
  1254. "customtag1": "foo",
  1255. "customtag2": "red",
  1256. "environment": "production",
  1257. },
  1258. timestamp=self.day_ago + timedelta(hours=hour),
  1259. )
  1260. self.store_on_demand_metric(
  1261. hour * 60 * 24,
  1262. spec=spec_two,
  1263. additional_tags={
  1264. "customtag1": "bar",
  1265. "customtag2": "blue",
  1266. "environment": "production",
  1267. },
  1268. timestamp=self.day_ago + timedelta(hours=hour),
  1269. )
  1270. yAxis = [field, field_two]
  1271. response = self.do_request(
  1272. data={
  1273. "project": self.project.id,
  1274. "start": iso_format(self.day_ago),
  1275. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1276. "interval": "1h",
  1277. "orderby": ["-count()"],
  1278. "query": query,
  1279. "yAxis": yAxis,
  1280. "field": yAxis + groupbys,
  1281. "topEvents": 5,
  1282. "dataset": "metricsEnhanced",
  1283. "useOnDemandMetrics": "true",
  1284. "onDemandType": "dynamic_query",
  1285. "dashboardWidgetId": widget.id,
  1286. },
  1287. )
  1288. saved_widget = DashboardWidget.objects.get(id=widget.id)
  1289. assert saved_widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE
  1290. assert response.status_code == 200, response.content
  1291. # Fell back to discover data which is empty for this test (empty group of '').
  1292. assert len(response.data.keys()) == 2
  1293. assert bool(response.data["foo,red"])
  1294. assert bool(response.data["bar,blue"])
  1295. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_error(
  1296. self,
  1297. ):
  1298. self.project = self.create_project(organization=self.organization)
  1299. Environment.get_or_create(self.project, "production")
  1300. field = "count()"
  1301. field_two = "count()"
  1302. groupbys = ["customtag1", "customtag2"]
  1303. query = "query.dataset:foo"
  1304. _, widget, __ = create_widget(
  1305. ["count()"],
  1306. "",
  1307. self.project,
  1308. discover_widget_split=None,
  1309. )
  1310. self.store_event(
  1311. data={
  1312. "event_id": "a" * 32,
  1313. "message": "very bad",
  1314. "type": "error",
  1315. "start_timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1316. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1317. "tags": {"customtag1": "error_value", "query.dataset": "foo"},
  1318. },
  1319. project_id=self.project.id,
  1320. )
  1321. self.store_event(
  1322. data={
  1323. "event_id": "b" * 32,
  1324. "message": "very bad 2",
  1325. "type": "error",
  1326. "start_timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1327. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1328. "tags": {"customtag1": "error_value2", "query.dataset": "foo"},
  1329. },
  1330. project_id=self.project.id,
  1331. )
  1332. yAxis = ["count()"]
  1333. response = self.do_request(
  1334. data={
  1335. "project": self.project.id,
  1336. "start": iso_format(self.day_ago),
  1337. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1338. "interval": "1h",
  1339. "orderby": ["-count()"],
  1340. "query": query,
  1341. "yAxis": yAxis,
  1342. "field": [field, field_two] + groupbys,
  1343. "topEvents": 5,
  1344. "dataset": "metricsEnhanced",
  1345. "useOnDemandMetrics": "true",
  1346. "onDemandType": "dynamic_query",
  1347. "dashboardWidgetId": widget.id,
  1348. },
  1349. )
  1350. saved_widget = DashboardWidget.objects.get(id=widget.id)
  1351. assert saved_widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
  1352. assert response.status_code == 200, response.content
  1353. # Fell back to discover data which is empty for this test (empty group of '').
  1354. assert len(response.data.keys()) == 2
  1355. assert bool(response.data["error_value,"])
  1356. assert bool(response.data["error_value2,"])
  1357. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_discover(self):
  1358. self.project = self.create_project(organization=self.organization)
  1359. Environment.get_or_create(self.project, "production")
  1360. field = "count()"
  1361. field_two = "count()"
  1362. groupbys = ["customtag1", "customtag2"]
  1363. query = "query.dataset:foo"
  1364. spec = OnDemandMetricSpec(
  1365. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1366. )
  1367. spec_two = OnDemandMetricSpec(
  1368. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1369. )
  1370. _, widget, __ = create_widget(
  1371. ["count()"],
  1372. "",
  1373. self.project,
  1374. discover_widget_split=None,
  1375. )
  1376. self.store_event(
  1377. data={
  1378. "event_id": "a" * 32,
  1379. "message": "very bad",
  1380. "type": "error",
  1381. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1382. "tags": {"customtag1": "error_value", "query.dataset": "foo"},
  1383. },
  1384. project_id=self.project.id,
  1385. )
  1386. transaction = load_data("transaction")
  1387. transaction["timestamp"] = iso_format(self.day_ago + timedelta(hours=1))
  1388. transaction["start_timestamp"] = iso_format(self.day_ago + timedelta(hours=1))
  1389. transaction["tags"] = {"customtag1": "transaction_value", "query.dataset": "foo"}
  1390. self.store_event(
  1391. data=transaction,
  1392. project_id=self.project.id,
  1393. )
  1394. for hour in range(0, 5):
  1395. self.store_on_demand_metric(
  1396. hour * 62 * 24,
  1397. spec=spec,
  1398. additional_tags={
  1399. "customtag1": "foo",
  1400. "customtag2": "red",
  1401. "environment": "production",
  1402. },
  1403. timestamp=self.day_ago + timedelta(hours=hour),
  1404. )
  1405. self.store_on_demand_metric(
  1406. hour * 60 * 24,
  1407. spec=spec_two,
  1408. additional_tags={
  1409. "customtag1": "bar",
  1410. "customtag2": "blue",
  1411. "environment": "production",
  1412. },
  1413. timestamp=self.day_ago + timedelta(hours=hour),
  1414. )
  1415. yAxis = ["count()"]
  1416. response = self.do_request(
  1417. data={
  1418. "project": self.project.id,
  1419. "start": iso_format(self.day_ago),
  1420. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1421. "interval": "1h",
  1422. "orderby": ["-count()"],
  1423. "query": query,
  1424. "yAxis": yAxis,
  1425. "field": [field, field_two, "customtag1", "customtag2"],
  1426. "topEvents": 5,
  1427. "dataset": "metricsEnhanced",
  1428. "useOnDemandMetrics": "true",
  1429. "onDemandType": "dynamic_query",
  1430. "dashboardWidgetId": widget.id,
  1431. },
  1432. )
  1433. saved_widget = DashboardWidget.objects.get(id=widget.id)
  1434. assert saved_widget.discover_widget_split == DashboardWidgetTypes.DISCOVER
  1435. assert response.status_code == 200, response.content
  1436. assert response.status_code == 200, response.content
  1437. # Fell back to discover data which is empty for this test (empty group of '').
  1438. assert len(response.data.keys()) == 2
  1439. assert bool(response.data["error_value,"])
  1440. assert bool(response.data["transaction_value,"])
  1441. def test_top_events_with_transaction_on_demand_passing_widget_id_saved(self):
  1442. field = "count()"
  1443. field_two = "count_web_vitals(measurements.lcp, good)"
  1444. groupbys = ["customtag1", "customtag2"]
  1445. query = "transaction.duration:>=100"
  1446. spec = OnDemandMetricSpec(
  1447. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1448. )
  1449. spec_two = OnDemandMetricSpec(
  1450. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1451. )
  1452. _, widget, __ = create_widget(
  1453. ["count()"],
  1454. "",
  1455. self.project,
  1456. discover_widget_split=DashboardWidgetTypes.TRANSACTION_LIKE, # Transactions like uses on-demand
  1457. )
  1458. for hour in range(0, 5):
  1459. self.store_on_demand_metric(
  1460. hour * 62 * 24,
  1461. spec=spec,
  1462. additional_tags={
  1463. "customtag1": "foo",
  1464. "customtag2": "red",
  1465. "environment": "production",
  1466. },
  1467. timestamp=self.day_ago + timedelta(hours=hour),
  1468. )
  1469. self.store_on_demand_metric(
  1470. hour * 60 * 24,
  1471. spec=spec_two,
  1472. additional_tags={
  1473. "customtag1": "bar",
  1474. "customtag2": "blue",
  1475. "environment": "production",
  1476. },
  1477. timestamp=self.day_ago + timedelta(hours=hour),
  1478. )
  1479. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1480. with mock.patch.object(widget, "save") as mock_widget_save:
  1481. response = self.do_request(
  1482. data={
  1483. "project": self.project.id,
  1484. "start": iso_format(self.day_ago),
  1485. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1486. "interval": "1h",
  1487. "orderby": ["-count()"],
  1488. "query": query,
  1489. "yAxis": yAxis,
  1490. "field": [
  1491. "count()",
  1492. "count_web_vitals(measurements.lcp, good)",
  1493. "customtag1",
  1494. "customtag2",
  1495. ],
  1496. "topEvents": 5,
  1497. "dataset": "metricsEnhanced",
  1498. "useOnDemandMetrics": "true",
  1499. "onDemandType": "dynamic_query",
  1500. "dashboardWidgetId": widget.id,
  1501. },
  1502. )
  1503. assert bool(mock_widget_save.assert_not_called)
  1504. assert response.status_code == 200, response.content
  1505. groups = [
  1506. ("foo,red", "count()", 0.0, 1488.0),
  1507. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1508. ("bar,blue", "count()", 0.0, 0.0),
  1509. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1510. ]
  1511. assert len(response.data.keys()) == 2
  1512. for group_count in groups:
  1513. group, agg, row1, row2 = group_count
  1514. row_data = response.data[group][agg]["data"][:2]
  1515. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1516. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1517. assert response.data[group]["isMetricsExtractedData"]
  1518. def test_timeseries_on_demand_with_multiple_percentiles(self):
  1519. field = "p75(measurements.fcp)"
  1520. field_two = "p75(measurements.lcp)"
  1521. query = "transaction.duration:>=100"
  1522. spec = OnDemandMetricSpec(field=field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY)
  1523. spec_two = OnDemandMetricSpec(
  1524. field=field_two, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1525. )
  1526. assert (
  1527. spec._query_str_for_hash
  1528. == "event.measurements.fcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1529. )
  1530. assert (
  1531. spec_two._query_str_for_hash
  1532. == "event.measurements.lcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1533. )
  1534. for count in range(0, 4):
  1535. self.store_on_demand_metric(
  1536. count * 100,
  1537. spec=spec,
  1538. timestamp=self.day_ago + timedelta(hours=1),
  1539. )
  1540. self.store_on_demand_metric(
  1541. count * 200.0,
  1542. spec=spec_two,
  1543. timestamp=self.day_ago + timedelta(hours=1),
  1544. )
  1545. yAxis = [field, field_two]
  1546. response = self.do_request(
  1547. data={
  1548. "project": self.project.id,
  1549. "start": iso_format(self.day_ago),
  1550. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1551. "interval": "1h",
  1552. "orderby": [field],
  1553. "query": query,
  1554. "yAxis": yAxis,
  1555. "dataset": "metricsEnhanced",
  1556. "useOnDemandMetrics": "true",
  1557. "onDemandType": "dynamic_query",
  1558. },
  1559. )
  1560. assert response.status_code == 200, response.content
  1561. assert response.data["p75(measurements.fcp)"]["meta"]["isMetricsExtractedData"]
  1562. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1563. assert [attrs for time, attrs in response.data["p75(measurements.fcp)"]["data"]] == [
  1564. [{"count": 0}],
  1565. [{"count": 225.0}],
  1566. ]
  1567. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsExtractedData"]
  1568. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1569. assert [attrs for time, attrs in response.data["p75(measurements.lcp)"]["data"]] == [
  1570. [{"count": 0}],
  1571. [{"count": 450.0}],
  1572. ]
  1573. def test_apdex_issue(self):
  1574. field = "apdex(300)"
  1575. groupbys = ["group_tag"]
  1576. query = "transaction.duration:>=100"
  1577. spec = OnDemandMetricSpec(
  1578. field=field,
  1579. groupbys=groupbys,
  1580. query=query,
  1581. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1582. )
  1583. for hour in range(0, 5):
  1584. self.store_on_demand_metric(
  1585. 1,
  1586. spec=spec,
  1587. additional_tags={
  1588. "group_tag": "group_one",
  1589. "environment": "production",
  1590. "satisfaction": "tolerable",
  1591. },
  1592. timestamp=self.day_ago + timedelta(hours=hour),
  1593. )
  1594. self.store_on_demand_metric(
  1595. 1,
  1596. spec=spec,
  1597. additional_tags={
  1598. "group_tag": "group_two",
  1599. "environment": "production",
  1600. "satisfaction": "satisfactory",
  1601. },
  1602. timestamp=self.day_ago + timedelta(hours=hour),
  1603. )
  1604. response = self.do_request(
  1605. data={
  1606. "dataset": "metricsEnhanced",
  1607. "environment": "production",
  1608. "excludeOther": 1,
  1609. "field": [field, "group_tag"],
  1610. "start": iso_format(self.day_ago),
  1611. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1612. "interval": "1h",
  1613. "orderby": f"-{field}",
  1614. "partial": 1,
  1615. "project": self.project.id,
  1616. "query": query,
  1617. "topEvents": 5,
  1618. "yAxis": field,
  1619. "onDemandType": "dynamic_query",
  1620. "useOnDemandMetrics": "true",
  1621. },
  1622. )
  1623. assert response.status_code == 200, response.content
  1624. assert response.data["group_one"]["meta"]["isMetricsExtractedData"] is True
  1625. assert [attrs for time, attrs in response.data["group_one"]["data"]] == [
  1626. [{"count": 0.5}],
  1627. [{"count": 0.5}],
  1628. ]
  1629. def test_glob_http_referer_on_demand(self):
  1630. agg = "count()"
  1631. network_id_tag = "networkId"
  1632. url = "https://sentry.io"
  1633. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1634. spec = OnDemandMetricSpec(
  1635. field=agg,
  1636. groupbys=[network_id_tag],
  1637. query=query,
  1638. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1639. )
  1640. assert spec.to_metric_spec(self.project) == {
  1641. "category": "transaction",
  1642. "mri": "c:transactions/on_demand@none",
  1643. "field": None,
  1644. "tags": [
  1645. {"key": "query_hash", "value": "ac241f56"},
  1646. {"key": "networkId", "field": "event.tags.networkId"},
  1647. {"key": "environment", "field": "event.environment"},
  1648. ],
  1649. "condition": {
  1650. "op": "and",
  1651. "inner": [
  1652. {
  1653. "op": "glob",
  1654. "name": "event.request.url",
  1655. "value": ["https://sentry.io/*/foo/bar/*"],
  1656. },
  1657. {
  1658. "op": "glob",
  1659. "name": "event.request.headers.Referer",
  1660. "value": ["https://sentry.io/*/bar/*"],
  1661. },
  1662. ],
  1663. },
  1664. }
  1665. for hour in range(0, 5):
  1666. self.store_on_demand_metric(
  1667. 1,
  1668. spec=spec,
  1669. additional_tags={network_id_tag: "1234"},
  1670. timestamp=self.day_ago + timedelta(hours=hour),
  1671. )
  1672. self.store_on_demand_metric(
  1673. 1,
  1674. spec=spec,
  1675. additional_tags={network_id_tag: "5678"},
  1676. timestamp=self.day_ago + timedelta(hours=hour),
  1677. )
  1678. response = self.do_request(
  1679. data={
  1680. "dataset": "metricsEnhanced",
  1681. "field": [network_id_tag, agg],
  1682. "start": iso_format(self.day_ago),
  1683. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1684. "onDemandType": "dynamic_query",
  1685. "orderby": f"-{agg}",
  1686. "interval": "1d",
  1687. "partial": 1,
  1688. "query": query,
  1689. "referrer": "api.dashboards.widget.bar-chart",
  1690. "project": self.project.id,
  1691. "topEvents": 2,
  1692. "useOnDemandMetrics": "true",
  1693. "yAxis": agg,
  1694. },
  1695. )
  1696. assert response.status_code == 200, response.content
  1697. for datum in response.data.values():
  1698. assert datum["meta"] == {
  1699. "dataset": "metricsEnhanced",
  1700. "datasetReason": "unchanged",
  1701. "fields": {},
  1702. "isMetricsData": False,
  1703. "isMetricsExtractedData": True,
  1704. "tips": {},
  1705. "units": {},
  1706. }
  1707. def _test_is_metrics_extracted_data(
  1708. self, params: dict[str, Any], expected_on_demand_query: bool, dataset: str
  1709. ) -> None:
  1710. spec = OnDemandMetricSpec(
  1711. field="count()",
  1712. query="transaction.duration:>1s",
  1713. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1714. )
  1715. self.store_on_demand_metric(1, spec=spec)
  1716. response = self.do_request(params)
  1717. assert response.status_code == 200, response.content
  1718. meta = response.data["meta"]
  1719. # This is the main thing we want to test for
  1720. assert meta.get("isMetricsExtractedData", False) is expected_on_demand_query
  1721. assert meta["dataset"] == dataset
  1722. return meta
  1723. def test_is_metrics_extracted_data_is_included(self):
  1724. self._test_is_metrics_extracted_data(
  1725. {
  1726. "dataset": "metricsEnhanced",
  1727. "query": "transaction.duration:>=91",
  1728. "useOnDemandMetrics": "true",
  1729. "yAxis": "count()",
  1730. },
  1731. expected_on_demand_query=True,
  1732. dataset="metricsEnhanced",
  1733. )
  1734. def test_on_demand_epm_no_query(self):
  1735. params = {
  1736. "dataset": "metricsEnhanced",
  1737. "environment": "production",
  1738. "onDemandType": "dynamic_query",
  1739. "project": self.project.id,
  1740. "query": "",
  1741. "statsPeriod": "1h",
  1742. "useOnDemandMetrics": "true",
  1743. "yAxis": ["epm()"],
  1744. }
  1745. response = self.do_request(params)
  1746. assert response.status_code == 200, response.content
  1747. assert response.data["meta"] == {
  1748. "fields": {"time": "date", "epm_900": "rate"},
  1749. "units": {"time": None, "epm_900": None},
  1750. "isMetricsData": True,
  1751. "isMetricsExtractedData": False,
  1752. "tips": {},
  1753. "datasetReason": "unchanged",
  1754. "dataset": "metricsEnhanced",
  1755. }
  1756. def test_group_by_transaction(self):
  1757. field = "count()"
  1758. groupbys = ["transaction"]
  1759. query = "transaction.duration:>=100"
  1760. spec = OnDemandMetricSpec(
  1761. field=field,
  1762. groupbys=groupbys,
  1763. query=query,
  1764. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1765. )
  1766. for hour in range(0, 2):
  1767. self.store_on_demand_metric(
  1768. (hour + 1) * 5,
  1769. spec=spec,
  1770. additional_tags={
  1771. "transaction": "/performance",
  1772. "environment": "production",
  1773. },
  1774. timestamp=self.day_ago + timedelta(hours=hour),
  1775. )
  1776. response = self.do_request(
  1777. data={
  1778. "dataset": "metricsEnhanced",
  1779. "environment": "production",
  1780. "excludeOther": 1,
  1781. "field": [field, "transaction"],
  1782. "start": iso_format(self.day_ago),
  1783. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1784. "interval": "1h",
  1785. "orderby": f"-{field}",
  1786. "partial": 1,
  1787. "project": self.project.id,
  1788. "query": query,
  1789. "topEvents": 5,
  1790. "yAxis": field,
  1791. "onDemandType": "dynamic_query",
  1792. "useOnDemandMetrics": "true",
  1793. },
  1794. )
  1795. assert response.status_code == 200, response.content
  1796. assert response.data["/performance"]["meta"]["isMetricsExtractedData"] is True
  1797. assert [attrs for time, attrs in response.data["/performance"]["data"]] == [
  1798. [{"count": 5.0}],
  1799. [{"count": 10.0}],
  1800. ]
  1801. def _setup_orderby_tests(self, query):
  1802. count_spec = OnDemandMetricSpec(
  1803. field="count()",
  1804. groupbys=["networkId"],
  1805. query=query,
  1806. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1807. )
  1808. p95_spec = OnDemandMetricSpec(
  1809. field="p95(transaction.duration)",
  1810. groupbys=["networkId"],
  1811. query=query,
  1812. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1813. )
  1814. for hour in range(0, 5):
  1815. self.store_on_demand_metric(
  1816. 1,
  1817. spec=count_spec,
  1818. additional_tags={"networkId": "1234"},
  1819. timestamp=self.day_ago + timedelta(hours=hour),
  1820. )
  1821. self.store_on_demand_metric(
  1822. 100,
  1823. spec=p95_spec,
  1824. additional_tags={"networkId": "1234"},
  1825. timestamp=self.day_ago + timedelta(hours=hour),
  1826. )
  1827. self.store_on_demand_metric(
  1828. 200,
  1829. spec=p95_spec,
  1830. additional_tags={"networkId": "5678"},
  1831. timestamp=self.day_ago + timedelta(hours=hour),
  1832. )
  1833. # Store twice as many 5678 so orderby puts it later
  1834. self.store_on_demand_metric(
  1835. 2,
  1836. spec=count_spec,
  1837. additional_tags={"networkId": "5678"},
  1838. timestamp=self.day_ago + timedelta(hours=hour),
  1839. )
  1840. def test_order_by_aggregate_top_events_desc(self):
  1841. url = "https://sentry.io"
  1842. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1843. self._setup_orderby_tests(query)
  1844. response = self.do_request(
  1845. data={
  1846. "dataset": "metricsEnhanced",
  1847. "field": ["networkId", "count()"],
  1848. "start": iso_format(self.day_ago),
  1849. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1850. "onDemandType": "dynamic_query",
  1851. "orderby": "-count()",
  1852. "interval": "1d",
  1853. "partial": 1,
  1854. "query": query,
  1855. "referrer": "api.dashboards.widget.bar-chart",
  1856. "project": self.project.id,
  1857. "topEvents": 2,
  1858. "useOnDemandMetrics": "true",
  1859. "yAxis": "count()",
  1860. },
  1861. )
  1862. assert response.status_code == 200, response.content
  1863. assert len(response.data) == 3
  1864. data1 = response.data["5678"]
  1865. assert data1["order"] == 0
  1866. assert data1["data"][0][1][0]["count"] == 10
  1867. data2 = response.data["1234"]
  1868. assert data2["order"] == 1
  1869. assert data2["data"][0][1][0]["count"] == 5
  1870. for datum in response.data.values():
  1871. assert datum["meta"] == {
  1872. "dataset": "metricsEnhanced",
  1873. "datasetReason": "unchanged",
  1874. "fields": {},
  1875. "isMetricsData": False,
  1876. "isMetricsExtractedData": True,
  1877. "tips": {},
  1878. "units": {},
  1879. }
  1880. def test_order_by_aggregate_top_events_asc(self):
  1881. url = "https://sentry.io"
  1882. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1883. self._setup_orderby_tests(query)
  1884. response = self.do_request(
  1885. data={
  1886. "dataset": "metricsEnhanced",
  1887. "field": ["networkId", "count()"],
  1888. "start": iso_format(self.day_ago),
  1889. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1890. "onDemandType": "dynamic_query",
  1891. "orderby": "count()",
  1892. "interval": "1d",
  1893. "partial": 1,
  1894. "query": query,
  1895. "referrer": "api.dashboards.widget.bar-chart",
  1896. "project": self.project.id,
  1897. "topEvents": 2,
  1898. "useOnDemandMetrics": "true",
  1899. "yAxis": "count()",
  1900. },
  1901. )
  1902. assert response.status_code == 200, response.content
  1903. assert len(response.data) == 3
  1904. data1 = response.data["1234"]
  1905. assert data1["order"] == 0
  1906. assert data1["data"][0][1][0]["count"] == 5
  1907. data2 = response.data["5678"]
  1908. assert data2["order"] == 1
  1909. assert data2["data"][0][1][0]["count"] == 10
  1910. for datum in response.data.values():
  1911. assert datum["meta"] == {
  1912. "dataset": "metricsEnhanced",
  1913. "datasetReason": "unchanged",
  1914. "fields": {},
  1915. "isMetricsData": False,
  1916. "isMetricsExtractedData": True,
  1917. "tips": {},
  1918. "units": {},
  1919. }
  1920. def test_order_by_aggregate_top_events_graph_different_aggregate(self):
  1921. url = "https://sentry.io"
  1922. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1923. self._setup_orderby_tests(query)
  1924. response = self.do_request(
  1925. data={
  1926. "dataset": "metricsEnhanced",
  1927. "field": ["networkId", "count()"],
  1928. "start": iso_format(self.day_ago),
  1929. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1930. "onDemandType": "dynamic_query",
  1931. "orderby": "count()",
  1932. "interval": "1d",
  1933. "partial": 1,
  1934. "query": query,
  1935. "referrer": "api.dashboards.widget.bar-chart",
  1936. "project": self.project.id,
  1937. "topEvents": 2,
  1938. "useOnDemandMetrics": "true",
  1939. "yAxis": "p95(transaction.duration)",
  1940. },
  1941. )
  1942. assert response.status_code == 200, response.content
  1943. assert len(response.data) == 3
  1944. data1 = response.data["1234"]
  1945. assert data1["order"] == 0
  1946. assert data1["data"][0][1][0]["count"] == 100
  1947. data2 = response.data["5678"]
  1948. assert data2["order"] == 1
  1949. assert data2["data"][0][1][0]["count"] == 200
  1950. for datum in response.data.values():
  1951. assert datum["meta"] == {
  1952. "dataset": "metricsEnhanced",
  1953. "datasetReason": "unchanged",
  1954. "fields": {},
  1955. "isMetricsData": False,
  1956. "isMetricsExtractedData": True,
  1957. "tips": {},
  1958. "units": {},
  1959. }
  1960. def test_cannot_order_by_tag(self):
  1961. url = "https://sentry.io"
  1962. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1963. self._setup_orderby_tests(query)
  1964. response = self.do_request(
  1965. data={
  1966. "dataset": "metrics",
  1967. "field": ["networkId", "count()"],
  1968. "start": iso_format(self.day_ago),
  1969. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1970. "onDemandType": "dynamic_query",
  1971. "orderby": "-networkId",
  1972. "interval": "1d",
  1973. "partial": 1,
  1974. "query": query,
  1975. "referrer": "api.dashboards.widget.bar-chart",
  1976. "project": self.project.id,
  1977. "topEvents": 2,
  1978. "useOnDemandMetrics": "true",
  1979. "yAxis": "count()",
  1980. },
  1981. )
  1982. assert response.status_code == 400, response.content
  1983. def test_order_by_two_aggregates(self):
  1984. url = "https://sentry.io"
  1985. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1986. self._setup_orderby_tests(query)
  1987. response = self.do_request(
  1988. data={
  1989. "dataset": "metrics",
  1990. "field": ["networkId", "count()", "p95(transaction.duration)"],
  1991. "start": iso_format(self.day_ago),
  1992. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1993. "onDemandType": "dynamic_query",
  1994. "orderby": ["count()", "p95(transaction.duration)"],
  1995. "interval": "1d",
  1996. "partial": 1,
  1997. "query": query,
  1998. "referrer": "api.dashboards.widget.bar-chart",
  1999. "project": self.project.id,
  2000. "topEvents": 2,
  2001. "useOnDemandMetrics": "true",
  2002. "yAxis": "p95(transaction.duration)",
  2003. },
  2004. )
  2005. assert response.status_code == 400, response.content
  2006. def test_top_events_with_tag(self):
  2007. query = "transaction.duration:>=100"
  2008. yAxis = ["count()"]
  2009. field = "count()"
  2010. groupbys = ["some-field"]
  2011. spec = OnDemandMetricSpec(
  2012. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  2013. )
  2014. self.store_on_demand_metric(
  2015. 1,
  2016. spec=spec,
  2017. additional_tags={
  2018. "some-field": "bar",
  2019. "environment": "production",
  2020. },
  2021. timestamp=self.day_ago,
  2022. )
  2023. response = self.do_request(
  2024. data={
  2025. "project": self.project.id,
  2026. "start": iso_format(self.day_ago),
  2027. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2028. "interval": "1h",
  2029. "orderby": ["-count()"],
  2030. "environment": "production",
  2031. "query": query,
  2032. "yAxis": yAxis,
  2033. "field": [
  2034. "some-field",
  2035. "count()",
  2036. ],
  2037. "topEvents": 5,
  2038. "dataset": "metrics",
  2039. "useOnDemandMetrics": "true",
  2040. },
  2041. )
  2042. assert response.status_code == 200, response.content