test_unmerge.py 20 KB

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