test_organization_events_stats_mep.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  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.models.dashboard_widget import DashboardWidget, DashboardWidgetTypes
  9. from sentry.models.environment import Environment
  10. from sentry.sentry_metrics.use_case_id_registry import UseCaseID
  11. from sentry.snuba.metrics.extraction import MetricSpecType, OnDemandMetricSpec
  12. from sentry.testutils.cases import MetricsEnhancedPerformanceTestCase
  13. from sentry.testutils.helpers.datetime import before_now, iso_format
  14. from sentry.testutils.helpers.on_demand import create_widget
  15. from sentry.testutils.silo import region_silo_test
  16. from sentry.utils.samples import load_data
  17. pytestmark = pytest.mark.sentry_metrics
  18. @region_silo_test
  19. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest(
  20. MetricsEnhancedPerformanceTestCase
  21. ):
  22. endpoint = "sentry-api-0-organization-events-stats"
  23. METRIC_STRINGS = [
  24. "foo_transaction",
  25. "d:transactions/measurements.datacenter_memory@pebibyte",
  26. ]
  27. def setUp(self):
  28. super().setUp()
  29. self.login_as(user=self.user)
  30. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  31. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  32. self.url = reverse(
  33. "sentry-api-0-organization-events-stats",
  34. kwargs={"organization_slug": self.project.organization.slug},
  35. )
  36. self.features = {
  37. "organizations:performance-use-metrics": True,
  38. }
  39. self.additional_params = dict()
  40. # These throughput tests should roughly match the ones in OrganizationEventsStatsEndpointTest
  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. @region_silo_test
  711. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithMetricLayer(
  712. OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest
  713. ):
  714. def setUp(self):
  715. super().setUp()
  716. self.features["organizations:use-metrics-layer"] = True
  717. self.additional_params = {"forceMetricsLayer": "true"}
  718. def test_counter_standard_metric(self):
  719. mri = "c:transactions/usage@none"
  720. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  721. self.store_transaction_metric(
  722. value,
  723. metric=mri,
  724. internal_metric=mri,
  725. entity="metrics_counters",
  726. timestamp=self.day_ago + timedelta(minutes=index),
  727. use_case_id=UseCaseID.CUSTOM,
  728. )
  729. response = self.do_request(
  730. data={
  731. "start": iso_format(self.day_ago),
  732. "end": iso_format(self.day_ago + timedelta(hours=6)),
  733. "interval": "1m",
  734. "yAxis": [f"sum({mri})"],
  735. "project": self.project.id,
  736. "dataset": "metricsEnhanced",
  737. **self.additional_params,
  738. },
  739. )
  740. assert response.status_code == 200, response.content
  741. data = response.data["data"]
  742. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  743. assert value[0]["count"] == expected_value # type:ignore
  744. def test_counter_custom_metric(self):
  745. mri = "c:custom/sentry.process_profile.track_outcome@second"
  746. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  747. self.store_transaction_metric(
  748. value,
  749. metric=mri,
  750. internal_metric=mri,
  751. entity="metrics_counters",
  752. timestamp=self.day_ago + timedelta(hours=index),
  753. use_case_id=UseCaseID.CUSTOM,
  754. )
  755. response = self.do_request(
  756. data={
  757. "start": iso_format(self.day_ago),
  758. "end": iso_format(self.day_ago + timedelta(hours=6)),
  759. "interval": "1h",
  760. "yAxis": [f"sum({mri})"],
  761. "project": self.project.id,
  762. "dataset": "metricsEnhanced",
  763. **self.additional_params,
  764. },
  765. )
  766. assert response.status_code == 200, response.content
  767. data = response.data["data"]
  768. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  769. assert value[0]["count"] == expected_value # type:ignore
  770. def test_distribution_custom_metric(self):
  771. mri = "d:custom/sentry.process_profile.track_outcome@second"
  772. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  773. for multiplier in (1, 2, 3):
  774. self.store_transaction_metric(
  775. value * multiplier,
  776. metric=mri,
  777. internal_metric=mri,
  778. entity="metrics_distributions",
  779. timestamp=self.day_ago + timedelta(hours=index),
  780. use_case_id=UseCaseID.CUSTOM,
  781. )
  782. response = self.do_request(
  783. data={
  784. "start": iso_format(self.day_ago),
  785. "end": iso_format(self.day_ago + timedelta(hours=6)),
  786. "interval": "1h",
  787. "yAxis": [f"min({mri})", f"max({mri})", f"p90({mri})"],
  788. "project": self.project.id,
  789. "dataset": "metricsEnhanced",
  790. **self.additional_params,
  791. },
  792. )
  793. assert response.status_code == 200, response.content
  794. data = response.data
  795. min = data[f"min({mri})"]["data"]
  796. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  797. assert value[0]["count"] == expected_value # type:ignore
  798. max = data[f"max({mri})"]["data"]
  799. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  800. assert value[0]["count"] == expected_value # type:ignore
  801. p90 = data[f"p90({mri})"]["data"]
  802. for (_, value), expected_value in zip(p90, [28.0, 56.0, 84.0, 112.0, 140.0, 168.0]):
  803. assert value[0]["count"] == expected_value # type:ignore
  804. def test_set_custom_metric(self):
  805. mri = "s:custom/sentry.process_profile.track_outcome@second"
  806. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  807. # We store each value a second time, since we want to check the de-duplication of sets.
  808. for i in range(0, 2):
  809. self.store_transaction_metric(
  810. value,
  811. metric=mri,
  812. internal_metric=mri,
  813. entity="metrics_sets",
  814. timestamp=self.day_ago + timedelta(hours=index),
  815. use_case_id=UseCaseID.CUSTOM,
  816. )
  817. response = self.do_request(
  818. data={
  819. "start": iso_format(self.day_ago),
  820. "end": iso_format(self.day_ago + timedelta(hours=6)),
  821. "interval": "1h",
  822. "yAxis": [f"count_unique({mri})"],
  823. "project": self.project.id,
  824. "dataset": "metricsEnhanced",
  825. **self.additional_params,
  826. },
  827. )
  828. assert response.status_code == 200, response.content
  829. data = response.data["data"]
  830. for (_, value), expected_value in zip(data, [1, 1, 1, 1, 1, 1]):
  831. assert value[0]["count"] == expected_value # type:ignore
  832. def test_gauge_custom_metric(self):
  833. mri = "g:custom/sentry.process_profile.track_outcome@second"
  834. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  835. for multiplier in (1, 3):
  836. self.store_transaction_metric(
  837. value * multiplier,
  838. metric=mri,
  839. internal_metric=mri,
  840. entity="metrics_gauges",
  841. # When multiple gauges are merged, in order to make the `last` merge work deterministically it's
  842. # better to have the gauges with different timestamps so that the last value is always the same.
  843. timestamp=self.day_ago + timedelta(hours=index, minutes=multiplier),
  844. use_case_id=UseCaseID.CUSTOM,
  845. )
  846. response = self.do_request(
  847. data={
  848. "start": iso_format(self.day_ago),
  849. "end": iso_format(self.day_ago + timedelta(hours=6)),
  850. "interval": "1h",
  851. "yAxis": [
  852. f"min({mri})",
  853. f"max({mri})",
  854. f"last({mri})",
  855. f"sum({mri})",
  856. f"count({mri})",
  857. ],
  858. "project": self.project.id,
  859. "dataset": "metricsEnhanced",
  860. **self.additional_params,
  861. },
  862. )
  863. assert response.status_code == 200, response.content
  864. data = response.data
  865. min = data[f"min({mri})"]["data"]
  866. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  867. assert value[0]["count"] == expected_value # type:ignore
  868. max = data[f"max({mri})"]["data"]
  869. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  870. assert value[0]["count"] == expected_value # type:ignore
  871. last = data[f"last({mri})"]["data"]
  872. for (_, value), expected_value in zip(last, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  873. assert value[0]["count"] == expected_value # type:ignore
  874. sum = data[f"sum({mri})"]["data"]
  875. for (_, value), expected_value in zip(sum, [40.0, 80.0, 120.0, 160.0, 200.0, 240.0]):
  876. assert value[0]["count"] == expected_value # type:ignore
  877. count = data[f"count({mri})"]["data"]
  878. for (_, value), expected_value in zip(count, [40, 80, 120, 160, 200, 240]):
  879. assert value[0]["count"] == expected_value # type:ignore
  880. @region_silo_test
  881. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithOnDemandWidgets(
  882. MetricsEnhancedPerformanceTestCase
  883. ):
  884. endpoint = "sentry-api-0-organization-events-stats"
  885. def setUp(self):
  886. super().setUp()
  887. self.login_as(user=self.user)
  888. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  889. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  890. Environment.get_or_create(self.project, "production")
  891. self.url = reverse(
  892. "sentry-api-0-organization-events-stats",
  893. kwargs={"organization_slug": self.project.organization.slug},
  894. )
  895. self.features = {
  896. "organizations:on-demand-metrics-extraction-widgets": True,
  897. "organizations:on-demand-metrics-extraction": True,
  898. }
  899. def _make_on_demand_request(
  900. self, params: dict[str, Any], extra_features: dict[str, bool] | None = None
  901. ) -> Response:
  902. """Ensures that the required parameters for an on-demand request are included."""
  903. # Expected parameters for this helper function
  904. params["dataset"] = "metricsEnhanced"
  905. params["useOnDemandMetrics"] = "true"
  906. params["onDemandType"] = "dynamic_query"
  907. _features = {**self.features, **(extra_features or {})}
  908. return self.do_request(params, features=_features)
  909. def test_top_events_wrong_on_demand_type(self):
  910. query = "transaction.duration:>=100"
  911. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  912. response = self.do_request(
  913. data={
  914. "project": self.project.id,
  915. "start": iso_format(self.day_ago),
  916. "end": iso_format(self.day_ago + timedelta(hours=2)),
  917. "interval": "1h",
  918. "orderby": ["-count()"],
  919. "environment": "production",
  920. "query": query,
  921. "yAxis": yAxis,
  922. "field": [
  923. "count()",
  924. ],
  925. "topEvents": 5,
  926. "dataset": "metrics",
  927. "useOnDemandMetrics": "true",
  928. "onDemandType": "not_real",
  929. },
  930. )
  931. assert response.status_code == 400, response.content
  932. def test_top_events_works_without_on_demand_type(self):
  933. query = "transaction.duration:>=100"
  934. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  935. response = self.do_request(
  936. data={
  937. "project": self.project.id,
  938. "start": iso_format(self.day_ago),
  939. "end": iso_format(self.day_ago + timedelta(hours=2)),
  940. "interval": "1h",
  941. "orderby": ["-count()"],
  942. "environment": "production",
  943. "query": query,
  944. "yAxis": yAxis,
  945. "field": [
  946. "count()",
  947. ],
  948. "topEvents": 5,
  949. "dataset": "metrics",
  950. "useOnDemandMetrics": "true",
  951. },
  952. )
  953. assert response.status_code == 200, response.content
  954. def test_top_events_with_transaction_on_demand(self):
  955. field = "count()"
  956. field_two = "count_web_vitals(measurements.lcp, good)"
  957. groupbys = ["customtag1", "customtag2"]
  958. query = "transaction.duration:>=100"
  959. spec = OnDemandMetricSpec(
  960. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  961. )
  962. spec_two = OnDemandMetricSpec(
  963. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  964. )
  965. for hour in range(0, 5):
  966. self.store_on_demand_metric(
  967. hour * 62 * 24,
  968. spec=spec,
  969. additional_tags={
  970. "customtag1": "foo",
  971. "customtag2": "red",
  972. "environment": "production",
  973. },
  974. timestamp=self.day_ago + timedelta(hours=hour),
  975. )
  976. self.store_on_demand_metric(
  977. hour * 60 * 24,
  978. spec=spec_two,
  979. additional_tags={
  980. "customtag1": "bar",
  981. "customtag2": "blue",
  982. "environment": "production",
  983. },
  984. timestamp=self.day_ago + timedelta(hours=hour),
  985. )
  986. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  987. response = self.do_request(
  988. data={
  989. "project": self.project.id,
  990. "start": iso_format(self.day_ago),
  991. "end": iso_format(self.day_ago + timedelta(hours=2)),
  992. "interval": "1h",
  993. "orderby": ["-count()"],
  994. "environment": "production",
  995. "query": query,
  996. "yAxis": yAxis,
  997. "field": [
  998. "count()",
  999. "count_web_vitals(measurements.lcp, good)",
  1000. "customtag1",
  1001. "customtag2",
  1002. ],
  1003. "topEvents": 5,
  1004. "dataset": "metricsEnhanced",
  1005. "useOnDemandMetrics": "true",
  1006. "onDemandType": "dynamic_query",
  1007. },
  1008. )
  1009. assert response.status_code == 200, response.content
  1010. groups = [
  1011. ("foo,red", "count()", 0.0, 1488.0),
  1012. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1013. ("bar,blue", "count()", 0.0, 0.0),
  1014. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1015. ]
  1016. assert len(response.data.keys()) == 2
  1017. for group_count in groups:
  1018. group, agg, row1, row2 = group_count
  1019. row_data = response.data[group][agg]["data"][:2]
  1020. assert [attrs for _, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1021. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1022. assert response.data[group]["isMetricsExtractedData"]
  1023. def test_top_events_with_transaction_on_demand_and_no_environment(self):
  1024. field = "count()"
  1025. field_two = "count_web_vitals(measurements.lcp, good)"
  1026. groupbys = ["customtag1", "customtag2"]
  1027. query = "transaction.duration:>=100"
  1028. spec = OnDemandMetricSpec(
  1029. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1030. )
  1031. spec_two = OnDemandMetricSpec(
  1032. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1033. )
  1034. for hour in range(0, 5):
  1035. self.store_on_demand_metric(
  1036. hour * 62 * 24,
  1037. spec=spec,
  1038. additional_tags={
  1039. "customtag1": "foo",
  1040. "customtag2": "red",
  1041. "environment": "production",
  1042. },
  1043. timestamp=self.day_ago + timedelta(hours=hour),
  1044. )
  1045. self.store_on_demand_metric(
  1046. hour * 60 * 24,
  1047. spec=spec_two,
  1048. additional_tags={
  1049. "customtag1": "bar",
  1050. "customtag2": "blue",
  1051. "environment": "production",
  1052. },
  1053. timestamp=self.day_ago + timedelta(hours=hour),
  1054. )
  1055. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1056. response = self.do_request(
  1057. data={
  1058. "project": self.project.id,
  1059. "start": iso_format(self.day_ago),
  1060. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1061. "interval": "1h",
  1062. "orderby": ["-count()"],
  1063. "query": query,
  1064. "yAxis": yAxis,
  1065. "field": [
  1066. "count()",
  1067. "count_web_vitals(measurements.lcp, good)",
  1068. "customtag1",
  1069. "customtag2",
  1070. ],
  1071. "topEvents": 5,
  1072. "dataset": "metricsEnhanced",
  1073. "useOnDemandMetrics": "true",
  1074. "onDemandType": "dynamic_query",
  1075. },
  1076. )
  1077. assert response.status_code == 200, response.content
  1078. groups = [
  1079. ("foo,red", "count()", 0.0, 1488.0),
  1080. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1081. ("bar,blue", "count()", 0.0, 0.0),
  1082. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1083. ]
  1084. assert len(response.data.keys()) == 2
  1085. for group_count in groups:
  1086. group, agg, row1, row2 = group_count
  1087. row_data = response.data[group][agg]["data"][:2]
  1088. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1089. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1090. assert response.data[group]["isMetricsExtractedData"]
  1091. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_transaction_only(self):
  1092. field = "count()"
  1093. field_two = "count_web_vitals(measurements.lcp, good)"
  1094. groupbys = ["customtag1", "customtag2"]
  1095. query = "transaction.duration:>=100"
  1096. spec = OnDemandMetricSpec(
  1097. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1098. )
  1099. spec_two = OnDemandMetricSpec(
  1100. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1101. )
  1102. _, widget, __ = create_widget(
  1103. ["count()"],
  1104. "",
  1105. self.project,
  1106. discover_widget_split=None,
  1107. )
  1108. for hour in range(0, 2):
  1109. self.store_on_demand_metric(
  1110. hour * 62 * 24,
  1111. spec=spec,
  1112. additional_tags={
  1113. "customtag1": "foo",
  1114. "customtag2": "red",
  1115. "environment": "production",
  1116. },
  1117. timestamp=self.day_ago + timedelta(hours=hour),
  1118. )
  1119. self.store_on_demand_metric(
  1120. hour * 60 * 24,
  1121. spec=spec_two,
  1122. additional_tags={
  1123. "customtag1": "bar",
  1124. "customtag2": "blue",
  1125. "environment": "production",
  1126. },
  1127. timestamp=self.day_ago + timedelta(hours=hour),
  1128. )
  1129. yAxis = [field, field_two]
  1130. response = self.do_request(
  1131. data={
  1132. "project": self.project.id,
  1133. "start": iso_format(self.day_ago),
  1134. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1135. "interval": "1h",
  1136. "orderby": ["-count()"],
  1137. "query": query,
  1138. "yAxis": yAxis,
  1139. "field": yAxis + groupbys,
  1140. "topEvents": 5,
  1141. "dataset": "metricsEnhanced",
  1142. "useOnDemandMetrics": "true",
  1143. "onDemandType": "dynamic_query",
  1144. "dashboardWidgetId": widget.id,
  1145. },
  1146. )
  1147. saved_widget = DashboardWidget.objects.get(id=widget.id)
  1148. assert saved_widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE
  1149. assert response.status_code == 200, response.content
  1150. # Fell back to discover data which is empty for this test (empty group of '').
  1151. assert len(response.data.keys()) == 2
  1152. assert bool(response.data["foo,red"])
  1153. assert bool(response.data["bar,blue"])
  1154. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_error(
  1155. self,
  1156. ):
  1157. field = "count()"
  1158. field_two = "count()"
  1159. groupbys = ["customtag1", "customtag2"]
  1160. query = "query.dataset:foo"
  1161. _, widget, __ = create_widget(
  1162. ["count()"],
  1163. "",
  1164. self.project,
  1165. discover_widget_split=None,
  1166. )
  1167. self.store_event(
  1168. data={
  1169. "event_id": "a" * 32,
  1170. "message": "very bad",
  1171. "type": "error",
  1172. "start_timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1173. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1174. "tags": {"customtag1": "error_value", "query.dataset": "foo"},
  1175. },
  1176. project_id=self.project.id,
  1177. )
  1178. self.store_event(
  1179. data={
  1180. "event_id": "b" * 32,
  1181. "message": "very bad 2",
  1182. "type": "error",
  1183. "start_timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1184. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1185. "tags": {"customtag1": "error_value2", "query.dataset": "foo"},
  1186. },
  1187. project_id=self.project.id,
  1188. )
  1189. yAxis = ["count()"]
  1190. response = self.do_request(
  1191. data={
  1192. "project": self.project.id,
  1193. "start": iso_format(self.day_ago),
  1194. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1195. "interval": "1h",
  1196. "orderby": ["-count()"],
  1197. "query": query,
  1198. "yAxis": yAxis,
  1199. "field": [field, field_two] + groupbys,
  1200. "topEvents": 5,
  1201. "dataset": "metricsEnhanced",
  1202. "useOnDemandMetrics": "true",
  1203. "onDemandType": "dynamic_query",
  1204. "dashboardWidgetId": widget.id,
  1205. },
  1206. )
  1207. saved_widget = DashboardWidget.objects.get(id=widget.id)
  1208. assert saved_widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
  1209. assert response.status_code == 200, response.content
  1210. # Fell back to discover data which is empty for this test (empty group of '').
  1211. assert len(response.data.keys()) == 2
  1212. assert bool(response.data["error_value,"])
  1213. assert bool(response.data["error_value2,"])
  1214. def test_top_events_with_transaction_on_demand_passing_widget_id_unsaved_discover(self):
  1215. field = "count()"
  1216. field_two = "count()"
  1217. groupbys = ["customtag1", "customtag2"]
  1218. query = "query.dataset:foo"
  1219. spec = OnDemandMetricSpec(
  1220. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1221. )
  1222. spec_two = OnDemandMetricSpec(
  1223. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1224. )
  1225. _, widget, __ = create_widget(
  1226. ["count()"],
  1227. "",
  1228. self.project,
  1229. discover_widget_split=None,
  1230. )
  1231. self.store_event(
  1232. data={
  1233. "event_id": "a" * 32,
  1234. "message": "very bad",
  1235. "type": "error",
  1236. "timestamp": iso_format(self.day_ago + timedelta(hours=1)),
  1237. "tags": {"customtag1": "error_value", "query.dataset": "foo"},
  1238. },
  1239. project_id=self.project.id,
  1240. )
  1241. transaction = load_data("transaction")
  1242. transaction["timestamp"] = iso_format(self.day_ago + timedelta(hours=1))
  1243. transaction["start_timestamp"] = iso_format(self.day_ago + timedelta(hours=1))
  1244. transaction["tags"] = {"customtag1": "transaction_value", "query.dataset": "foo"}
  1245. self.store_event(
  1246. data=transaction,
  1247. project_id=self.project.id,
  1248. )
  1249. for hour in range(0, 5):
  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 = ["count()"]
  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": [field, field_two, "customtag1", "customtag2"],
  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.DISCOVER
  1290. assert response.status_code == 200, response.content
  1291. assert response.status_code == 200, response.content
  1292. # Fell back to discover data which is empty for this test (empty group of '').
  1293. assert len(response.data.keys()) == 2
  1294. assert bool(response.data["error_value,"])
  1295. assert bool(response.data["transaction_value,"])
  1296. def test_top_events_with_transaction_on_demand_passing_widget_id_saved(self):
  1297. field = "count()"
  1298. field_two = "count_web_vitals(measurements.lcp, good)"
  1299. groupbys = ["customtag1", "customtag2"]
  1300. query = "transaction.duration:>=100"
  1301. spec = OnDemandMetricSpec(
  1302. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1303. )
  1304. spec_two = OnDemandMetricSpec(
  1305. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1306. )
  1307. _, widget, __ = create_widget(
  1308. ["count()"],
  1309. "",
  1310. self.project,
  1311. discover_widget_split=DashboardWidgetTypes.TRANSACTION_LIKE, # Transactions like uses on-demand
  1312. )
  1313. for hour in range(0, 5):
  1314. self.store_on_demand_metric(
  1315. hour * 62 * 24,
  1316. spec=spec,
  1317. additional_tags={
  1318. "customtag1": "foo",
  1319. "customtag2": "red",
  1320. "environment": "production",
  1321. },
  1322. timestamp=self.day_ago + timedelta(hours=hour),
  1323. )
  1324. self.store_on_demand_metric(
  1325. hour * 60 * 24,
  1326. spec=spec_two,
  1327. additional_tags={
  1328. "customtag1": "bar",
  1329. "customtag2": "blue",
  1330. "environment": "production",
  1331. },
  1332. timestamp=self.day_ago + timedelta(hours=hour),
  1333. )
  1334. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1335. with mock.patch.object(widget, "save") as mock_widget_save:
  1336. response = self.do_request(
  1337. data={
  1338. "project": self.project.id,
  1339. "start": iso_format(self.day_ago),
  1340. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1341. "interval": "1h",
  1342. "orderby": ["-count()"],
  1343. "query": query,
  1344. "yAxis": yAxis,
  1345. "field": [
  1346. "count()",
  1347. "count_web_vitals(measurements.lcp, good)",
  1348. "customtag1",
  1349. "customtag2",
  1350. ],
  1351. "topEvents": 5,
  1352. "dataset": "metricsEnhanced",
  1353. "useOnDemandMetrics": "true",
  1354. "onDemandType": "dynamic_query",
  1355. "dashboardWidgetId": widget.id,
  1356. },
  1357. )
  1358. assert bool(mock_widget_save.assert_not_called)
  1359. assert response.status_code == 200, response.content
  1360. groups = [
  1361. ("foo,red", "count()", 0.0, 1488.0),
  1362. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1363. ("bar,blue", "count()", 0.0, 0.0),
  1364. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1365. ]
  1366. assert len(response.data.keys()) == 2
  1367. for group_count in groups:
  1368. group, agg, row1, row2 = group_count
  1369. row_data = response.data[group][agg]["data"][:2]
  1370. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1371. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1372. assert response.data[group]["isMetricsExtractedData"]
  1373. def test_timeseries_on_demand_with_multiple_percentiles(self):
  1374. field = "p75(measurements.fcp)"
  1375. field_two = "p75(measurements.lcp)"
  1376. query = "transaction.duration:>=100"
  1377. spec = OnDemandMetricSpec(field=field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY)
  1378. spec_two = OnDemandMetricSpec(
  1379. field=field_two, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1380. )
  1381. assert (
  1382. spec._query_str_for_hash
  1383. == "event.measurements.fcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1384. )
  1385. assert (
  1386. spec_two._query_str_for_hash
  1387. == "event.measurements.lcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1388. )
  1389. for count in range(0, 4):
  1390. self.store_on_demand_metric(
  1391. count * 100,
  1392. spec=spec,
  1393. timestamp=self.day_ago + timedelta(hours=1),
  1394. )
  1395. self.store_on_demand_metric(
  1396. count * 200.0,
  1397. spec=spec_two,
  1398. timestamp=self.day_ago + timedelta(hours=1),
  1399. )
  1400. yAxis = [field, field_two]
  1401. response = self.do_request(
  1402. data={
  1403. "project": self.project.id,
  1404. "start": iso_format(self.day_ago),
  1405. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1406. "interval": "1h",
  1407. "orderby": [field],
  1408. "query": query,
  1409. "yAxis": yAxis,
  1410. "dataset": "metricsEnhanced",
  1411. "useOnDemandMetrics": "true",
  1412. "onDemandType": "dynamic_query",
  1413. },
  1414. )
  1415. assert response.status_code == 200, response.content
  1416. assert response.data["p75(measurements.fcp)"]["meta"]["isMetricsExtractedData"]
  1417. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1418. assert [attrs for time, attrs in response.data["p75(measurements.fcp)"]["data"]] == [
  1419. [{"count": 0}],
  1420. [{"count": 225.0}],
  1421. ]
  1422. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsExtractedData"]
  1423. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1424. assert [attrs for time, attrs in response.data["p75(measurements.lcp)"]["data"]] == [
  1425. [{"count": 0}],
  1426. [{"count": 450.0}],
  1427. ]
  1428. def test_apdex_issue(self):
  1429. field = "apdex(300)"
  1430. groupbys = ["group_tag"]
  1431. query = "transaction.duration:>=100"
  1432. spec = OnDemandMetricSpec(
  1433. field=field,
  1434. groupbys=groupbys,
  1435. query=query,
  1436. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1437. )
  1438. for hour in range(0, 5):
  1439. self.store_on_demand_metric(
  1440. 1,
  1441. spec=spec,
  1442. additional_tags={
  1443. "group_tag": "group_one",
  1444. "environment": "production",
  1445. "satisfaction": "tolerable",
  1446. },
  1447. timestamp=self.day_ago + timedelta(hours=hour),
  1448. )
  1449. self.store_on_demand_metric(
  1450. 1,
  1451. spec=spec,
  1452. additional_tags={
  1453. "group_tag": "group_two",
  1454. "environment": "production",
  1455. "satisfaction": "satisfactory",
  1456. },
  1457. timestamp=self.day_ago + timedelta(hours=hour),
  1458. )
  1459. response = self.do_request(
  1460. data={
  1461. "dataset": "metricsEnhanced",
  1462. "environment": "production",
  1463. "excludeOther": 1,
  1464. "field": [field, "group_tag"],
  1465. "start": iso_format(self.day_ago),
  1466. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1467. "interval": "1h",
  1468. "orderby": f"-{field}",
  1469. "partial": 1,
  1470. "project": self.project.id,
  1471. "query": query,
  1472. "topEvents": 5,
  1473. "yAxis": field,
  1474. "onDemandType": "dynamic_query",
  1475. "useOnDemandMetrics": "true",
  1476. },
  1477. )
  1478. assert response.status_code == 200, response.content
  1479. assert response.data["group_one"]["meta"]["isMetricsExtractedData"] is True
  1480. assert [attrs for time, attrs in response.data["group_one"]["data"]] == [
  1481. [{"count": 0.5}],
  1482. [{"count": 0.5}],
  1483. ]
  1484. def test_glob_http_referer_on_demand(self):
  1485. agg = "count()"
  1486. network_id_tag = "networkId"
  1487. url = "https://sentry.io"
  1488. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1489. spec = OnDemandMetricSpec(
  1490. field=agg,
  1491. groupbys=[network_id_tag],
  1492. query=query,
  1493. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1494. )
  1495. assert spec.to_metric_spec(self.project) == {
  1496. "category": "transaction",
  1497. "mri": "c:transactions/on_demand@none",
  1498. "field": None,
  1499. "tags": [
  1500. {"key": "query_hash", "value": "ac241f56"},
  1501. {"key": "networkId", "field": "event.tags.networkId"},
  1502. {"key": "environment", "field": "event.environment"},
  1503. ],
  1504. "condition": {
  1505. "op": "and",
  1506. "inner": [
  1507. {
  1508. "op": "glob",
  1509. "name": "event.request.url",
  1510. "value": ["https://sentry.io/*/foo/bar/*"],
  1511. },
  1512. {
  1513. "op": "glob",
  1514. "name": "event.request.headers.Referer",
  1515. "value": ["https://sentry.io/*/bar/*"],
  1516. },
  1517. ],
  1518. },
  1519. }
  1520. for hour in range(0, 5):
  1521. self.store_on_demand_metric(
  1522. 1,
  1523. spec=spec,
  1524. additional_tags={network_id_tag: "1234"},
  1525. timestamp=self.day_ago + timedelta(hours=hour),
  1526. )
  1527. self.store_on_demand_metric(
  1528. 1,
  1529. spec=spec,
  1530. additional_tags={network_id_tag: "5678"},
  1531. timestamp=self.day_ago + timedelta(hours=hour),
  1532. )
  1533. response = self.do_request(
  1534. data={
  1535. "dataset": "metricsEnhanced",
  1536. "field": [network_id_tag, agg],
  1537. "start": iso_format(self.day_ago),
  1538. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1539. "onDemandType": "dynamic_query",
  1540. "orderby": f"-{agg}",
  1541. "interval": "1d",
  1542. "partial": 1,
  1543. "query": query,
  1544. "referrer": "api.dashboards.widget.bar-chart",
  1545. "project": self.project.id,
  1546. "topEvents": 2,
  1547. "useOnDemandMetrics": "true",
  1548. "yAxis": agg,
  1549. },
  1550. )
  1551. assert response.status_code == 200, response.content
  1552. for datum in response.data.values():
  1553. assert datum["meta"] == {
  1554. "dataset": "metricsEnhanced",
  1555. "datasetReason": "unchanged",
  1556. "fields": {},
  1557. "isMetricsData": False,
  1558. "isMetricsExtractedData": True,
  1559. "tips": {},
  1560. "units": {},
  1561. }
  1562. def _test_is_metrics_extracted_data(
  1563. self, params: dict[str, Any], expected_on_demand_query: bool, dataset: str
  1564. ) -> None:
  1565. spec = OnDemandMetricSpec(
  1566. field="count()",
  1567. query="transaction.duration:>1s",
  1568. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1569. )
  1570. self.store_on_demand_metric(1, spec=spec)
  1571. response = self.do_request(params)
  1572. assert response.status_code == 200, response.content
  1573. meta = response.data["meta"]
  1574. # This is the main thing we want to test for
  1575. assert meta.get("isMetricsExtractedData", False) is expected_on_demand_query
  1576. assert meta["dataset"] == dataset
  1577. return meta
  1578. def test_is_metrics_extracted_data_is_included(self):
  1579. self._test_is_metrics_extracted_data(
  1580. {
  1581. "dataset": "metricsEnhanced",
  1582. "query": "transaction.duration:>=91",
  1583. "useOnDemandMetrics": "true",
  1584. "yAxis": "count()",
  1585. },
  1586. expected_on_demand_query=True,
  1587. dataset="metricsEnhanced",
  1588. )
  1589. def test_on_demand_epm_no_query(self):
  1590. params = {
  1591. "dataset": "metricsEnhanced",
  1592. "environment": "production",
  1593. "onDemandType": "dynamic_query",
  1594. "project": self.project.id,
  1595. "query": "",
  1596. "statsPeriod": "1h",
  1597. "useOnDemandMetrics": "true",
  1598. "yAxis": ["epm()"],
  1599. }
  1600. response = self.do_request(params)
  1601. assert response.status_code == 200, response.content
  1602. assert response.data["meta"] == {
  1603. "fields": {"time": "date", "epm_900": "rate"},
  1604. "units": {"time": None, "epm_900": None},
  1605. "isMetricsData": True,
  1606. "isMetricsExtractedData": False,
  1607. "tips": {},
  1608. "datasetReason": "unchanged",
  1609. "dataset": "metricsEnhanced",
  1610. }
  1611. def test_group_by_transaction(self):
  1612. field = "count()"
  1613. groupbys = ["transaction"]
  1614. query = "transaction.duration:>=100"
  1615. spec = OnDemandMetricSpec(
  1616. field=field,
  1617. groupbys=groupbys,
  1618. query=query,
  1619. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1620. )
  1621. for hour in range(0, 2):
  1622. self.store_on_demand_metric(
  1623. (hour + 1) * 5,
  1624. spec=spec,
  1625. additional_tags={
  1626. "transaction": "/performance",
  1627. "environment": "production",
  1628. },
  1629. timestamp=self.day_ago + timedelta(hours=hour),
  1630. )
  1631. response = self.do_request(
  1632. data={
  1633. "dataset": "metricsEnhanced",
  1634. "environment": "production",
  1635. "excludeOther": 1,
  1636. "field": [field, "transaction"],
  1637. "start": iso_format(self.day_ago),
  1638. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1639. "interval": "1h",
  1640. "orderby": f"-{field}",
  1641. "partial": 1,
  1642. "project": self.project.id,
  1643. "query": query,
  1644. "topEvents": 5,
  1645. "yAxis": field,
  1646. "onDemandType": "dynamic_query",
  1647. "useOnDemandMetrics": "true",
  1648. },
  1649. )
  1650. assert response.status_code == 200, response.content
  1651. assert response.data["/performance"]["meta"]["isMetricsExtractedData"] is True
  1652. assert [attrs for time, attrs in response.data["/performance"]["data"]] == [
  1653. [{"count": 5.0}],
  1654. [{"count": 10.0}],
  1655. ]
  1656. def _setup_orderby_tests(self, query):
  1657. count_spec = OnDemandMetricSpec(
  1658. field="count()",
  1659. groupbys=["networkId"],
  1660. query=query,
  1661. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1662. )
  1663. p95_spec = OnDemandMetricSpec(
  1664. field="p95(transaction.duration)",
  1665. groupbys=["networkId"],
  1666. query=query,
  1667. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1668. )
  1669. for hour in range(0, 5):
  1670. self.store_on_demand_metric(
  1671. 1,
  1672. spec=count_spec,
  1673. additional_tags={"networkId": "1234"},
  1674. timestamp=self.day_ago + timedelta(hours=hour),
  1675. )
  1676. self.store_on_demand_metric(
  1677. 100,
  1678. spec=p95_spec,
  1679. additional_tags={"networkId": "1234"},
  1680. timestamp=self.day_ago + timedelta(hours=hour),
  1681. )
  1682. self.store_on_demand_metric(
  1683. 200,
  1684. spec=p95_spec,
  1685. additional_tags={"networkId": "5678"},
  1686. timestamp=self.day_ago + timedelta(hours=hour),
  1687. )
  1688. # Store twice as many 5678 so orderby puts it later
  1689. self.store_on_demand_metric(
  1690. 2,
  1691. spec=count_spec,
  1692. additional_tags={"networkId": "5678"},
  1693. timestamp=self.day_ago + timedelta(hours=hour),
  1694. )
  1695. def test_order_by_aggregate_top_events_desc(self):
  1696. url = "https://sentry.io"
  1697. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1698. self._setup_orderby_tests(query)
  1699. response = self.do_request(
  1700. data={
  1701. "dataset": "metricsEnhanced",
  1702. "field": ["networkId", "count()"],
  1703. "start": iso_format(self.day_ago),
  1704. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1705. "onDemandType": "dynamic_query",
  1706. "orderby": "-count()",
  1707. "interval": "1d",
  1708. "partial": 1,
  1709. "query": query,
  1710. "referrer": "api.dashboards.widget.bar-chart",
  1711. "project": self.project.id,
  1712. "topEvents": 2,
  1713. "useOnDemandMetrics": "true",
  1714. "yAxis": "count()",
  1715. },
  1716. )
  1717. assert response.status_code == 200, response.content
  1718. assert len(response.data) == 3
  1719. data1 = response.data["5678"]
  1720. assert data1["order"] == 0
  1721. assert data1["data"][0][1][0]["count"] == 10
  1722. data2 = response.data["1234"]
  1723. assert data2["order"] == 1
  1724. assert data2["data"][0][1][0]["count"] == 5
  1725. for datum in response.data.values():
  1726. assert datum["meta"] == {
  1727. "dataset": "metricsEnhanced",
  1728. "datasetReason": "unchanged",
  1729. "fields": {},
  1730. "isMetricsData": False,
  1731. "isMetricsExtractedData": True,
  1732. "tips": {},
  1733. "units": {},
  1734. }
  1735. def test_order_by_aggregate_top_events_asc(self):
  1736. url = "https://sentry.io"
  1737. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1738. self._setup_orderby_tests(query)
  1739. response = self.do_request(
  1740. data={
  1741. "dataset": "metricsEnhanced",
  1742. "field": ["networkId", "count()"],
  1743. "start": iso_format(self.day_ago),
  1744. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1745. "onDemandType": "dynamic_query",
  1746. "orderby": "count()",
  1747. "interval": "1d",
  1748. "partial": 1,
  1749. "query": query,
  1750. "referrer": "api.dashboards.widget.bar-chart",
  1751. "project": self.project.id,
  1752. "topEvents": 2,
  1753. "useOnDemandMetrics": "true",
  1754. "yAxis": "count()",
  1755. },
  1756. )
  1757. assert response.status_code == 200, response.content
  1758. assert len(response.data) == 3
  1759. data1 = response.data["1234"]
  1760. assert data1["order"] == 0
  1761. assert data1["data"][0][1][0]["count"] == 5
  1762. data2 = response.data["5678"]
  1763. assert data2["order"] == 1
  1764. assert data2["data"][0][1][0]["count"] == 10
  1765. for datum in response.data.values():
  1766. assert datum["meta"] == {
  1767. "dataset": "metricsEnhanced",
  1768. "datasetReason": "unchanged",
  1769. "fields": {},
  1770. "isMetricsData": False,
  1771. "isMetricsExtractedData": True,
  1772. "tips": {},
  1773. "units": {},
  1774. }
  1775. def test_order_by_aggregate_top_events_graph_different_aggregate(self):
  1776. url = "https://sentry.io"
  1777. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1778. self._setup_orderby_tests(query)
  1779. response = self.do_request(
  1780. data={
  1781. "dataset": "metricsEnhanced",
  1782. "field": ["networkId", "count()"],
  1783. "start": iso_format(self.day_ago),
  1784. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1785. "onDemandType": "dynamic_query",
  1786. "orderby": "count()",
  1787. "interval": "1d",
  1788. "partial": 1,
  1789. "query": query,
  1790. "referrer": "api.dashboards.widget.bar-chart",
  1791. "project": self.project.id,
  1792. "topEvents": 2,
  1793. "useOnDemandMetrics": "true",
  1794. "yAxis": "p95(transaction.duration)",
  1795. },
  1796. )
  1797. assert response.status_code == 200, response.content
  1798. assert len(response.data) == 3
  1799. data1 = response.data["1234"]
  1800. assert data1["order"] == 0
  1801. assert data1["data"][0][1][0]["count"] == 100
  1802. data2 = response.data["5678"]
  1803. assert data2["order"] == 1
  1804. assert data2["data"][0][1][0]["count"] == 200
  1805. for datum in response.data.values():
  1806. assert datum["meta"] == {
  1807. "dataset": "metricsEnhanced",
  1808. "datasetReason": "unchanged",
  1809. "fields": {},
  1810. "isMetricsData": False,
  1811. "isMetricsExtractedData": True,
  1812. "tips": {},
  1813. "units": {},
  1814. }
  1815. def test_cannot_order_by_tag(self):
  1816. url = "https://sentry.io"
  1817. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1818. self._setup_orderby_tests(query)
  1819. response = self.do_request(
  1820. data={
  1821. "dataset": "metrics",
  1822. "field": ["networkId", "count()"],
  1823. "start": iso_format(self.day_ago),
  1824. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1825. "onDemandType": "dynamic_query",
  1826. "orderby": "-networkId",
  1827. "interval": "1d",
  1828. "partial": 1,
  1829. "query": query,
  1830. "referrer": "api.dashboards.widget.bar-chart",
  1831. "project": self.project.id,
  1832. "topEvents": 2,
  1833. "useOnDemandMetrics": "true",
  1834. "yAxis": "count()",
  1835. },
  1836. )
  1837. assert response.status_code == 400, response.content
  1838. def test_order_by_two_aggregates(self):
  1839. url = "https://sentry.io"
  1840. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1841. self._setup_orderby_tests(query)
  1842. response = self.do_request(
  1843. data={
  1844. "dataset": "metrics",
  1845. "field": ["networkId", "count()", "p95(transaction.duration)"],
  1846. "start": iso_format(self.day_ago),
  1847. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1848. "onDemandType": "dynamic_query",
  1849. "orderby": ["count()", "p95(transaction.duration)"],
  1850. "interval": "1d",
  1851. "partial": 1,
  1852. "query": query,
  1853. "referrer": "api.dashboards.widget.bar-chart",
  1854. "project": self.project.id,
  1855. "topEvents": 2,
  1856. "useOnDemandMetrics": "true",
  1857. "yAxis": "p95(transaction.duration)",
  1858. },
  1859. )
  1860. assert response.status_code == 400, response.content
  1861. def test_top_events_with_tag(self):
  1862. query = "transaction.duration:>=100"
  1863. yAxis = ["count()"]
  1864. field = "count()"
  1865. groupbys = ["some-field"]
  1866. spec = OnDemandMetricSpec(
  1867. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1868. )
  1869. self.store_on_demand_metric(
  1870. 1,
  1871. spec=spec,
  1872. additional_tags={
  1873. "some-field": "bar",
  1874. "environment": "production",
  1875. },
  1876. timestamp=self.day_ago,
  1877. )
  1878. response = self.do_request(
  1879. data={
  1880. "project": self.project.id,
  1881. "start": iso_format(self.day_ago),
  1882. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1883. "interval": "1h",
  1884. "orderby": ["-count()"],
  1885. "environment": "production",
  1886. "query": query,
  1887. "yAxis": yAxis,
  1888. "field": [
  1889. "some-field",
  1890. "count()",
  1891. ],
  1892. "topEvents": 5,
  1893. "dataset": "metrics",
  1894. "useOnDemandMetrics": "true",
  1895. },
  1896. )
  1897. assert response.status_code == 200, response.content