test_unmerge.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. from __future__ import annotations
  2. import functools
  3. import hashlib
  4. import itertools
  5. import logging
  6. import uuid
  7. from datetime import timedelta
  8. from unittest import mock
  9. from unittest.mock import patch
  10. from django.utils import timezone
  11. from sentry import eventstream, tagstore, tsdb
  12. from sentry.eventstore.models import Event
  13. from sentry.models.environment import Environment
  14. from sentry.models.group import Group
  15. from sentry.models.grouphash import GroupHash
  16. from sentry.models.grouprelease import GroupRelease
  17. from sentry.models.release import Release
  18. from sentry.models.userreport import UserReport
  19. from sentry.similarity import _make_index_backend, features
  20. from sentry.tasks.merge import merge_groups
  21. from sentry.tasks.unmerge import (
  22. get_caches,
  23. get_event_user_from_interface,
  24. get_fingerprint,
  25. get_group_backfill_attributes,
  26. get_group_creation_attributes,
  27. unmerge,
  28. )
  29. from sentry.testutils.cases import SnubaTestCase, TestCase
  30. from sentry.testutils.helpers.datetime import before_now, iso_format
  31. from sentry.testutils.helpers.features import with_feature
  32. from sentry.tsdb.base import TSDBModel
  33. from sentry.utils import redis
  34. # Use the default redis client as a cluster client in the similarity index
  35. index = _make_index_backend(redis.clusters.get("default").get_local_client(0))
  36. @patch.object(features, "index", new=index)
  37. class UnmergeTestCase(TestCase, SnubaTestCase):
  38. def test_get_fingerprint(self):
  39. assert (
  40. get_fingerprint(
  41. self.store_event(data={"message": "Hello world"}, project_id=self.project.id)
  42. )
  43. == hashlib.md5(b"Hello world").hexdigest()
  44. )
  45. assert (
  46. get_fingerprint(
  47. self.store_event(
  48. data={"message": "Hello world", "fingerprint": ["Not hello world"]},
  49. project_id=self.project.id,
  50. )
  51. )
  52. == hashlib.md5(b"Not hello world").hexdigest()
  53. )
  54. def test_get_group_creation_attributes(self):
  55. now = timezone.now().replace(microsecond=0)
  56. e1 = self.store_event(
  57. data={
  58. "fingerprint": ["group1"],
  59. "platform": "javascript",
  60. "message": "Hello from JavaScript",
  61. "type": "default",
  62. "level": "info",
  63. "tags": {"logger": "javascript"},
  64. "timestamp": iso_format(now),
  65. },
  66. project_id=self.project.id,
  67. )
  68. e2 = self.store_event(
  69. data={
  70. "fingerprint": ["group1"],
  71. "platform": "python",
  72. "message": "Hello from Python",
  73. "type": "default",
  74. "level": "error",
  75. "tags": {"logger": "python"},
  76. "timestamp": iso_format(now),
  77. },
  78. project_id=self.project.id,
  79. )
  80. e3 = self.store_event(
  81. data={
  82. "fingerprint": ["group1"],
  83. "platform": "java",
  84. "message": "Hello from Java",
  85. "type": "default",
  86. "level": "debug",
  87. "tags": {"logger": "java"},
  88. "timestamp": iso_format(now),
  89. },
  90. project_id=self.project.id,
  91. )
  92. events = [e1, e2, e3]
  93. assert get_group_creation_attributes(get_caches(), e1.group, events) == {
  94. "active_at": now,
  95. "first_seen": now,
  96. "last_seen": now,
  97. "platform": "java",
  98. "message": "Hello from JavaScript",
  99. "level": logging.INFO,
  100. "logger": "java",
  101. "times_seen": 3,
  102. "first_release": None,
  103. "culprit": "",
  104. "data": {
  105. "type": "default",
  106. "last_received": e1.data["received"],
  107. "metadata": {"title": "Hello from JavaScript"},
  108. },
  109. "status": e1.group.status,
  110. "substatus": e1.group.substatus,
  111. }
  112. def test_get_group_backfill_attributes(self):
  113. now = timezone.now().replace(microsecond=0)
  114. assert get_group_backfill_attributes(
  115. get_caches(),
  116. Group(
  117. active_at=now,
  118. first_seen=now,
  119. last_seen=now,
  120. platform="javascript",
  121. message="Hello from JavaScript",
  122. level=logging.INFO,
  123. logger="javascript",
  124. times_seen=1,
  125. first_release=None,
  126. culprit="",
  127. data={"type": "default", "last_received": now.timestamp(), "metadata": {}},
  128. ),
  129. [
  130. self.store_event(
  131. data={
  132. "platform": "python",
  133. "message": "Hello from Python",
  134. "timestamp": iso_format(now - timedelta(hours=1)),
  135. "type": "default",
  136. "level": "debug",
  137. "tags": {"logger": "java"},
  138. },
  139. project_id=self.project.id,
  140. ),
  141. self.store_event(
  142. data={
  143. "platform": "java",
  144. "message": "Hello from Java",
  145. "timestamp": iso_format(now - timedelta(hours=2)),
  146. "type": "default",
  147. "level": "debug",
  148. "tags": {"logger": "java"},
  149. },
  150. project_id=self.project.id,
  151. ),
  152. ],
  153. ) == {
  154. "active_at": now - timedelta(hours=2),
  155. "first_seen": now - timedelta(hours=2),
  156. "platform": "java",
  157. "logger": "java",
  158. "times_seen": 3,
  159. "first_release": None,
  160. }
  161. @with_feature("projects:similarity-indexing")
  162. @mock.patch("sentry.analytics.record")
  163. def test_unmerge(self, mock_record):
  164. now = before_now(minutes=5).replace(microsecond=0)
  165. def time_from_now(offset=0):
  166. return now + timedelta(seconds=offset)
  167. project = self.create_project()
  168. project.date_added = timezone.now() - timedelta(minutes=10)
  169. project.save()
  170. sequence = itertools.count(0)
  171. tag_values = itertools.cycle(["red", "green", "blue"])
  172. user_values = itertools.cycle([{"id": 1}, {"id": 2}])
  173. def create_message_event(
  174. template, parameters, environment, release, fingerprint="group1"
  175. ) -> Event:
  176. i = next(sequence)
  177. event_id = uuid.UUID(fields=(i, 0x0, 0x1000, 0x80, 0x80, 0x808080808080)).hex
  178. tags = [["color", next(tag_values)]]
  179. if release:
  180. tags.append(["sentry:release", release])
  181. event = self.store_event(
  182. data={
  183. "event_id": event_id,
  184. "message": template % parameters,
  185. "type": "default",
  186. "user": next(user_values),
  187. "tags": tags,
  188. "fingerprint": [fingerprint],
  189. "timestamp": iso_format(now + timedelta(seconds=i)),
  190. "environment": environment,
  191. "release": release,
  192. },
  193. project_id=project.id,
  194. )
  195. UserReport.objects.create(
  196. project_id=project.id,
  197. group_id=event.group.id,
  198. event_id=event_id,
  199. name="Log Hat",
  200. email="ceo@corptron.com",
  201. comments="Quack",
  202. )
  203. features.record([event])
  204. return event
  205. events: dict[str | None, list[Event]] = {}
  206. for event in (
  207. create_message_event(
  208. "This is message #%s.", i, environment="production", release="version"
  209. )
  210. for i in range(10)
  211. ):
  212. events.setdefault(get_fingerprint(event), []).append(event)
  213. for event in (
  214. create_message_event(
  215. "This is message #%s!",
  216. i,
  217. environment="production",
  218. release="version2",
  219. fingerprint="group2",
  220. )
  221. for i in range(10, 16)
  222. ):
  223. events.setdefault(get_fingerprint(event), []).append(event)
  224. event = create_message_event(
  225. "This is message #%s!",
  226. 17,
  227. environment="staging",
  228. release="version3",
  229. fingerprint="group3",
  230. )
  231. events.setdefault(get_fingerprint(event), []).append(event)
  232. merge_source, source, destination = list(Group.objects.all())
  233. assert len(events) == 3
  234. assert sum(len(x) for x in events.values()) == 17
  235. production_environment = Environment.objects.get(
  236. organization_id=project.organization_id, name="production"
  237. )
  238. with self.tasks():
  239. eventstream_state = eventstream.backend.start_merge(
  240. project.id, [merge_source.id], source.id
  241. )
  242. merge_groups.delay([merge_source.id], source.id)
  243. eventstream.backend.end_merge(eventstream_state)
  244. assert {
  245. (gtv.value, gtv.times_seen)
  246. for gtv in tagstore.backend.get_group_tag_values(
  247. source,
  248. production_environment.id,
  249. "color",
  250. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  251. )
  252. } == {("red", 6), ("green", 5), ("blue", 5)}
  253. similar_items = features.compare(source)
  254. assert len(similar_items) == 2
  255. assert similar_items[0][0] == source.id
  256. assert similar_items[0][1]["message:message:character-shingles"] == 1.0
  257. assert similar_items[1][0] == destination.id
  258. assert similar_items[1][1]["message:message:character-shingles"] < 1.0
  259. with self.tasks():
  260. unmerge.delay(
  261. project.id, source.id, destination.id, [list(events.keys())[0]], None, batch_size=5
  262. )
  263. assert (
  264. list(
  265. Group.objects.filter(id=merge_source.id).values_list(
  266. "times_seen", "first_seen", "last_seen"
  267. )
  268. )
  269. == []
  270. )
  271. assert list(
  272. Group.objects.filter(id=source.id).values_list("times_seen", "first_seen", "last_seen")
  273. ) == [(6, time_from_now(10), time_from_now(15))]
  274. assert list(
  275. Group.objects.filter(id=destination.id).values_list(
  276. "times_seen", "first_seen", "last_seen"
  277. )
  278. ) == [(11, time_from_now(0), time_from_now(16))]
  279. assert source.id != destination.id
  280. assert source.project == destination.project
  281. destination_event_ids = set(map(lambda event: event.event_id, list(events.values())[1]))
  282. assert destination_event_ids == set(
  283. UserReport.objects.filter(group_id=source.id).values_list("event_id", flat=True)
  284. )
  285. assert list(
  286. GroupHash.objects.filter(group_id=source.id).values_list("hash", flat=True)
  287. ) == [list(events.keys())[1]]
  288. assert set(
  289. GroupRelease.objects.filter(group_id=source.id).values_list(
  290. "environment", "first_seen", "last_seen"
  291. )
  292. ) == {("production", time_from_now(10), time_from_now(15))}
  293. assert {
  294. (gtv.value, gtv.times_seen)
  295. for gtv in tagstore.backend.get_group_tag_values(
  296. destination,
  297. production_environment.id,
  298. "color",
  299. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  300. )
  301. } == {("red", 4), ("green", 3), ("blue", 3)}
  302. destination_event_ids = set(
  303. map(lambda event: event.event_id, list(events.values())[0] + list(events.values())[2])
  304. )
  305. assert destination_event_ids == set(
  306. UserReport.objects.filter(group_id=destination.id).values_list("event_id", flat=True)
  307. )
  308. assert set(
  309. GroupHash.objects.filter(group_id=destination.id).values_list("hash", flat=True)
  310. ) == {list(events.keys())[0], list(events.keys())[2]}
  311. assert set(
  312. GroupRelease.objects.filter(group_id=destination.id).values_list(
  313. "environment", "first_seen", "last_seen"
  314. )
  315. ) == {
  316. ("production", time_from_now(0), time_from_now(9)),
  317. ("staging", time_from_now(16), time_from_now(16)),
  318. }
  319. assert {
  320. (gtk.value, gtk.times_seen)
  321. for gtk in tagstore.backend.get_group_tag_values(
  322. destination,
  323. production_environment.id,
  324. "color",
  325. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  326. )
  327. } == {("red", 4), ("blue", 3), ("green", 3)}
  328. rollup_duration = 3600
  329. time_series = tsdb.backend.get_range(
  330. TSDBModel.group,
  331. [source.id, destination.id],
  332. now - timedelta(seconds=rollup_duration),
  333. time_from_now(17),
  334. rollup_duration,
  335. tenant_ids={"referrer": "get_range", "organization_id": 1},
  336. )
  337. environment_time_series = tsdb.backend.get_range(
  338. TSDBModel.group,
  339. [source.id, destination.id],
  340. now - timedelta(seconds=rollup_duration),
  341. time_from_now(17),
  342. rollup_duration,
  343. environment_ids=[production_environment.id],
  344. tenant_ids={"referrer": "get_range", "organization_id": 1},
  345. )
  346. def get_expected_series_values(rollup, events, function=None):
  347. if function is None:
  348. def function(aggregate, event):
  349. return (aggregate if aggregate is not None else 0) + 1
  350. expected: dict[float, float] = {}
  351. for event in events:
  352. k = float((event.datetime.timestamp() // rollup_duration) * rollup_duration)
  353. expected[k] = function(expected.get(k), event)
  354. return expected
  355. def assert_series_contains(expected, actual, default=0):
  356. actual = dict(actual)
  357. for key, value in expected.items():
  358. assert actual.get(key, 0) == value
  359. for key in set(actual.keys()) - set(expected.keys()):
  360. assert actual.get(key, 0) == default
  361. assert_series_contains(
  362. get_expected_series_values(rollup_duration, list(events.values())[1]),
  363. time_series[source.id],
  364. 0,
  365. )
  366. assert_series_contains(
  367. get_expected_series_values(
  368. rollup_duration, list(events.values())[0] + list(events.values())[2]
  369. ),
  370. time_series[destination.id],
  371. 0,
  372. )
  373. assert_series_contains(
  374. get_expected_series_values(rollup_duration, list(events.values())[1]),
  375. environment_time_series[source.id],
  376. 0,
  377. )
  378. assert_series_contains(
  379. get_expected_series_values(
  380. rollup_duration, list(events.values())[0][:-1] + list(events.values())[2]
  381. ),
  382. environment_time_series[destination.id],
  383. 0,
  384. )
  385. time_series = tsdb.backend.get_distinct_counts_series(
  386. TSDBModel.users_affected_by_group,
  387. [source.id, destination.id],
  388. now - timedelta(seconds=rollup_duration),
  389. time_from_now(17),
  390. rollup_duration,
  391. tenant_ids={"referrer": "r", "organization_id": 1234},
  392. )
  393. environment_time_series = tsdb.backend.get_distinct_counts_series(
  394. TSDBModel.users_affected_by_group,
  395. [source.id, destination.id],
  396. now - timedelta(seconds=rollup_duration),
  397. time_from_now(17),
  398. rollup_duration,
  399. environment_id=production_environment.id,
  400. tenant_ids={"referrer": "r", "organization_id": 1234},
  401. )
  402. def collect_by_user_tag(aggregate, event):
  403. aggregate = aggregate if aggregate is not None else set()
  404. aggregate.add(
  405. get_event_user_from_interface(event.data["user"], event.group.project).tag_value
  406. )
  407. mock_record.assert_called_with(
  408. "eventuser_endpoint.request",
  409. project_id=event.group.project.id,
  410. endpoint="sentry.tasks.unmerge.get_event_user_from_interface",
  411. )
  412. return aggregate
  413. for series in [time_series, environment_time_series]:
  414. assert_series_contains(
  415. {
  416. timestamp: len(values)
  417. for timestamp, values in get_expected_series_values(
  418. rollup_duration, list(events.values())[1], collect_by_user_tag
  419. ).items()
  420. },
  421. series[source.id],
  422. )
  423. assert_series_contains(
  424. {
  425. timestamp: len(values)
  426. for timestamp, values in get_expected_series_values(
  427. rollup_duration,
  428. list(events.values())[0] + list(events.values())[2],
  429. collect_by_user_tag,
  430. ).items()
  431. },
  432. time_series[destination.id],
  433. )
  434. def strip_zeroes(data):
  435. for group_id, series in data.items():
  436. for _, values in series:
  437. for key, val in list(values.items()):
  438. if val == 0:
  439. values.pop(key)
  440. return data
  441. def collect_by_release(group, aggregate, event):
  442. aggregate = aggregate if aggregate is not None else {}
  443. release = event.get_tag("sentry:release")
  444. if not release:
  445. return aggregate
  446. release = GroupRelease.objects.get(
  447. group_id=group.id,
  448. environment=event.data["environment"],
  449. release_id=Release.objects.get(
  450. organization_id=project.organization_id, version=release
  451. ).id,
  452. ).id
  453. aggregate[release] = aggregate.get(release, 0) + 1
  454. return aggregate
  455. items = {}
  456. for i in [source.id, destination.id]:
  457. items[i] = list(GroupRelease.objects.filter(group_id=i).values_list("id", flat=True))
  458. time_series = strip_zeroes(
  459. tsdb.backend.get_frequency_series(
  460. TSDBModel.frequent_releases_by_group,
  461. items,
  462. now - timedelta(seconds=rollup_duration),
  463. time_from_now(17),
  464. rollup_duration,
  465. tenant_ids={"referrer": "r", "organization_id": 1234},
  466. )
  467. )
  468. assert_series_contains(
  469. get_expected_series_values(
  470. rollup_duration,
  471. list(events.values())[1],
  472. functools.partial(collect_by_release, source),
  473. ),
  474. time_series[source.id],
  475. {},
  476. )
  477. assert_series_contains(
  478. get_expected_series_values(
  479. rollup_duration,
  480. list(events.values())[0] + list(events.values())[2],
  481. functools.partial(collect_by_release, destination),
  482. ),
  483. time_series[destination.id],
  484. {},
  485. )
  486. items = {}
  487. for i in [source.id, destination.id]:
  488. items[i] = list(Environment.objects.all().values_list("id", flat=True))
  489. time_series = strip_zeroes(
  490. tsdb.backend.get_frequency_series(
  491. TSDBModel.frequent_environments_by_group,
  492. items,
  493. now - timedelta(seconds=rollup_duration),
  494. time_from_now(17),
  495. rollup_duration,
  496. tenant_ids={"referrer": "r", "organization_id": 1234},
  497. )
  498. )
  499. def collect_by_environment(aggregate, event):
  500. aggregate = aggregate if aggregate is not None else {}
  501. environment = Environment.objects.get(
  502. organization_id=project.organization_id, name=event.data["environment"]
  503. ).id
  504. aggregate[environment] = aggregate.get(environment, 0) + 1
  505. return aggregate
  506. assert_series_contains(
  507. get_expected_series_values(
  508. rollup_duration, list(events.values())[1], collect_by_environment
  509. ),
  510. time_series[source.id],
  511. {},
  512. )
  513. assert_series_contains(
  514. get_expected_series_values(
  515. rollup_duration,
  516. list(events.values())[0] + list(events.values())[2],
  517. collect_by_environment,
  518. ),
  519. time_series[destination.id],
  520. {},
  521. )
  522. source_similar_items = features.compare(source)
  523. assert source_similar_items[0] == (
  524. source.id,
  525. {
  526. "exception:message:character-shingles": None,
  527. "exception:stacktrace:application-chunks": None,
  528. "exception:stacktrace:pairs": None,
  529. "message:message:character-shingles": 1.0,
  530. },
  531. )
  532. assert source_similar_items[1][0] == destination.id
  533. assert source_similar_items[1][1]["message:message:character-shingles"] < 1.0
  534. destination_similar_items = features.compare(destination)
  535. assert destination_similar_items[0] == (
  536. destination.id,
  537. {
  538. "exception:message:character-shingles": None,
  539. "exception:stacktrace:application-chunks": None,
  540. "exception:stacktrace:pairs": None,
  541. "message:message:character-shingles": 1.0,
  542. },
  543. )
  544. assert destination_similar_items[1][0] == source.id
  545. assert destination_similar_items[1][1]["message:message:character-shingles"] < 1.0