test_organization_events_stats_mep.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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 sentry.models.environment import Environment
  8. from sentry.sentry_metrics.use_case_id_registry import UseCaseID
  9. from sentry.snuba.metrics.extraction import MetricSpecType, OnDemandMetricSpec
  10. from sentry.testutils.cases import MetricsEnhancedPerformanceTestCase
  11. from sentry.testutils.helpers.datetime import before_now, iso_format
  12. from sentry.testutils.silo import region_silo_test
  13. pytestmark = pytest.mark.sentry_metrics
  14. @region_silo_test
  15. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest(
  16. MetricsEnhancedPerformanceTestCase
  17. ):
  18. endpoint = "sentry-api-0-organization-events-stats"
  19. METRIC_STRINGS = [
  20. "foo_transaction",
  21. "d:transactions/measurements.datacenter_memory@pebibyte",
  22. ]
  23. def setUp(self):
  24. super().setUp()
  25. self.login_as(user=self.user)
  26. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  27. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  28. self.url = reverse(
  29. "sentry-api-0-organization-events-stats",
  30. kwargs={"organization_slug": self.project.organization.slug},
  31. )
  32. self.features = {
  33. "organizations:performance-use-metrics": True,
  34. }
  35. self.additional_params = dict()
  36. # These throughput tests should roughly match the ones in OrganizationEventsStatsEndpointTest
  37. def test_throughput_epm_hour_rollup(self):
  38. # Each of these denotes how many events to create in each hour
  39. event_counts = [6, 0, 6, 3, 0, 3]
  40. for hour, count in enumerate(event_counts):
  41. for minute in range(count):
  42. self.store_transaction_metric(
  43. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  44. )
  45. for axis in ["epm()", "tpm()"]:
  46. response = self.do_request(
  47. data={
  48. "start": iso_format(self.day_ago),
  49. "end": iso_format(self.day_ago + timedelta(hours=6)),
  50. "interval": "1h",
  51. "yAxis": axis,
  52. "project": self.project.id,
  53. "dataset": "metricsEnhanced",
  54. **self.additional_params,
  55. },
  56. )
  57. assert response.status_code == 200, response.content
  58. data = response.data["data"]
  59. assert len(data) == 6
  60. assert response.data["isMetricsData"]
  61. rows = data[0:6]
  62. for test in zip(event_counts, rows):
  63. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  64. def test_throughput_epm_day_rollup(self):
  65. # Each of these denotes how many events to create in each minute
  66. event_counts = [6, 0, 6, 3, 0, 3]
  67. for hour, count in enumerate(event_counts):
  68. for minute in range(count):
  69. self.store_transaction_metric(
  70. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  71. )
  72. for axis in ["epm()", "tpm()"]:
  73. response = self.do_request(
  74. data={
  75. "start": iso_format(self.day_ago),
  76. "end": iso_format(self.day_ago + timedelta(hours=24)),
  77. "interval": "24h",
  78. "yAxis": axis,
  79. "project": self.project.id,
  80. "dataset": "metricsEnhanced",
  81. **self.additional_params,
  82. },
  83. )
  84. assert response.status_code == 200, response.content
  85. data = response.data["data"]
  86. assert len(data) == 2
  87. assert response.data["isMetricsData"]
  88. assert data[0][1][0]["count"] == sum(event_counts) / (86400.0 / 60.0)
  89. def test_throughput_epm_hour_rollup_offset_of_hour(self):
  90. # Each of these denotes how many events to create in each hour
  91. event_counts = [6, 0, 6, 3, 0, 3]
  92. for hour, count in enumerate(event_counts):
  93. for minute in range(count):
  94. self.store_transaction_metric(
  95. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute + 30)
  96. )
  97. for axis in ["tpm()", "epm()"]:
  98. response = self.do_request(
  99. data={
  100. "start": iso_format(self.day_ago + timedelta(minutes=30)),
  101. "end": iso_format(self.day_ago + timedelta(hours=6, minutes=30)),
  102. "interval": "1h",
  103. "yAxis": axis,
  104. "project": self.project.id,
  105. "dataset": "metricsEnhanced",
  106. **self.additional_params,
  107. },
  108. )
  109. assert response.status_code == 200, response.content
  110. data = response.data["data"]
  111. assert len(data) == 6
  112. assert response.data["isMetricsData"]
  113. rows = data[0:6]
  114. for test in zip(event_counts, rows):
  115. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  116. def test_throughput_eps_minute_rollup(self):
  117. # Each of these denotes how many events to create in each minute
  118. event_counts = [6, 0, 6, 3, 0, 3]
  119. for minute, count in enumerate(event_counts):
  120. for second in range(count):
  121. self.store_transaction_metric(
  122. 1, timestamp=self.day_ago + timedelta(minutes=minute, seconds=second)
  123. )
  124. for axis in ["eps()", "tps()"]:
  125. response = self.do_request(
  126. data={
  127. "start": iso_format(self.day_ago),
  128. "end": iso_format(self.day_ago + timedelta(minutes=6)),
  129. "interval": "1m",
  130. "yAxis": axis,
  131. "project": self.project.id,
  132. "dataset": "metricsEnhanced",
  133. **self.additional_params,
  134. },
  135. )
  136. assert response.status_code == 200, response.content
  137. data = response.data["data"]
  138. assert len(data) == 6
  139. assert response.data["isMetricsData"]
  140. rows = data[0:6]
  141. for test in zip(event_counts, rows):
  142. assert test[1][1][0]["count"] == test[0] / 60.0
  143. def test_failure_rate(self):
  144. for hour in range(6):
  145. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  146. self.store_transaction_metric(1, tags={"transaction.status": "ok"}, timestamp=timestamp)
  147. if hour < 3:
  148. self.store_transaction_metric(
  149. 1, tags={"transaction.status": "internal_error"}, timestamp=timestamp
  150. )
  151. response = self.do_request(
  152. data={
  153. "start": iso_format(self.day_ago),
  154. "end": iso_format(self.day_ago + timedelta(hours=6)),
  155. "interval": "1h",
  156. "yAxis": ["failure_rate()"],
  157. "project": self.project.id,
  158. "dataset": "metricsEnhanced",
  159. **self.additional_params,
  160. },
  161. )
  162. assert response.status_code == 200, response.content
  163. data = response.data["data"]
  164. assert len(data) == 6
  165. assert response.data["isMetricsData"]
  166. assert [attrs for time, attrs in response.data["data"]] == [
  167. [{"count": 0.5}],
  168. [{"count": 0.5}],
  169. [{"count": 0.5}],
  170. [{"count": 0}],
  171. [{"count": 0}],
  172. [{"count": 0}],
  173. ]
  174. def test_percentiles_multi_axis(self):
  175. for hour in range(6):
  176. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  177. self.store_transaction_metric(111, timestamp=timestamp)
  178. self.store_transaction_metric(222, metric="measurements.lcp", timestamp=timestamp)
  179. response = self.do_request(
  180. data={
  181. "start": iso_format(self.day_ago),
  182. "end": iso_format(self.day_ago + timedelta(hours=6)),
  183. "interval": "1h",
  184. "yAxis": ["p75(measurements.lcp)", "p75(transaction.duration)"],
  185. "project": self.project.id,
  186. "dataset": "metricsEnhanced",
  187. **self.additional_params,
  188. },
  189. )
  190. assert response.status_code == 200, response.content
  191. lcp = response.data["p75(measurements.lcp)"]
  192. duration = response.data["p75(transaction.duration)"]
  193. assert len(duration["data"]) == 6
  194. assert duration["isMetricsData"]
  195. assert len(lcp["data"]) == 6
  196. assert lcp["isMetricsData"]
  197. for item in duration["data"]:
  198. assert item[1][0]["count"] == 111
  199. for item in lcp["data"]:
  200. assert item[1][0]["count"] == 222
  201. @mock.patch("sentry.snuba.metrics_enhanced_performance.timeseries_query", return_value={})
  202. def test_multiple_yaxis_only_one_query(self, mock_query):
  203. self.do_request(
  204. data={
  205. "project": self.project.id,
  206. "start": iso_format(self.day_ago),
  207. "end": iso_format(self.day_ago + timedelta(hours=2)),
  208. "interval": "1h",
  209. "yAxis": ["epm()", "eps()", "tpm()", "p50(transaction.duration)"],
  210. "dataset": "metricsEnhanced",
  211. **self.additional_params,
  212. },
  213. )
  214. assert mock_query.call_count == 1
  215. def test_aggregate_function_user_count(self):
  216. self.store_transaction_metric(
  217. 1, metric="user", timestamp=self.day_ago + timedelta(minutes=30)
  218. )
  219. self.store_transaction_metric(
  220. 1, metric="user", timestamp=self.day_ago + timedelta(hours=1, minutes=30)
  221. )
  222. response = self.do_request(
  223. data={
  224. "start": iso_format(self.day_ago),
  225. "end": iso_format(self.day_ago + timedelta(hours=2)),
  226. "interval": "1h",
  227. "yAxis": "count_unique(user)",
  228. "dataset": "metricsEnhanced",
  229. **self.additional_params,
  230. },
  231. )
  232. assert response.status_code == 200, response.content
  233. assert response.data["isMetricsData"]
  234. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 1}]]
  235. meta = response.data["meta"]
  236. assert meta["isMetricsData"] == response.data["isMetricsData"]
  237. def test_non_mep_query_fallsback(self):
  238. def get_mep(query):
  239. response = self.do_request(
  240. data={
  241. "project": self.project.id,
  242. "start": iso_format(self.day_ago),
  243. "end": iso_format(self.day_ago + timedelta(hours=2)),
  244. "interval": "1h",
  245. "query": query,
  246. "yAxis": ["epm()"],
  247. "dataset": "metricsEnhanced",
  248. **self.additional_params,
  249. },
  250. )
  251. assert response.status_code == 200, response.content
  252. return response.data["isMetricsData"]
  253. assert get_mep(""), "empty query"
  254. assert get_mep("event.type:transaction"), "event type transaction"
  255. assert not get_mep("event.type:error"), "event type error"
  256. assert not get_mep("transaction.duration:<15min"), "outlier filter"
  257. assert get_mep("epm():>0.01"), "throughput filter"
  258. assert not get_mep(
  259. "event.type:transaction OR event.type:error"
  260. ), "boolean with non-mep filter"
  261. assert get_mep(
  262. "event.type:transaction OR transaction:foo_transaction"
  263. ), "boolean with mep filter"
  264. def test_having_condition_with_preventing_aggregates(self):
  265. response = self.do_request(
  266. data={
  267. "project": self.project.id,
  268. "start": iso_format(self.day_ago),
  269. "end": iso_format(self.day_ago + timedelta(hours=2)),
  270. "interval": "1h",
  271. "query": "p95():<5s",
  272. "yAxis": ["epm()"],
  273. "dataset": "metricsEnhanced",
  274. "preventMetricAggregates": "1",
  275. **self.additional_params,
  276. },
  277. )
  278. assert response.status_code == 200, response.content
  279. assert not response.data["isMetricsData"]
  280. meta = response.data["meta"]
  281. assert meta["isMetricsData"] == response.data["isMetricsData"]
  282. def test_explicit_not_mep(self):
  283. response = self.do_request(
  284. data={
  285. "project": self.project.id,
  286. "start": iso_format(self.day_ago),
  287. "end": iso_format(self.day_ago + timedelta(hours=2)),
  288. "interval": "1h",
  289. # Should be a mep able query
  290. "query": "",
  291. "yAxis": ["epm()"],
  292. "metricsEnhanced": "0",
  293. **self.additional_params,
  294. },
  295. )
  296. assert response.status_code == 200, response.content
  297. assert not response.data["isMetricsData"]
  298. meta = response.data["meta"]
  299. assert meta["isMetricsData"] == response.data["isMetricsData"]
  300. def test_sum_transaction_duration(self):
  301. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  302. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  303. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  304. response = self.do_request(
  305. data={
  306. "start": iso_format(self.day_ago),
  307. "end": iso_format(self.day_ago + timedelta(hours=2)),
  308. "interval": "1h",
  309. "yAxis": "sum(transaction.duration)",
  310. "dataset": "metricsEnhanced",
  311. **self.additional_params,
  312. },
  313. )
  314. assert response.status_code == 200, response.content
  315. assert response.data["isMetricsData"]
  316. assert [attrs for time, attrs in response.data["data"]] == [
  317. [{"count": 123}],
  318. [{"count": 1245}],
  319. ]
  320. meta = response.data["meta"]
  321. assert meta["isMetricsData"] == response.data["isMetricsData"]
  322. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  323. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  324. def test_sum_transaction_duration_with_comparison(self):
  325. # We store the data for the previous day (in order to have values for the comparison).
  326. self.store_transaction_metric(
  327. 1, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  328. )
  329. self.store_transaction_metric(
  330. 2, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  331. )
  332. # We store the data for today.
  333. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  334. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(minutes=30))
  335. response = self.do_request(
  336. data={
  337. "start": iso_format(self.day_ago),
  338. "end": iso_format(self.day_ago + timedelta(days=1)),
  339. "interval": "1d",
  340. "yAxis": "sum(transaction.duration)",
  341. "comparisonDelta": 86400,
  342. "dataset": "metricsEnhanced",
  343. **self.additional_params,
  344. },
  345. )
  346. assert response.status_code == 200, response.content
  347. assert response.data["isMetricsData"]
  348. # For some reason, if all tests run, there is some shared state that makes this test have data in the second
  349. # time bucket, which is filled automatically by the zerofilling. In order to avoid this flaky failure, we will
  350. # only check that the first bucket contains the actual data.
  351. assert [attrs for time, attrs in response.data["data"]][0] == [
  352. {"comparisonCount": 3.0, "count": 579.0}
  353. ]
  354. meta = response.data["meta"]
  355. assert meta["isMetricsData"] == response.data["isMetricsData"]
  356. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  357. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  358. def test_custom_measurement(self):
  359. self.store_transaction_metric(
  360. 123,
  361. metric="measurements.bytes_transfered",
  362. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  363. entity="metrics_distributions",
  364. tags={"transaction": "foo_transaction"},
  365. timestamp=self.day_ago + timedelta(minutes=30),
  366. )
  367. self.store_transaction_metric(
  368. 456,
  369. metric="measurements.bytes_transfered",
  370. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  371. entity="metrics_distributions",
  372. tags={"transaction": "foo_transaction"},
  373. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  374. )
  375. self.store_transaction_metric(
  376. 789,
  377. metric="measurements.bytes_transfered",
  378. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  379. entity="metrics_distributions",
  380. tags={"transaction": "foo_transaction"},
  381. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  382. )
  383. response = self.do_request(
  384. data={
  385. "start": iso_format(self.day_ago),
  386. "end": iso_format(self.day_ago + timedelta(hours=2)),
  387. "interval": "1h",
  388. "yAxis": "sum(measurements.datacenter_memory)",
  389. "dataset": "metricsEnhanced",
  390. **self.additional_params,
  391. },
  392. )
  393. assert response.status_code == 200, response.content
  394. assert response.data["isMetricsData"]
  395. assert [attrs for time, attrs in response.data["data"]] == [
  396. [{"count": 123}],
  397. [{"count": 1245}],
  398. ]
  399. meta = response.data["meta"]
  400. assert meta["isMetricsData"] == response.data["isMetricsData"]
  401. assert meta["fields"] == {"time": "date", "sum_measurements_datacenter_memory": "size"}
  402. assert meta["units"] == {"time": None, "sum_measurements_datacenter_memory": "pebibyte"}
  403. def test_does_not_fallback_if_custom_metric_is_out_of_request_time_range(self):
  404. self.store_transaction_metric(
  405. 123,
  406. timestamp=self.day_ago + timedelta(hours=1),
  407. internal_metric="d:transactions/measurements.custom@kibibyte",
  408. entity="metrics_distributions",
  409. )
  410. response = self.do_request(
  411. data={
  412. "start": iso_format(self.day_ago),
  413. "end": iso_format(self.day_ago + timedelta(hours=2)),
  414. "interval": "1h",
  415. "yAxis": "p99(measurements.custom)",
  416. "dataset": "metricsEnhanced",
  417. **self.additional_params,
  418. },
  419. )
  420. meta = response.data["meta"]
  421. assert response.status_code == 200, response.content
  422. assert response.data["isMetricsData"]
  423. assert meta["isMetricsData"]
  424. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  425. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  426. def test_multi_yaxis_custom_measurement(self):
  427. self.store_transaction_metric(
  428. 123,
  429. metric="measurements.bytes_transfered",
  430. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  431. entity="metrics_distributions",
  432. tags={"transaction": "foo_transaction"},
  433. timestamp=self.day_ago + timedelta(minutes=30),
  434. )
  435. self.store_transaction_metric(
  436. 456,
  437. metric="measurements.bytes_transfered",
  438. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  439. entity="metrics_distributions",
  440. tags={"transaction": "foo_transaction"},
  441. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  442. )
  443. self.store_transaction_metric(
  444. 789,
  445. metric="measurements.bytes_transfered",
  446. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  447. entity="metrics_distributions",
  448. tags={"transaction": "foo_transaction"},
  449. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  450. )
  451. response = self.do_request(
  452. data={
  453. "start": iso_format(self.day_ago),
  454. "end": iso_format(self.day_ago + timedelta(hours=2)),
  455. "interval": "1h",
  456. "yAxis": [
  457. "sum(measurements.datacenter_memory)",
  458. "p50(measurements.datacenter_memory)",
  459. ],
  460. "dataset": "metricsEnhanced",
  461. **self.additional_params,
  462. },
  463. )
  464. assert response.status_code == 200, response.content
  465. sum_data = response.data["sum(measurements.datacenter_memory)"]
  466. p50_data = response.data["p50(measurements.datacenter_memory)"]
  467. assert sum_data["isMetricsData"]
  468. assert p50_data["isMetricsData"]
  469. assert [attrs for time, attrs in sum_data["data"]] == [
  470. [{"count": 123}],
  471. [{"count": 1245}],
  472. ]
  473. assert [attrs for time, attrs in p50_data["data"]] == [
  474. [{"count": 123}],
  475. [{"count": 622.5}],
  476. ]
  477. sum_meta = sum_data["meta"]
  478. assert sum_meta["isMetricsData"] == sum_data["isMetricsData"]
  479. assert sum_meta["fields"] == {
  480. "time": "date",
  481. "sum_measurements_datacenter_memory": "size",
  482. "p50_measurements_datacenter_memory": "size",
  483. }
  484. assert sum_meta["units"] == {
  485. "time": None,
  486. "sum_measurements_datacenter_memory": "pebibyte",
  487. "p50_measurements_datacenter_memory": "pebibyte",
  488. }
  489. p50_meta = p50_data["meta"]
  490. assert p50_meta["isMetricsData"] == p50_data["isMetricsData"]
  491. assert p50_meta["fields"] == {
  492. "time": "date",
  493. "sum_measurements_datacenter_memory": "size",
  494. "p50_measurements_datacenter_memory": "size",
  495. }
  496. assert p50_meta["units"] == {
  497. "time": None,
  498. "sum_measurements_datacenter_memory": "pebibyte",
  499. "p50_measurements_datacenter_memory": "pebibyte",
  500. }
  501. def test_dataset_metrics_does_not_fallback(self):
  502. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  503. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  504. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  505. response = self.do_request(
  506. data={
  507. "start": iso_format(self.day_ago),
  508. "end": iso_format(self.day_ago + timedelta(hours=2)),
  509. "interval": "1h",
  510. "query": "transaction.duration:<5s",
  511. "yAxis": "sum(transaction.duration)",
  512. "dataset": "metrics",
  513. **self.additional_params,
  514. },
  515. )
  516. assert response.status_code == 400, response.content
  517. def test_title_filter(self):
  518. self.store_transaction_metric(
  519. 123,
  520. tags={"transaction": "foo_transaction"},
  521. timestamp=self.day_ago + timedelta(minutes=30),
  522. )
  523. response = self.do_request(
  524. data={
  525. "start": iso_format(self.day_ago),
  526. "end": iso_format(self.day_ago + timedelta(hours=2)),
  527. "interval": "1h",
  528. "query": "title:foo_transaction",
  529. "yAxis": [
  530. "sum(transaction.duration)",
  531. ],
  532. "dataset": "metricsEnhanced",
  533. **self.additional_params,
  534. },
  535. )
  536. assert response.status_code == 200, response.content
  537. data = response.data["data"]
  538. assert [attrs for time, attrs in data] == [
  539. [{"count": 123}],
  540. [{"count": 0}],
  541. ]
  542. def test_transaction_status_unknown_error(self):
  543. self.store_transaction_metric(
  544. 123,
  545. tags={"transaction.status": "unknown"},
  546. timestamp=self.day_ago + timedelta(minutes=30),
  547. )
  548. response = self.do_request(
  549. data={
  550. "start": iso_format(self.day_ago),
  551. "end": iso_format(self.day_ago + timedelta(hours=2)),
  552. "interval": "1h",
  553. "query": "transaction.status:unknown_error",
  554. "yAxis": [
  555. "sum(transaction.duration)",
  556. ],
  557. "dataset": "metricsEnhanced",
  558. **self.additional_params,
  559. },
  560. )
  561. assert response.status_code == 200, response.content
  562. data = response.data["data"]
  563. assert [attrs for time, attrs in data] == [
  564. [{"count": 123}],
  565. [{"count": 0}],
  566. ]
  567. def test_custom_performance_metric_meta_contains_field_and_unit_data(self):
  568. self.store_transaction_metric(
  569. 123,
  570. timestamp=self.day_ago + timedelta(hours=1),
  571. internal_metric="d:transactions/measurements.custom@kibibyte",
  572. entity="metrics_distributions",
  573. )
  574. response = self.do_request(
  575. data={
  576. "start": iso_format(self.day_ago),
  577. "end": iso_format(self.day_ago + timedelta(hours=2)),
  578. "interval": "1h",
  579. "yAxis": "p99(measurements.custom)",
  580. "query": "",
  581. **self.additional_params,
  582. },
  583. )
  584. assert response.status_code == 200
  585. meta = response.data["meta"]
  586. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  587. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  588. def test_multi_series_custom_performance_metric_meta_contains_field_and_unit_data(self):
  589. self.store_transaction_metric(
  590. 123,
  591. timestamp=self.day_ago + timedelta(hours=1),
  592. internal_metric="d:transactions/measurements.custom@kibibyte",
  593. entity="metrics_distributions",
  594. )
  595. self.store_transaction_metric(
  596. 123,
  597. timestamp=self.day_ago + timedelta(hours=1),
  598. internal_metric="d:transactions/measurements.another.custom@pebibyte",
  599. entity="metrics_distributions",
  600. )
  601. response = self.do_request(
  602. data={
  603. "start": iso_format(self.day_ago),
  604. "end": iso_format(self.day_ago + timedelta(hours=2)),
  605. "interval": "1h",
  606. "yAxis": [
  607. "p95(measurements.custom)",
  608. "p99(measurements.custom)",
  609. "p99(measurements.another.custom)",
  610. ],
  611. "query": "",
  612. **self.additional_params,
  613. },
  614. )
  615. assert response.status_code == 200
  616. meta = response.data["p95(measurements.custom)"]["meta"]
  617. assert meta["fields"] == {
  618. "time": "date",
  619. "p95_measurements_custom": "size",
  620. "p99_measurements_custom": "size",
  621. "p99_measurements_another_custom": "size",
  622. }
  623. assert meta["units"] == {
  624. "time": None,
  625. "p95_measurements_custom": "kibibyte",
  626. "p99_measurements_custom": "kibibyte",
  627. "p99_measurements_another_custom": "pebibyte",
  628. }
  629. assert meta == response.data["p99(measurements.custom)"]["meta"]
  630. assert meta == response.data["p99(measurements.another.custom)"]["meta"]
  631. def test_no_top_events_with_project_field(self):
  632. project = self.create_project()
  633. response = self.do_request(
  634. data={
  635. # make sure to query the project with 0 events
  636. "project": project.id,
  637. "start": iso_format(self.day_ago),
  638. "end": iso_format(self.day_ago + timedelta(hours=2)),
  639. "interval": "1h",
  640. "yAxis": "count()",
  641. "orderby": ["-count()"],
  642. "field": ["count()", "project"],
  643. "topEvents": 5,
  644. "dataset": "metrics",
  645. **self.additional_params,
  646. },
  647. )
  648. assert response.status_code == 200, response.content
  649. # When there are no top events, we do not return an empty dict.
  650. # Instead, we return a single zero-filled series for an empty graph.
  651. data = response.data["data"]
  652. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  653. def test_top_events_with_transaction(self):
  654. transaction_spec = [("foo", 100), ("bar", 200), ("baz", 300)]
  655. for offset in range(5):
  656. for transaction, duration in transaction_spec:
  657. self.store_transaction_metric(
  658. duration,
  659. tags={"transaction": f"{transaction}_transaction"},
  660. timestamp=self.day_ago + timedelta(hours=offset, minutes=30),
  661. )
  662. response = self.do_request(
  663. data={
  664. # make sure to query the project with 0 events
  665. "project": self.project.id,
  666. "start": iso_format(self.day_ago),
  667. "end": iso_format(self.day_ago + timedelta(hours=5)),
  668. "interval": "1h",
  669. "yAxis": "p75(transaction.duration)",
  670. "orderby": ["-p75(transaction.duration)"],
  671. "field": ["p75(transaction.duration)", "transaction"],
  672. "topEvents": 5,
  673. "dataset": "metrics",
  674. **self.additional_params,
  675. },
  676. )
  677. assert response.status_code == 200, response.content
  678. for position, (transaction, duration) in enumerate(transaction_spec):
  679. data = response.data[f"{transaction}_transaction"]
  680. chart_data = data["data"]
  681. assert data["order"] == 2 - position
  682. assert [attrs for time, attrs in chart_data] == [[{"count": duration}]] * 5
  683. def test_top_events_with_project(self):
  684. self.store_transaction_metric(
  685. 100,
  686. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  687. )
  688. response = self.do_request(
  689. data={
  690. # make sure to query the project with 0 events
  691. "project": self.project.id,
  692. "start": iso_format(self.day_ago),
  693. "end": iso_format(self.day_ago + timedelta(hours=5)),
  694. "interval": "1h",
  695. "yAxis": "p75(transaction.duration)",
  696. "orderby": ["-p75(transaction.duration)"],
  697. "field": ["p75(transaction.duration)", "project"],
  698. "topEvents": 5,
  699. "dataset": "metrics",
  700. **self.additional_params,
  701. },
  702. )
  703. assert response.status_code == 200, response.content
  704. data = response.data[f"{self.project.slug}"]
  705. assert data["order"] == 0
  706. @region_silo_test
  707. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithMetricLayer(
  708. OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest
  709. ):
  710. def setUp(self):
  711. super().setUp()
  712. self.features["organizations:use-metrics-layer"] = True
  713. self.additional_params = {"forceMetricsLayer": "true"}
  714. def test_counter_standard_metric(self):
  715. mri = "c:transactions/usage@none"
  716. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  717. self.store_transaction_metric(
  718. value,
  719. metric=mri,
  720. internal_metric=mri,
  721. entity="metrics_counters",
  722. timestamp=self.day_ago + timedelta(minutes=index),
  723. use_case_id=UseCaseID.CUSTOM,
  724. )
  725. response = self.do_request(
  726. data={
  727. "start": iso_format(self.day_ago),
  728. "end": iso_format(self.day_ago + timedelta(hours=6)),
  729. "interval": "1m",
  730. "yAxis": [f"sum({mri})"],
  731. "project": self.project.id,
  732. "dataset": "metricsEnhanced",
  733. **self.additional_params,
  734. },
  735. )
  736. assert response.status_code == 200, response.content
  737. data = response.data["data"]
  738. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  739. assert value[0]["count"] == expected_value # type:ignore
  740. def test_counter_custom_metric(self):
  741. mri = "c:custom/sentry.process_profile.track_outcome@second"
  742. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  743. self.store_transaction_metric(
  744. value,
  745. metric=mri,
  746. internal_metric=mri,
  747. entity="metrics_counters",
  748. timestamp=self.day_ago + timedelta(hours=index),
  749. use_case_id=UseCaseID.CUSTOM,
  750. )
  751. response = self.do_request(
  752. data={
  753. "start": iso_format(self.day_ago),
  754. "end": iso_format(self.day_ago + timedelta(hours=6)),
  755. "interval": "1h",
  756. "yAxis": [f"sum({mri})"],
  757. "project": self.project.id,
  758. "dataset": "metricsEnhanced",
  759. **self.additional_params,
  760. },
  761. )
  762. assert response.status_code == 200, response.content
  763. data = response.data["data"]
  764. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  765. assert value[0]["count"] == expected_value # type:ignore
  766. def test_distribution_custom_metric(self):
  767. mri = "d:custom/sentry.process_profile.track_outcome@second"
  768. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  769. for multiplier in (1, 2, 3):
  770. self.store_transaction_metric(
  771. value * multiplier,
  772. metric=mri,
  773. internal_metric=mri,
  774. entity="metrics_distributions",
  775. timestamp=self.day_ago + timedelta(hours=index),
  776. use_case_id=UseCaseID.CUSTOM,
  777. )
  778. response = self.do_request(
  779. data={
  780. "start": iso_format(self.day_ago),
  781. "end": iso_format(self.day_ago + timedelta(hours=6)),
  782. "interval": "1h",
  783. "yAxis": [f"min({mri})", f"max({mri})", f"p90({mri})"],
  784. "project": self.project.id,
  785. "dataset": "metricsEnhanced",
  786. **self.additional_params,
  787. },
  788. )
  789. assert response.status_code == 200, response.content
  790. data = response.data
  791. min = data[f"min({mri})"]["data"]
  792. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  793. assert value[0]["count"] == expected_value # type:ignore
  794. max = data[f"max({mri})"]["data"]
  795. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  796. assert value[0]["count"] == expected_value # type:ignore
  797. p90 = data[f"p90({mri})"]["data"]
  798. for (_, value), expected_value in zip(p90, [28.0, 56.0, 84.0, 112.0, 140.0, 168.0]):
  799. assert value[0]["count"] == expected_value # type:ignore
  800. def test_set_custom_metric(self):
  801. mri = "s:custom/sentry.process_profile.track_outcome@second"
  802. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  803. # We store each value a second time, since we want to check the de-duplication of sets.
  804. for i in range(0, 2):
  805. self.store_transaction_metric(
  806. value,
  807. metric=mri,
  808. internal_metric=mri,
  809. entity="metrics_sets",
  810. timestamp=self.day_ago + timedelta(hours=index),
  811. use_case_id=UseCaseID.CUSTOM,
  812. )
  813. response = self.do_request(
  814. data={
  815. "start": iso_format(self.day_ago),
  816. "end": iso_format(self.day_ago + timedelta(hours=6)),
  817. "interval": "1h",
  818. "yAxis": [f"count_unique({mri})"],
  819. "project": self.project.id,
  820. "dataset": "metricsEnhanced",
  821. **self.additional_params,
  822. },
  823. )
  824. assert response.status_code == 200, response.content
  825. data = response.data["data"]
  826. for (_, value), expected_value in zip(data, [1, 1, 1, 1, 1, 1]):
  827. assert value[0]["count"] == expected_value # type:ignore
  828. def test_gauge_custom_metric(self):
  829. mri = "g:custom/sentry.process_profile.track_outcome@second"
  830. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  831. for multiplier in (1, 3):
  832. self.store_transaction_metric(
  833. value * multiplier,
  834. metric=mri,
  835. internal_metric=mri,
  836. entity="metrics_gauges",
  837. # When multiple gauges are merged, in order to make the `last` merge work deterministically it's
  838. # better to have the gauges with different timestamps so that the last value is always the same.
  839. timestamp=self.day_ago + timedelta(hours=index, minutes=multiplier),
  840. use_case_id=UseCaseID.CUSTOM,
  841. )
  842. response = self.do_request(
  843. data={
  844. "start": iso_format(self.day_ago),
  845. "end": iso_format(self.day_ago + timedelta(hours=6)),
  846. "interval": "1h",
  847. "yAxis": [
  848. f"min({mri})",
  849. f"max({mri})",
  850. f"last({mri})",
  851. f"sum({mri})",
  852. f"count({mri})",
  853. ],
  854. "project": self.project.id,
  855. "dataset": "metricsEnhanced",
  856. **self.additional_params,
  857. },
  858. )
  859. assert response.status_code == 200, response.content
  860. data = response.data
  861. min = data[f"min({mri})"]["data"]
  862. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  863. assert value[0]["count"] == expected_value # type:ignore
  864. max = data[f"max({mri})"]["data"]
  865. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  866. assert value[0]["count"] == expected_value # type:ignore
  867. last = data[f"last({mri})"]["data"]
  868. for (_, value), expected_value in zip(last, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  869. assert value[0]["count"] == expected_value # type:ignore
  870. sum = data[f"sum({mri})"]["data"]
  871. for (_, value), expected_value in zip(sum, [40.0, 80.0, 120.0, 160.0, 200.0, 240.0]):
  872. assert value[0]["count"] == expected_value # type:ignore
  873. count = data[f"count({mri})"]["data"]
  874. for (_, value), expected_value in zip(count, [40, 80, 120, 160, 200, 240]):
  875. assert value[0]["count"] == expected_value # type:ignore
  876. @region_silo_test
  877. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithOnDemandWidgets(
  878. MetricsEnhancedPerformanceTestCase
  879. ):
  880. endpoint = "sentry-api-0-organization-events-stats"
  881. def setUp(self):
  882. super().setUp()
  883. self.login_as(user=self.user)
  884. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  885. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  886. Environment.get_or_create(self.project, "production")
  887. self.url = reverse(
  888. "sentry-api-0-organization-events-stats",
  889. kwargs={"organization_slug": self.project.organization.slug},
  890. )
  891. self.features = {
  892. "organizations:on-demand-metrics-extraction-widgets": True,
  893. "organizations:on-demand-metrics-extraction": True,
  894. }
  895. def test_top_events_wrong_on_demand_type(self):
  896. query = "transaction.duration:>=100"
  897. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  898. response = self.do_request(
  899. data={
  900. "project": self.project.id,
  901. "start": iso_format(self.day_ago),
  902. "end": iso_format(self.day_ago + timedelta(hours=2)),
  903. "interval": "1h",
  904. "orderby": ["-count()"],
  905. "environment": "production",
  906. "query": query,
  907. "yAxis": yAxis,
  908. "field": [
  909. "count()",
  910. ],
  911. "topEvents": 5,
  912. "dataset": "metrics",
  913. "useOnDemandMetrics": "true",
  914. "onDemandType": "not_real",
  915. },
  916. )
  917. assert response.status_code == 400, response.content
  918. def test_top_events_works_without_on_demand_type(self):
  919. query = "transaction.duration:>=100"
  920. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  921. response = self.do_request(
  922. data={
  923. "project": self.project.id,
  924. "start": iso_format(self.day_ago),
  925. "end": iso_format(self.day_ago + timedelta(hours=2)),
  926. "interval": "1h",
  927. "orderby": ["-count()"],
  928. "environment": "production",
  929. "query": query,
  930. "yAxis": yAxis,
  931. "field": [
  932. "count()",
  933. ],
  934. "topEvents": 5,
  935. "dataset": "metrics",
  936. "useOnDemandMetrics": "true",
  937. },
  938. )
  939. assert response.status_code == 200, response.content
  940. def test_top_events_with_transaction_on_demand(self):
  941. field = "count()"
  942. field_two = "count_web_vitals(measurements.lcp, good)"
  943. groupbys = ["customtag1", "customtag2"]
  944. query = "transaction.duration:>=100"
  945. spec = OnDemandMetricSpec(
  946. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  947. )
  948. spec_two = OnDemandMetricSpec(
  949. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  950. )
  951. for hour in range(0, 5):
  952. self.store_on_demand_metric(
  953. hour * 62 * 24,
  954. spec=spec,
  955. additional_tags={
  956. "customtag1": "foo",
  957. "customtag2": "red",
  958. "environment": "production",
  959. },
  960. timestamp=self.day_ago + timedelta(hours=hour),
  961. )
  962. self.store_on_demand_metric(
  963. hour * 60 * 24,
  964. spec=spec_two,
  965. additional_tags={
  966. "customtag1": "bar",
  967. "customtag2": "blue",
  968. "environment": "production",
  969. },
  970. timestamp=self.day_ago + timedelta(hours=hour),
  971. )
  972. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  973. response = self.do_request(
  974. data={
  975. "project": self.project.id,
  976. "start": iso_format(self.day_ago),
  977. "end": iso_format(self.day_ago + timedelta(hours=2)),
  978. "interval": "1h",
  979. "orderby": ["-count()"],
  980. "environment": "production",
  981. "query": query,
  982. "yAxis": yAxis,
  983. "field": [
  984. "count()",
  985. "count_web_vitals(measurements.lcp, good)",
  986. "customtag1",
  987. "customtag2",
  988. ],
  989. "topEvents": 5,
  990. "dataset": "metricsEnhanced",
  991. "useOnDemandMetrics": "true",
  992. "onDemandType": "dynamic_query",
  993. },
  994. )
  995. assert response.status_code == 200, response.content
  996. groups = [
  997. ("foo,red", "count()", 0.0, 1488.0),
  998. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  999. ("bar,blue", "count()", 0.0, 0.0),
  1000. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1001. ]
  1002. assert len(response.data.keys()) == 2
  1003. for group_count in groups:
  1004. group, agg, row1, row2 = group_count
  1005. row_data = response.data[group][agg]["data"][:2]
  1006. assert [attrs for _, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1007. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1008. assert response.data[group]["isMetricsExtractedData"]
  1009. def test_top_events_with_transaction_on_demand_and_no_environment(self):
  1010. field = "count()"
  1011. field_two = "count_web_vitals(measurements.lcp, good)"
  1012. groupbys = ["customtag1", "customtag2"]
  1013. query = "transaction.duration:>=100"
  1014. spec = OnDemandMetricSpec(
  1015. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1016. )
  1017. spec_two = OnDemandMetricSpec(
  1018. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1019. )
  1020. for hour in range(0, 5):
  1021. self.store_on_demand_metric(
  1022. hour * 62 * 24,
  1023. spec=spec,
  1024. additional_tags={
  1025. "customtag1": "foo",
  1026. "customtag2": "red",
  1027. "environment": "production",
  1028. },
  1029. timestamp=self.day_ago + timedelta(hours=hour),
  1030. )
  1031. self.store_on_demand_metric(
  1032. hour * 60 * 24,
  1033. spec=spec_two,
  1034. additional_tags={
  1035. "customtag1": "bar",
  1036. "customtag2": "blue",
  1037. "environment": "production",
  1038. },
  1039. timestamp=self.day_ago + timedelta(hours=hour),
  1040. )
  1041. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1042. response = self.do_request(
  1043. data={
  1044. "project": self.project.id,
  1045. "start": iso_format(self.day_ago),
  1046. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1047. "interval": "1h",
  1048. "orderby": ["-count()"],
  1049. "query": query,
  1050. "yAxis": yAxis,
  1051. "field": [
  1052. "count()",
  1053. "count_web_vitals(measurements.lcp, good)",
  1054. "customtag1",
  1055. "customtag2",
  1056. ],
  1057. "topEvents": 5,
  1058. "dataset": "metricsEnhanced",
  1059. "useOnDemandMetrics": "true",
  1060. "onDemandType": "dynamic_query",
  1061. },
  1062. )
  1063. assert response.status_code == 200, response.content
  1064. groups = [
  1065. ("foo,red", "count()", 0.0, 1488.0),
  1066. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1067. ("bar,blue", "count()", 0.0, 0.0),
  1068. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1069. ]
  1070. assert len(response.data.keys()) == 2
  1071. for group_count in groups:
  1072. group, agg, row1, row2 = group_count
  1073. row_data = response.data[group][agg]["data"][:2]
  1074. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1075. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1076. assert response.data[group]["isMetricsExtractedData"]
  1077. def test_timeseries_on_demand_with_multiple_percentiles(self):
  1078. field = "p75(measurements.fcp)"
  1079. field_two = "p75(measurements.lcp)"
  1080. query = "transaction.duration:>=100"
  1081. spec = OnDemandMetricSpec(field=field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY)
  1082. spec_two = OnDemandMetricSpec(
  1083. field=field_two, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1084. )
  1085. assert (
  1086. spec._query_str_for_hash
  1087. == "event.measurements.fcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1088. )
  1089. assert (
  1090. spec_two._query_str_for_hash
  1091. == "event.measurements.lcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1092. )
  1093. for count in range(0, 4):
  1094. self.store_on_demand_metric(
  1095. count * 100,
  1096. spec=spec,
  1097. timestamp=self.day_ago + timedelta(hours=1),
  1098. )
  1099. self.store_on_demand_metric(
  1100. count * 200.0,
  1101. spec=spec_two,
  1102. timestamp=self.day_ago + timedelta(hours=1),
  1103. )
  1104. yAxis = [field, field_two]
  1105. response = self.do_request(
  1106. data={
  1107. "project": self.project.id,
  1108. "start": iso_format(self.day_ago),
  1109. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1110. "interval": "1h",
  1111. "orderby": [field],
  1112. "query": query,
  1113. "yAxis": yAxis,
  1114. "dataset": "metricsEnhanced",
  1115. "useOnDemandMetrics": "true",
  1116. "onDemandType": "dynamic_query",
  1117. },
  1118. )
  1119. assert response.status_code == 200, response.content
  1120. assert response.data["p75(measurements.fcp)"]["meta"]["isMetricsExtractedData"]
  1121. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1122. assert [attrs for time, attrs in response.data["p75(measurements.fcp)"]["data"]] == [
  1123. [{"count": 0}],
  1124. [{"count": 225.0}],
  1125. ]
  1126. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsExtractedData"]
  1127. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1128. assert [attrs for time, attrs in response.data["p75(measurements.lcp)"]["data"]] == [
  1129. [{"count": 0}],
  1130. [{"count": 450.0}],
  1131. ]
  1132. def test_apdex_issue(self):
  1133. field = "apdex(300)"
  1134. groupbys = ["group_tag"]
  1135. query = "transaction.duration:>=100"
  1136. spec = OnDemandMetricSpec(
  1137. field=field,
  1138. groupbys=groupbys,
  1139. query=query,
  1140. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1141. )
  1142. for hour in range(0, 5):
  1143. self.store_on_demand_metric(
  1144. 1,
  1145. spec=spec,
  1146. additional_tags={
  1147. "group_tag": "group_one",
  1148. "environment": "production",
  1149. "satisfaction": "tolerable",
  1150. },
  1151. timestamp=self.day_ago + timedelta(hours=hour),
  1152. )
  1153. self.store_on_demand_metric(
  1154. 1,
  1155. spec=spec,
  1156. additional_tags={
  1157. "group_tag": "group_two",
  1158. "environment": "production",
  1159. "satisfaction": "satisfactory",
  1160. },
  1161. timestamp=self.day_ago + timedelta(hours=hour),
  1162. )
  1163. response = self.do_request(
  1164. data={
  1165. "dataset": "metricsEnhanced",
  1166. "environment": "production",
  1167. "excludeOther": 1,
  1168. "field": [field, "group_tag"],
  1169. "start": iso_format(self.day_ago),
  1170. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1171. "interval": "1h",
  1172. "orderby": f"-{field}",
  1173. "partial": 1,
  1174. "project": self.project.id,
  1175. "query": query,
  1176. "topEvents": 5,
  1177. "yAxis": field,
  1178. "onDemandType": "dynamic_query",
  1179. "useOnDemandMetrics": "true",
  1180. },
  1181. )
  1182. assert response.status_code == 200, response.content
  1183. assert response.data["group_one"]["meta"]["isMetricsExtractedData"] is True
  1184. assert [attrs for time, attrs in response.data["group_one"]["data"]] == [
  1185. [{"count": 0.5}],
  1186. [{"count": 0.5}],
  1187. ]
  1188. def test_glob_http_referer_on_demand(self):
  1189. agg = "count()"
  1190. network_id_tag = "networkId"
  1191. url = "https://sentry.io"
  1192. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1193. spec = OnDemandMetricSpec(
  1194. field=agg,
  1195. groupbys=[network_id_tag],
  1196. query=query,
  1197. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1198. )
  1199. assert spec.to_metric_spec(self.project) == {
  1200. "category": "transaction",
  1201. "mri": "c:transactions/on_demand@none",
  1202. "field": None,
  1203. "tags": [
  1204. {"key": "query_hash", "value": "ac241f56"},
  1205. {"key": "networkId", "field": "event.tags.networkId"},
  1206. {"key": "environment", "field": "event.environment"},
  1207. ],
  1208. "condition": {
  1209. "op": "and",
  1210. "inner": [
  1211. {
  1212. "op": "glob",
  1213. "name": "event.request.url",
  1214. "value": ["https://sentry.io/*/foo/bar/*"],
  1215. },
  1216. {
  1217. "op": "glob",
  1218. "name": "event.request.headers.Referer",
  1219. "value": ["https://sentry.io/*/bar/*"],
  1220. },
  1221. ],
  1222. },
  1223. }
  1224. for hour in range(0, 5):
  1225. self.store_on_demand_metric(
  1226. 1,
  1227. spec=spec,
  1228. additional_tags={network_id_tag: "1234"},
  1229. timestamp=self.day_ago + timedelta(hours=hour),
  1230. )
  1231. self.store_on_demand_metric(
  1232. 1,
  1233. spec=spec,
  1234. additional_tags={network_id_tag: "5678"},
  1235. timestamp=self.day_ago + timedelta(hours=hour),
  1236. )
  1237. response = self.do_request(
  1238. data={
  1239. "dataset": "metricsEnhanced",
  1240. "field": [network_id_tag, agg],
  1241. "start": iso_format(self.day_ago),
  1242. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1243. "onDemandType": "dynamic_query",
  1244. "orderby": f"-{agg}",
  1245. "interval": "1d",
  1246. "partial": 1,
  1247. "query": query,
  1248. "referrer": "api.dashboards.widget.bar-chart",
  1249. "project": self.project.id,
  1250. "topEvents": 2,
  1251. "useOnDemandMetrics": "true",
  1252. "yAxis": agg,
  1253. },
  1254. )
  1255. assert response.status_code == 200, response.content
  1256. for datum in response.data.values():
  1257. assert datum["meta"] == {
  1258. "dataset": "metricsEnhanced",
  1259. "datasetReason": "unchanged",
  1260. "fields": {},
  1261. "isMetricsData": False,
  1262. "isMetricsExtractedData": True,
  1263. "tips": {},
  1264. "units": {},
  1265. }
  1266. def _test_is_metrics_extracted_data(
  1267. self, params: dict[str, Any], expected_on_demand_query: bool, dataset: str
  1268. ) -> None:
  1269. spec = OnDemandMetricSpec(
  1270. field="count()",
  1271. query="transaction.duration:>1s",
  1272. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1273. )
  1274. self.store_on_demand_metric(1, spec=spec)
  1275. response = self.do_request(params)
  1276. assert response.status_code == 200, response.content
  1277. meta = response.data["meta"]
  1278. # This is the main thing we want to test for
  1279. assert meta.get("isMetricsExtractedData", False) is expected_on_demand_query
  1280. assert meta["dataset"] == dataset
  1281. return meta
  1282. def test_is_metrics_extracted_data_is_included(self):
  1283. self._test_is_metrics_extracted_data(
  1284. {
  1285. "dataset": "metricsEnhanced",
  1286. "query": "transaction.duration:>=91",
  1287. "useOnDemandMetrics": "true",
  1288. "yAxis": "count()",
  1289. },
  1290. expected_on_demand_query=True,
  1291. dataset="metricsEnhanced",
  1292. )
  1293. def test_group_by_transaction(self):
  1294. field = "count()"
  1295. groupbys = ["transaction"]
  1296. query = "transaction.duration:>=100"
  1297. spec = OnDemandMetricSpec(
  1298. field=field,
  1299. groupbys=groupbys,
  1300. query=query,
  1301. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1302. )
  1303. for hour in range(0, 2):
  1304. self.store_on_demand_metric(
  1305. (hour + 1) * 5,
  1306. spec=spec,
  1307. additional_tags={
  1308. "transaction": "/performance",
  1309. "environment": "production",
  1310. },
  1311. timestamp=self.day_ago + timedelta(hours=hour),
  1312. )
  1313. response = self.do_request(
  1314. data={
  1315. "dataset": "metricsEnhanced",
  1316. "environment": "production",
  1317. "excludeOther": 1,
  1318. "field": [field, "transaction"],
  1319. "start": iso_format(self.day_ago),
  1320. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1321. "interval": "1h",
  1322. "orderby": f"-{field}",
  1323. "partial": 1,
  1324. "project": self.project.id,
  1325. "query": query,
  1326. "topEvents": 5,
  1327. "yAxis": field,
  1328. "onDemandType": "dynamic_query",
  1329. "useOnDemandMetrics": "true",
  1330. },
  1331. )
  1332. assert response.status_code == 200, response.content
  1333. assert response.data["/performance"]["meta"]["isMetricsExtractedData"] is True
  1334. assert [attrs for time, attrs in response.data["/performance"]["data"]] == [
  1335. [{"count": 5.0}],
  1336. [{"count": 10.0}],
  1337. ]
  1338. def _setup_orderby_tests(self, query):
  1339. count_spec = OnDemandMetricSpec(
  1340. field="count()",
  1341. groupbys=["networkId"],
  1342. query=query,
  1343. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1344. )
  1345. p95_spec = OnDemandMetricSpec(
  1346. field="p95(transaction.duration)",
  1347. groupbys=["networkId"],
  1348. query=query,
  1349. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1350. )
  1351. for hour in range(0, 5):
  1352. self.store_on_demand_metric(
  1353. 1,
  1354. spec=count_spec,
  1355. additional_tags={"networkId": "1234"},
  1356. timestamp=self.day_ago + timedelta(hours=hour),
  1357. )
  1358. self.store_on_demand_metric(
  1359. 100,
  1360. spec=p95_spec,
  1361. additional_tags={"networkId": "1234"},
  1362. timestamp=self.day_ago + timedelta(hours=hour),
  1363. )
  1364. self.store_on_demand_metric(
  1365. 200,
  1366. spec=p95_spec,
  1367. additional_tags={"networkId": "5678"},
  1368. timestamp=self.day_ago + timedelta(hours=hour),
  1369. )
  1370. # Store twice as many 5678 so orderby puts it later
  1371. self.store_on_demand_metric(
  1372. 2,
  1373. spec=count_spec,
  1374. additional_tags={"networkId": "5678"},
  1375. timestamp=self.day_ago + timedelta(hours=hour),
  1376. )
  1377. def test_order_by_aggregate_top_events_desc(self):
  1378. url = "https://sentry.io"
  1379. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1380. self._setup_orderby_tests(query)
  1381. response = self.do_request(
  1382. data={
  1383. "dataset": "metricsEnhanced",
  1384. "field": ["networkId", "count()"],
  1385. "start": iso_format(self.day_ago),
  1386. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1387. "onDemandType": "dynamic_query",
  1388. "orderby": "-count()",
  1389. "interval": "1d",
  1390. "partial": 1,
  1391. "query": query,
  1392. "referrer": "api.dashboards.widget.bar-chart",
  1393. "project": self.project.id,
  1394. "topEvents": 2,
  1395. "useOnDemandMetrics": "true",
  1396. "yAxis": "count()",
  1397. },
  1398. )
  1399. assert response.status_code == 200, response.content
  1400. assert len(response.data) == 3
  1401. data1 = response.data["5678"]
  1402. assert data1["order"] == 0
  1403. assert data1["data"][0][1][0]["count"] == 10
  1404. data2 = response.data["1234"]
  1405. assert data2["order"] == 1
  1406. assert data2["data"][0][1][0]["count"] == 5
  1407. for datum in response.data.values():
  1408. assert datum["meta"] == {
  1409. "dataset": "metricsEnhanced",
  1410. "datasetReason": "unchanged",
  1411. "fields": {},
  1412. "isMetricsData": False,
  1413. "isMetricsExtractedData": True,
  1414. "tips": {},
  1415. "units": {},
  1416. }
  1417. def test_order_by_aggregate_top_events_asc(self):
  1418. url = "https://sentry.io"
  1419. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1420. self._setup_orderby_tests(query)
  1421. response = self.do_request(
  1422. data={
  1423. "dataset": "metricsEnhanced",
  1424. "field": ["networkId", "count()"],
  1425. "start": iso_format(self.day_ago),
  1426. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1427. "onDemandType": "dynamic_query",
  1428. "orderby": "count()",
  1429. "interval": "1d",
  1430. "partial": 1,
  1431. "query": query,
  1432. "referrer": "api.dashboards.widget.bar-chart",
  1433. "project": self.project.id,
  1434. "topEvents": 2,
  1435. "useOnDemandMetrics": "true",
  1436. "yAxis": "count()",
  1437. },
  1438. )
  1439. assert response.status_code == 200, response.content
  1440. assert len(response.data) == 3
  1441. data1 = response.data["1234"]
  1442. assert data1["order"] == 0
  1443. assert data1["data"][0][1][0]["count"] == 5
  1444. data2 = response.data["5678"]
  1445. assert data2["order"] == 1
  1446. assert data2["data"][0][1][0]["count"] == 10
  1447. for datum in response.data.values():
  1448. assert datum["meta"] == {
  1449. "dataset": "metricsEnhanced",
  1450. "datasetReason": "unchanged",
  1451. "fields": {},
  1452. "isMetricsData": False,
  1453. "isMetricsExtractedData": True,
  1454. "tips": {},
  1455. "units": {},
  1456. }
  1457. def test_order_by_aggregate_top_events_graph_different_aggregate(self):
  1458. url = "https://sentry.io"
  1459. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1460. self._setup_orderby_tests(query)
  1461. response = self.do_request(
  1462. data={
  1463. "dataset": "metricsEnhanced",
  1464. "field": ["networkId", "count()"],
  1465. "start": iso_format(self.day_ago),
  1466. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1467. "onDemandType": "dynamic_query",
  1468. "orderby": "count()",
  1469. "interval": "1d",
  1470. "partial": 1,
  1471. "query": query,
  1472. "referrer": "api.dashboards.widget.bar-chart",
  1473. "project": self.project.id,
  1474. "topEvents": 2,
  1475. "useOnDemandMetrics": "true",
  1476. "yAxis": "p95(transaction.duration)",
  1477. },
  1478. )
  1479. assert response.status_code == 200, response.content
  1480. assert len(response.data) == 3
  1481. data1 = response.data["1234"]
  1482. assert data1["order"] == 0
  1483. assert data1["data"][0][1][0]["count"] == 100
  1484. data2 = response.data["5678"]
  1485. assert data2["order"] == 1
  1486. assert data2["data"][0][1][0]["count"] == 200
  1487. for datum in response.data.values():
  1488. assert datum["meta"] == {
  1489. "dataset": "metricsEnhanced",
  1490. "datasetReason": "unchanged",
  1491. "fields": {},
  1492. "isMetricsData": False,
  1493. "isMetricsExtractedData": True,
  1494. "tips": {},
  1495. "units": {},
  1496. }
  1497. def test_cannot_order_by_tag(self):
  1498. url = "https://sentry.io"
  1499. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1500. self._setup_orderby_tests(query)
  1501. response = self.do_request(
  1502. data={
  1503. "dataset": "metrics",
  1504. "field": ["networkId", "count()"],
  1505. "start": iso_format(self.day_ago),
  1506. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1507. "onDemandType": "dynamic_query",
  1508. "orderby": "-networkId",
  1509. "interval": "1d",
  1510. "partial": 1,
  1511. "query": query,
  1512. "referrer": "api.dashboards.widget.bar-chart",
  1513. "project": self.project.id,
  1514. "topEvents": 2,
  1515. "useOnDemandMetrics": "true",
  1516. "yAxis": "count()",
  1517. },
  1518. )
  1519. assert response.status_code == 400, response.content
  1520. def test_order_by_two_aggregates(self):
  1521. url = "https://sentry.io"
  1522. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1523. self._setup_orderby_tests(query)
  1524. response = self.do_request(
  1525. data={
  1526. "dataset": "metrics",
  1527. "field": ["networkId", "count()", "p95(transaction.duration)"],
  1528. "start": iso_format(self.day_ago),
  1529. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1530. "onDemandType": "dynamic_query",
  1531. "orderby": ["count()", "p95(transaction.duration)"],
  1532. "interval": "1d",
  1533. "partial": 1,
  1534. "query": query,
  1535. "referrer": "api.dashboards.widget.bar-chart",
  1536. "project": self.project.id,
  1537. "topEvents": 2,
  1538. "useOnDemandMetrics": "true",
  1539. "yAxis": "p95(transaction.duration)",
  1540. },
  1541. )
  1542. assert response.status_code == 400, response.content