test_unmerge.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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(
  234. source,
  235. production_environment.id,
  236. "color",
  237. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  238. )
  239. } == {("red", 6), ("green", 5), ("blue", 5)}
  240. similar_items = features.compare(source)
  241. assert len(similar_items) == 2
  242. assert similar_items[0][0] == source.id
  243. assert similar_items[0][1]["message:message:character-shingles"] == 1.0
  244. assert similar_items[1][0] == destination.id
  245. assert similar_items[1][1]["message:message:character-shingles"] < 1.0
  246. with self.tasks():
  247. unmerge.delay(
  248. project.id, source.id, destination.id, [list(events.keys())[0]], None, batch_size=5
  249. )
  250. assert (
  251. list(
  252. Group.objects.filter(id=merge_source.id).values_list(
  253. "times_seen", "first_seen", "last_seen"
  254. )
  255. )
  256. == []
  257. )
  258. assert list(
  259. Group.objects.filter(id=source.id).values_list("times_seen", "first_seen", "last_seen")
  260. ) == [(6, time_from_now(10), time_from_now(15))]
  261. assert list(
  262. Group.objects.filter(id=destination.id).values_list(
  263. "times_seen", "first_seen", "last_seen"
  264. )
  265. ) == [(11, time_from_now(0), time_from_now(16))]
  266. assert source.id != destination.id
  267. assert source.project == destination.project
  268. destination_event_ids = set(map(lambda event: event.event_id, list(events.values())[1]))
  269. assert destination_event_ids == set(
  270. UserReport.objects.filter(group_id=source.id).values_list("event_id", flat=True)
  271. )
  272. assert list(
  273. GroupHash.objects.filter(group_id=source.id).values_list("hash", flat=True)
  274. ) == [list(events.keys())[1]]
  275. assert set(
  276. GroupRelease.objects.filter(group_id=source.id).values_list(
  277. "environment", "first_seen", "last_seen"
  278. )
  279. ) == {("production", time_from_now(10), time_from_now(15))}
  280. assert {
  281. (gtv.value, gtv.times_seen)
  282. for gtv in tagstore.get_group_tag_values(
  283. destination,
  284. production_environment.id,
  285. "color",
  286. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  287. )
  288. } == {("red", 4), ("green", 3), ("blue", 3)}
  289. destination_event_ids = set(
  290. map(lambda event: event.event_id, list(events.values())[0] + list(events.values())[2])
  291. )
  292. assert destination_event_ids == set(
  293. UserReport.objects.filter(group_id=destination.id).values_list("event_id", flat=True)
  294. )
  295. assert set(
  296. GroupHash.objects.filter(group_id=destination.id).values_list("hash", flat=True)
  297. ) == {list(events.keys())[0], list(events.keys())[2]}
  298. assert set(
  299. GroupRelease.objects.filter(group_id=destination.id).values_list(
  300. "environment", "first_seen", "last_seen"
  301. )
  302. ) == {
  303. ("production", time_from_now(0), time_from_now(9)),
  304. ("staging", time_from_now(16), time_from_now(16)),
  305. }
  306. assert {
  307. (gtk.value, gtk.times_seen)
  308. for gtk in tagstore.get_group_tag_values(
  309. destination,
  310. production_environment.id,
  311. "color",
  312. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  313. )
  314. } == {("red", 4), ("blue", 3), ("green", 3)}
  315. rollup_duration = 3600
  316. 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. tenant_ids={"referrer": "get_range", "organization_id": 1},
  323. )
  324. environment_time_series = tsdb.get_range(
  325. tsdb.models.group,
  326. [source.id, destination.id],
  327. now - timedelta(seconds=rollup_duration),
  328. time_from_now(17),
  329. rollup_duration,
  330. environment_ids=[production_environment.id],
  331. tenant_ids={"referrer": "get_range", "organization_id": 1},
  332. )
  333. def get_expected_series_values(rollup, events, function=None):
  334. if function is None:
  335. def function(aggregate, event):
  336. return (aggregate if aggregate is not None else 0) + 1
  337. expected = {}
  338. for event in events:
  339. k = float((to_timestamp(event.datetime) // rollup_duration) * rollup_duration)
  340. expected[k] = function(expected.get(k), event)
  341. return expected
  342. def assert_series_contains(expected, actual, default=0):
  343. actual = dict(actual)
  344. for key, value in expected.items():
  345. assert actual.get(key, 0) == value
  346. for key in set(actual.keys()) - set(expected.keys()):
  347. assert actual.get(key, 0) == default
  348. assert_series_contains(
  349. get_expected_series_values(rollup_duration, list(events.values())[1]),
  350. time_series[source.id],
  351. 0,
  352. )
  353. assert_series_contains(
  354. get_expected_series_values(
  355. rollup_duration, list(events.values())[0] + list(events.values())[2]
  356. ),
  357. time_series[destination.id],
  358. 0,
  359. )
  360. assert_series_contains(
  361. get_expected_series_values(rollup_duration, list(events.values())[1]),
  362. environment_time_series[source.id],
  363. 0,
  364. )
  365. assert_series_contains(
  366. get_expected_series_values(
  367. rollup_duration, list(events.values())[0][:-1] + list(events.values())[2]
  368. ),
  369. environment_time_series[destination.id],
  370. 0,
  371. )
  372. time_series = tsdb.get_distinct_counts_series(
  373. tsdb.models.users_affected_by_group,
  374. [source.id, destination.id],
  375. now - timedelta(seconds=rollup_duration),
  376. time_from_now(17),
  377. rollup_duration,
  378. tenant_ids={"referrer": "r", "organization_id": 1234},
  379. )
  380. environment_time_series = tsdb.get_distinct_counts_series(
  381. tsdb.models.users_affected_by_group,
  382. [source.id, destination.id],
  383. now - timedelta(seconds=rollup_duration),
  384. time_from_now(17),
  385. rollup_duration,
  386. environment_id=production_environment.id,
  387. tenant_ids={"referrer": "r", "organization_id": 1234},
  388. )
  389. def collect_by_user_tag(aggregate, event):
  390. aggregate = aggregate if aggregate is not None else set()
  391. aggregate.add(get_event_user_from_interface(event.data["user"]).tag_value)
  392. return aggregate
  393. for series in [time_series, environment_time_series]:
  394. assert_series_contains(
  395. {
  396. timestamp: len(values)
  397. for timestamp, values in get_expected_series_values(
  398. rollup_duration, list(events.values())[1], collect_by_user_tag
  399. ).items()
  400. },
  401. series[source.id],
  402. )
  403. assert_series_contains(
  404. {
  405. timestamp: len(values)
  406. for timestamp, values in get_expected_series_values(
  407. rollup_duration,
  408. list(events.values())[0] + list(events.values())[2],
  409. collect_by_user_tag,
  410. ).items()
  411. },
  412. time_series[destination.id],
  413. )
  414. def strip_zeroes(data):
  415. for group_id, series in data.items():
  416. for _, values in series:
  417. for key, val in list(values.items()):
  418. if val == 0:
  419. values.pop(key)
  420. return data
  421. def collect_by_release(group, aggregate, event):
  422. aggregate = aggregate if aggregate is not None else {}
  423. release = event.get_tag("sentry:release")
  424. if not release:
  425. return aggregate
  426. release = GroupRelease.objects.get(
  427. group_id=group.id,
  428. environment=event.data["environment"],
  429. release_id=Release.objects.get(
  430. organization_id=project.organization_id, version=release
  431. ).id,
  432. ).id
  433. aggregate[release] = aggregate.get(release, 0) + 1
  434. return aggregate
  435. items = {}
  436. for i in [source.id, destination.id]:
  437. items[i] = list(GroupRelease.objects.filter(group_id=i).values_list("id", flat=True))
  438. time_series = strip_zeroes(
  439. tsdb.get_frequency_series(
  440. tsdb.models.frequent_releases_by_group,
  441. items,
  442. now - timedelta(seconds=rollup_duration),
  443. time_from_now(17),
  444. rollup_duration,
  445. tenant_ids={"referrer": "r", "organization_id": 1234},
  446. )
  447. )
  448. assert_series_contains(
  449. get_expected_series_values(
  450. rollup_duration,
  451. list(events.values())[1],
  452. functools.partial(collect_by_release, source),
  453. ),
  454. time_series[source.id],
  455. {},
  456. )
  457. assert_series_contains(
  458. get_expected_series_values(
  459. rollup_duration,
  460. list(events.values())[0] + list(events.values())[2],
  461. functools.partial(collect_by_release, destination),
  462. ),
  463. time_series[destination.id],
  464. {},
  465. )
  466. items = {}
  467. for i in [source.id, destination.id]:
  468. items[i] = list(Environment.objects.all().values_list("id", flat=True))
  469. time_series = strip_zeroes(
  470. tsdb.get_frequency_series(
  471. tsdb.models.frequent_environments_by_group,
  472. items,
  473. now - timedelta(seconds=rollup_duration),
  474. time_from_now(17),
  475. rollup_duration,
  476. tenant_ids={"referrer": "r", "organization_id": 1234},
  477. )
  478. )
  479. def collect_by_environment(aggregate, event):
  480. aggregate = aggregate if aggregate is not None else {}
  481. environment = Environment.objects.get(
  482. organization_id=project.organization_id, name=event.data["environment"]
  483. ).id
  484. aggregate[environment] = aggregate.get(environment, 0) + 1
  485. return aggregate
  486. assert_series_contains(
  487. get_expected_series_values(
  488. rollup_duration, list(events.values())[1], collect_by_environment
  489. ),
  490. time_series[source.id],
  491. {},
  492. )
  493. assert_series_contains(
  494. get_expected_series_values(
  495. rollup_duration,
  496. list(events.values())[0] + list(events.values())[2],
  497. collect_by_environment,
  498. ),
  499. time_series[destination.id],
  500. {},
  501. )
  502. source_similar_items = features.compare(source)
  503. assert source_similar_items[0] == (
  504. source.id,
  505. {
  506. "exception:message:character-shingles": None,
  507. "exception:stacktrace:application-chunks": None,
  508. "exception:stacktrace:pairs": None,
  509. "message:message:character-shingles": 1.0,
  510. },
  511. )
  512. assert source_similar_items[1][0] == destination.id
  513. assert source_similar_items[1][1]["message:message:character-shingles"] < 1.0
  514. destination_similar_items = features.compare(destination)
  515. assert destination_similar_items[0] == (
  516. destination.id,
  517. {
  518. "exception:message:character-shingles": None,
  519. "exception:stacktrace:application-chunks": None,
  520. "exception:stacktrace:pairs": None,
  521. "message:message:character-shingles": 1.0,
  522. },
  523. )
  524. assert destination_similar_items[1][0] == source.id
  525. assert destination_similar_items[1][1]["message:message:character-shingles"] < 1.0