| 1 | """Regression coverage for concurrent engagement updates in the research store.""" |
| 2 | |
| 3 | import sqlite3 |
| 4 | import threading |
| 5 | from concurrent.futures import ThreadPoolExecutor |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | import store |
| 10 | |
| 11 | |
| 12 | @pytest.fixture |
| 13 | def database(tmp_path, monkeypatch): |
| 14 | path = tmp_path / "research.db" |
| 15 | monkeypatch.setattr(store, "_db_override", path) |
| 16 | store.init_db() |
| 17 | topic = store.add_topic("Concurrent research") |
| 18 | return path, topic["id"] |
| 19 | |
| 20 | |
| 21 | @pytest.mark.parametrize("existing", [True, False], ids=["existing-row", "insert-conflict"]) |
| 22 | def test_concurrent_observations_keep_maximum_and_each_run_history(database, monkeypatch, existing): |
| 23 | path, topic_id = database |
| 24 | finding = { |
| 25 | "source": "reddit", |
| 26 | "source_url": "https://reddit.com/r/test/concurrent", |
| 27 | "source_title": "Concurrent observation", |
| 28 | } |
| 29 | expected_history = [] |
| 30 | expected_counts = [] |
| 31 | if existing: |
| 32 | initial_run = store.record_run(topic_id) |
| 33 | assert store.store_findings(initial_run, topic_id, [{**finding, "engagement_score": 10}]) == { |
| 34 | "new": 1, "updated": 0, |
| 35 | } |
| 36 | expected_history.append((initial_run, 10.0)) |
| 37 | expected_counts.append((initial_run, 1, 0)) |
| 38 | runs = {score: store.record_run(topic_id) for score in (100, 50)} |
| 39 | |
| 40 | start_barrier = threading.Barrier(2, timeout=5) |
| 41 | high_locked = threading.Event() |
| 42 | worker = threading.local() |
| 43 | lock_order = [] |
| 44 | real_connect = store._connect |
| 45 | |
| 46 | class GatedConnection: |
| 47 | def __init__(self, connection): |
| 48 | self.connection = connection |
| 49 | |
| 50 | def execute(self, sql, parameters=()): |
| 51 | if sql == "BEGIN IMMEDIATE": |
| 52 | start_barrier.wait() |
| 53 | if worker.score == 50: |
| 54 | assert high_locked.wait(timeout=5), "The high observation did not acquire write lock" |
| 55 | cursor = self.connection.execute(sql, parameters) |
| 56 | lock_order.append(worker.score) |
| 57 | if worker.score == 100: |
| 58 | high_locked.set() |
| 59 | return cursor |
| 60 | return self.connection.execute(sql, parameters) |
| 61 | |
| 62 | def __getattr__(self, name): |
| 63 | return getattr(self.connection, name) |
| 64 | |
| 65 | monkeypatch.setattr(store, "_connect", lambda: GatedConnection(real_connect())) |
| 66 | |
| 67 | def observe(score): |
| 68 | worker.score = score |
| 69 | return store.store_findings(runs[score], topic_id, [{**finding, "engagement_score": score}]) |
| 70 | |
| 71 | with ThreadPoolExecutor(max_workers=2) as executor: |
| 72 | futures = {score: executor.submit(observe, score) for score in (100, 50)} |
| 73 | results = {score: future.result(timeout=10) for score, future in futures.items()} |
| 74 | |
| 75 | assert lock_order == [100, 50] |
| 76 | assert results == { |
| 77 | 100: {"new": 0 if existing else 1, "updated": 1 if existing else 0}, |
| 78 | 50: {"new": 0, "updated": 1}, |
| 79 | } |
| 80 | expected_history.extend([(runs[100], 100.0), (runs[50], 50.0)]) |
| 81 | expected_counts.extend([ |
| 82 | (runs[100], 0 if existing else 1, 1 if existing else 0), |
| 83 | (runs[50], 0, 1), |
| 84 | ]) |
| 85 | with sqlite3.connect(path) as connection: |
| 86 | aggregate = connection.execute( |
| 87 | "SELECT engagement_score, sighting_count, run_id FROM findings" |
| 88 | ).fetchall() |
| 89 | history = connection.execute( |
| 90 | "SELECT run_id, engagement_score FROM finding_sightings ORDER BY run_id" |
| 91 | ).fetchall() |
| 92 | counts = connection.execute( |
| 93 | "SELECT id, findings_new, findings_updated FROM research_runs ORDER BY id" |
| 94 | ).fetchall() |
| 95 | assert aggregate == [(100.0, 3 if existing else 2, runs[50])] |
| 96 | assert history == expected_history |
| 97 | assert counts == expected_counts |
| 98 | |
| 99 | |
| 100 | @pytest.mark.parametrize( |
| 101 | "stored,incoming,expected", |
| 102 | [(10, 50, 50), (100, 50, 100), (None, 50, 50), (100, None, 100), (None, None, 0)], |
| 103 | ) |
| 104 | def test_existing_engagement_preserves_maximum_and_handles_null(database, stored, incoming, expected): |
| 105 | path, topic_id = database |
| 106 | finding = {"source": "reddit", "source_url": "https://reddit.com/r/test/sequential"} |
| 107 | initial_run = store.record_run(topic_id) |
| 108 | store.store_findings(initial_run, topic_id, [{**finding, "engagement_score": stored}]) |
| 109 | if stored is None: |
| 110 | with sqlite3.connect(path) as connection: |
| 111 | connection.execute("UPDATE findings SET engagement_score = NULL") |
| 112 | run = store.record_run(topic_id) |
| 113 | assert store.store_findings(run, topic_id, [{**finding, "engagement_score": incoming}]) == { |
| 114 | "new": 0, "updated": 1, |
| 115 | } |
| 116 | with sqlite3.connect(path) as connection: |
| 117 | assert connection.execute("SELECT engagement_score, sighting_count FROM findings").fetchall() == [ |
| 118 | (expected, 2), |
| 119 | ] |
| 120 | assert connection.execute( |
| 121 | "SELECT engagement_score FROM finding_sightings WHERE run_id = ?", (run,) |
| 122 | ).fetchone() == (incoming or 0,) |
| 123 |