test_unmerge.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. from __future__ import annotations
  2. import functools
  3. import hashlib
  4. import itertools
  5. import logging
  6. import uuid
  7. from datetime import datetime, timedelta, timezone
  8. from unittest import mock
  9. from unittest.mock import patch
  10. from django.utils import timezone as django_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 = datetime.now(timezone.utc).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(), 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. "score": Group.calculate_score(3, now),
  101. "logger": "java",
  102. "times_seen": 3,
  103. "first_release": None,
  104. "culprit": "",
  105. "data": {
  106. "type": "default",
  107. "last_received": e1.data["received"],
  108. "metadata": {"title": "Hello from JavaScript"},
  109. },
  110. }
  111. def test_get_group_backfill_attributes(self):
  112. now = datetime.now(timezone.utc).replace(microsecond=0)
  113. assert get_group_backfill_attributes(
  114. get_caches(),
  115. Group(
  116. active_at=now,
  117. first_seen=now,
  118. last_seen=now,
  119. platform="javascript",
  120. message="Hello from JavaScript",
  121. level=logging.INFO,
  122. score=Group.calculate_score(3, now),
  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. "score": Group.calculate_score(3, now),
  158. "logger": "java",
  159. "times_seen": 3,
  160. "first_release": None,
  161. }
  162. @with_feature("projects:similarity-indexing")
  163. @mock.patch("sentry.analytics.record")
  164. def test_unmerge(self, mock_record):
  165. now = before_now(minutes=5).replace(microsecond=0)
  166. def time_from_now(offset=0):
  167. return now + timedelta(seconds=offset)
  168. project = self.create_project()
  169. project.date_added = django_timezone.now() - timedelta(minutes=10)
  170. project.save()
  171. sequence = itertools.count(0)
  172. tag_values = itertools.cycle(["red", "green", "blue"])
  173. user_values = itertools.cycle([{"id": 1}, {"id": 2}])
  174. def create_message_event(
  175. template, parameters, environment, release, fingerprint="group1"
  176. ) -> Event:
  177. i = next(sequence)
  178. event_id = uuid.UUID(fields=(i, 0x0, 0x1000, 0x80, 0x80, 0x808080808080)).hex
  179. tags = [["color", next(tag_values)]]
  180. if release:
  181. tags.append(["sentry:release", release])
  182. event = self.store_event(
  183. data={
  184. "event_id": event_id,
  185. "message": template % parameters,
  186. "type": "default",
  187. "user": next(user_values),
  188. "tags": tags,
  189. "fingerprint": [fingerprint],
  190. "timestamp": iso_format(now + timedelta(seconds=i)),
  191. "environment": environment,
  192. "release": release,
  193. },
  194. project_id=project.id,
  195. )
  196. UserReport.objects.create(
  197. project_id=project.id,
  198. group_id=event.group.id,
  199. event_id=event_id,
  200. name="Log Hat",
  201. email="ceo@corptron.com",
  202. comments="Quack",
  203. )
  204. features.record([event])
  205. return event
  206. events: dict[str | None, list[Event]] = {}
  207. for event in (
  208. create_message_event(
  209. "This is message #%s.", i, environment="production", release="version"
  210. )
  211. for i in range(10)
  212. ):
  213. events.setdefault(get_fingerprint(event), []).append(event)
  214. for event in (
  215. create_message_event(
  216. "This is message #%s!",
  217. i,
  218. environment="production",
  219. release="version2",
  220. fingerprint="group2",
  221. )
  222. for i in range(10, 16)
  223. ):
  224. events.setdefault(get_fingerprint(event), []).append(event)
  225. event = create_message_event(
  226. "This is message #%s!",
  227. 17,
  228. environment="staging",
  229. release="version3",
  230. fingerprint="group3",
  231. )
  232. events.setdefault(get_fingerprint(event), []).append(event)
  233. merge_source, source, destination = list(Group.objects.all())
  234. assert len(events) == 3
  235. assert sum(len(x) for x in events.values()) == 17
  236. production_environment = Environment.objects.get(
  237. organization_id=project.organization_id, name="production"
  238. )
  239. with self.tasks():
  240. eventstream_state = eventstream.backend.start_merge(
  241. project.id, [merge_source.id], source.id
  242. )
  243. merge_groups.delay([merge_source.id], source.id)
  244. eventstream.backend.end_merge(eventstream_state)
  245. assert {
  246. (gtv.value, gtv.times_seen)
  247. for gtv in tagstore.backend.get_group_tag_values(
  248. source,
  249. production_environment.id,
  250. "color",
  251. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  252. )
  253. } == {("red", 6), ("green", 5), ("blue", 5)}
  254. similar_items = features.compare(source)
  255. assert len(similar_items) == 2
  256. assert similar_items[0][0] == source.id
  257. assert similar_items[0][1]["message:message:character-shingles"] == 1.0
  258. assert similar_items[1][0] == destination.id
  259. assert similar_items[1][1]["message:message:character-shingles"] < 1.0
  260. with self.tasks():
  261. unmerge.delay(
  262. project.id, source.id, destination.id, [list(events.keys())[0]], None, batch_size=5
  263. )
  264. assert (
  265. list(
  266. Group.objects.filter(id=merge_source.id).values_list(
  267. "times_seen", "first_seen", "last_seen"
  268. )
  269. )
  270. == []
  271. )
  272. assert list(
  273. Group.objects.filter(id=source.id).values_list("times_seen", "first_seen", "last_seen")
  274. ) == [(6, time_from_now(10), time_from_now(15))]
  275. assert list(
  276. Group.objects.filter(id=destination.id).values_list(
  277. "times_seen", "first_seen", "last_seen"
  278. )
  279. ) == [(11, time_from_now(0), time_from_now(16))]
  280. assert source.id != destination.id
  281. assert source.project == destination.project
  282. destination_event_ids = set(map(lambda event: event.event_id, list(events.values())[1]))
  283. assert destination_event_ids == set(
  284. UserReport.objects.filter(group_id=source.id).values_list("event_id", flat=True)
  285. )
  286. assert list(
  287. GroupHash.objects.filter(group_id=source.id).values_list("hash", flat=True)
  288. ) == [list(events.keys())[1]]
  289. assert set(
  290. GroupRelease.objects.filter(group_id=source.id).values_list(
  291. "environment", "first_seen", "last_seen"
  292. )
  293. ) == {("production", time_from_now(10), time_from_now(15))}
  294. assert {
  295. (gtv.value, gtv.times_seen)
  296. for gtv in tagstore.backend.get_group_tag_values(
  297. destination,
  298. production_environment.id,
  299. "color",
  300. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  301. )
  302. } == {("red", 4), ("green", 3), ("blue", 3)}
  303. destination_event_ids = set(
  304. map(lambda event: event.event_id, list(events.values())[0] + list(events.values())[2])
  305. )
  306. assert destination_event_ids == set(
  307. UserReport.objects.filter(group_id=destination.id).values_list("event_id", flat=True)
  308. )
  309. assert set(
  310. GroupHash.objects.filter(group_id=destination.id).values_list("hash", flat=True)
  311. ) == {list(events.keys())[0], list(events.keys())[2]}
  312. assert set(
  313. GroupRelease.objects.filter(group_id=destination.id).values_list(
  314. "environment", "first_seen", "last_seen"
  315. )
  316. ) == {
  317. ("production", time_from_now(0), time_from_now(9)),
  318. ("staging", time_from_now(16), time_from_now(16)),
  319. }
  320. assert {
  321. (gtk.value, gtk.times_seen)
  322. for gtk in tagstore.backend.get_group_tag_values(
  323. destination,
  324. production_environment.id,
  325. "color",
  326. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  327. )
  328. } == {("red", 4), ("blue", 3), ("green", 3)}
  329. rollup_duration = 3600
  330. time_series = tsdb.backend.get_range(
  331. TSDBModel.group,
  332. [source.id, destination.id],
  333. now - timedelta(seconds=rollup_duration),
  334. time_from_now(17),
  335. rollup_duration,
  336. tenant_ids={"referrer": "get_range", "organization_id": 1},
  337. )
  338. environment_time_series = tsdb.backend.get_range(
  339. TSDBModel.group,
  340. [source.id, destination.id],
  341. now - timedelta(seconds=rollup_duration),
  342. time_from_now(17),
  343. rollup_duration,
  344. environment_ids=[production_environment.id],
  345. tenant_ids={"referrer": "get_range", "organization_id": 1},
  346. )
  347. def get_expected_series_values(rollup, events, function=None):
  348. if function is None:
  349. def function(aggregate, event):
  350. return (aggregate if aggregate is not None else 0) + 1
  351. expected: dict[float, float] = {}
  352. for event in events:
  353. k = float((event.datetime.timestamp() // rollup_duration) * rollup_duration)
  354. expected[k] = function(expected.get(k), event)
  355. return expected
  356. def assert_series_contains(expected, actual, default=0):
  357. actual = dict(actual)
  358. for key, value in expected.items():
  359. assert actual.get(key, 0) == value
  360. for key in set(actual.keys()) - set(expected.keys()):
  361. assert actual.get(key, 0) == default
  362. assert_series_contains(
  363. get_expected_series_values(rollup_duration, list(events.values())[1]),
  364. time_series[source.id],
  365. 0,
  366. )
  367. assert_series_contains(
  368. get_expected_series_values(
  369. rollup_duration, list(events.values())[0] + list(events.values())[2]
  370. ),
  371. time_series[destination.id],
  372. 0,
  373. )
  374. assert_series_contains(
  375. get_expected_series_values(rollup_duration, list(events.values())[1]),
  376. environment_time_series[source.id],
  377. 0,
  378. )
  379. assert_series_contains(
  380. get_expected_series_values(
  381. rollup_duration, list(events.values())[0][:-1] + list(events.values())[2]
  382. ),
  383. environment_time_series[destination.id],
  384. 0,
  385. )
  386. time_series = tsdb.backend.get_distinct_counts_series(
  387. TSDBModel.users_affected_by_group,
  388. [source.id, destination.id],
  389. now - timedelta(seconds=rollup_duration),
  390. time_from_now(17),
  391. rollup_duration,
  392. tenant_ids={"referrer": "r", "organization_id": 1234},
  393. )
  394. environment_time_series = tsdb.backend.get_distinct_counts_series(
  395. TSDBModel.users_affected_by_group,
  396. [source.id, destination.id],
  397. now - timedelta(seconds=rollup_duration),
  398. time_from_now(17),
  399. rollup_duration,
  400. environment_id=production_environment.id,
  401. tenant_ids={"referrer": "r", "organization_id": 1234},
  402. )
  403. def collect_by_user_tag(aggregate, event):
  404. aggregate = aggregate if aggregate is not None else set()
  405. aggregate.add(
  406. get_event_user_from_interface(event.data["user"], event.group.project).tag_value
  407. )
  408. mock_record.assert_called_with(
  409. "eventuser_endpoint.request",
  410. project_id=event.group.project.id,
  411. endpoint="sentry.tasks.unmerge.get_event_user_from_interface",
  412. )
  413. return aggregate
  414. for series in [time_series, environment_time_series]:
  415. assert_series_contains(
  416. {
  417. timestamp: len(values)
  418. for timestamp, values in get_expected_series_values(
  419. rollup_duration, list(events.values())[1], collect_by_user_tag
  420. ).items()
  421. },
  422. series[source.id],
  423. )
  424. assert_series_contains(
  425. {
  426. timestamp: len(values)
  427. for timestamp, values in get_expected_series_values(
  428. rollup_duration,
  429. list(events.values())[0] + list(events.values())[2],
  430. collect_by_user_tag,
  431. ).items()
  432. },
  433. time_series[destination.id],
  434. )
  435. def strip_zeroes(data):
  436. for group_id, series in data.items():
  437. for _, values in series:
  438. for key, val in list(values.items()):
  439. if val == 0:
  440. values.pop(key)
  441. return data
  442. def collect_by_release(group, aggregate, event):
  443. aggregate = aggregate if aggregate is not None else {}
  444. release = event.get_tag("sentry:release")
  445. if not release:
  446. return aggregate
  447. release = GroupRelease.objects.get(
  448. group_id=group.id,
  449. environment=event.data["environment"],
  450. release_id=Release.objects.get(
  451. organization_id=project.organization_id, version=release
  452. ).id,
  453. ).id
  454. aggregate[release] = aggregate.get(release, 0) + 1
  455. return aggregate
  456. items = {}
  457. for i in [source.id, destination.id]:
  458. items[i] = list(GroupRelease.objects.filter(group_id=i).values_list("id", flat=True))
  459. time_series = strip_zeroes(
  460. tsdb.backend.get_frequency_series(
  461. TSDBModel.frequent_releases_by_group,
  462. items,
  463. now - timedelta(seconds=rollup_duration),
  464. time_from_now(17),
  465. rollup_duration,
  466. tenant_ids={"referrer": "r", "organization_id": 1234},
  467. )
  468. )
  469. assert_series_contains(
  470. get_expected_series_values(
  471. rollup_duration,
  472. list(events.values())[1],
  473. functools.partial(collect_by_release, source),
  474. ),
  475. time_series[source.id],
  476. {},
  477. )
  478. assert_series_contains(
  479. get_expected_series_values(
  480. rollup_duration,
  481. list(events.values())[0] + list(events.values())[2],
  482. functools.partial(collect_by_release, destination),
  483. ),
  484. time_series[destination.id],
  485. {},
  486. )
  487. items = {}
  488. for i in [source.id, destination.id]:
  489. items[i] = list(Environment.objects.all().values_list("id", flat=True))
  490. time_series = strip_zeroes(
  491. tsdb.backend.get_frequency_series(
  492. TSDBModel.frequent_environments_by_group,
  493. items,
  494. now - timedelta(seconds=rollup_duration),
  495. time_from_now(17),
  496. rollup_duration,
  497. tenant_ids={"referrer": "r", "organization_id": 1234},
  498. )
  499. )
  500. def collect_by_environment(aggregate, event):
  501. aggregate = aggregate if aggregate is not None else {}
  502. environment = Environment.objects.get(
  503. organization_id=project.organization_id, name=event.data["environment"]
  504. ).id
  505. aggregate[environment] = aggregate.get(environment, 0) + 1
  506. return aggregate
  507. assert_series_contains(
  508. get_expected_series_values(
  509. rollup_duration, list(events.values())[1], collect_by_environment
  510. ),
  511. time_series[source.id],
  512. {},
  513. )
  514. assert_series_contains(
  515. get_expected_series_values(
  516. rollup_duration,
  517. list(events.values())[0] + list(events.values())[2],
  518. collect_by_environment,
  519. ),
  520. time_series[destination.id],
  521. {},
  522. )
  523. source_similar_items = features.compare(source)
  524. assert source_similar_items[0] == (
  525. source.id,
  526. {
  527. "exception:message:character-shingles": None,
  528. "exception:stacktrace:application-chunks": None,
  529. "exception:stacktrace:pairs": None,
  530. "message:message:character-shingles": 1.0,
  531. },
  532. )
  533. assert source_similar_items[1][0] == destination.id
  534. assert source_similar_items[1][1]["message:message:character-shingles"] < 1.0
  535. destination_similar_items = features.compare(destination)
  536. assert destination_similar_items[0] == (
  537. destination.id,
  538. {
  539. "exception:message:character-shingles": None,
  540. "exception:stacktrace:application-chunks": None,
  541. "exception:stacktrace:pairs": None,
  542. "message:message:character-shingles": 1.0,
  543. },
  544. )
  545. assert destination_similar_items[1][0] == source.id
  546. assert destination_similar_items[1][1]["message:message:character-shingles"] < 1.0