test_unmerge.py 22 KB

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