test_unmerge.py 20 KB

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