返回 last30days-skill
test_store_topic_membership.py
根目录 / tests / test_store_topic_membership.py
1 """Shared findings retain every topic's membership and history."""
2
3 import sqlite3
4 from concurrent.futures import ThreadPoolExecutor
5 from datetime import datetime, timedelta, timezone
6 from threading import Event
7
8 import pytest
9
10 import briefing
11 import store
12
13
14 @pytest.fixture
15 def shared_findings(tmp_path):
16 path = tmp_path / "research.db"
17 with store.scoped_db(path):
18 store.init_db()
19 topics = {name: store.add_topic(name) for name in ("A", "B")}
20 runs = {}
21 for name in topics:
22 runs[name] = store.record_run(topics[name]["id"])
23 store.store_findings(runs[name], topics[name]["id"], [
24 {
25 "source": "reddit",
26 "source_url": "https://example.test/shared",
27 "source_title": "Shared research",
28 "engagement_score": 10,
29 },
30 {
31 "source": "reddit",
32 "source_url": f"https://example.test/{name}",
33 "source_title": f"Exclusive {name}",
34 "engagement_score": 5,
35 },
36 ])
37 yield path, topics, runs
38
39
40 @pytest.fixture
41 def later_topic_sighting(tmp_path, monkeypatch):
42 path = tmp_path / "research.db"
43 monkeypatch.setattr(briefing, "BRIEFS_DIR", tmp_path / "briefs")
44 now = datetime.now(timezone.utc)
45 old = (now - timedelta(days=10)).strftime("%Y-%m-%d %H:%M:%S")
46 recent = (now - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
47 finding = {
48 "source": "reddit", "source_url": "https://example.test/shared",
49 "source_title": "Shared research", "engagement_score": 10,
50 }
51 with store.scoped_db(path):
52 topics = {name: store.add_topic(name) for name in ("A", "B")}
53 for name, seen in (("A", old), ("B", recent)):
54 run = store.record_run(topics[name]["id"])
55 store.store_findings(run, topics[name]["id"], [finding])
56 with sqlite3.connect(path) as conn:
57 conn.execute("UPDATE research_runs SET run_date = ? WHERE id = ?", (seen, run))
58 conn.execute("UPDATE finding_sightings SET seen_at = ? WHERE run_id = ?", (seen, run))
59 conn.execute("UPDATE findings SET first_seen = ?", (old,))
60 for name in ("A", "B"):
61 run = store.record_run(topics[name]["id"])
62 store.store_findings(run, topics[name]["id"], [finding])
63 yield path, topics, old, recent
64
65
66 def _create_legacy_findings(path):
67 old = (datetime.now(timezone.utc) - timedelta(days=20)).strftime("%Y-%m-%d %H:%M:%S")
68 with sqlite3.connect(path) as conn:
69 conn.executescript(store.SCHEMA_V1)
70 conn.execute("INSERT INTO schema_version (version) VALUES (1)")
71 conn.executemany("INSERT INTO settings (key, value) VALUES (?, ?)", store._DEFAULT_SETTINGS.items())
72 conn.execute("INSERT INTO topics (id, name) VALUES (1, 'A')")
73 conn.execute("INSERT INTO research_runs (id, topic_id, run_date) VALUES (1, 1, ?)", (old,))
74 for finding_id in (1, 2):
75 conn.execute(
76 """INSERT INTO findings
77 (id, topic_id, run_id, source, source_url, source_title, first_seen)
78 VALUES (?, 1, 1, 'reddit', ?, 'Legacy research', ?)""",
79 (finding_id, f"https://example.test/legacy/{finding_id}", old),
80 )
81 return old
82
83
84 @pytest.mark.parametrize("resighted_before_upgrade", [False, True])
85 def test_backfill_preserves_legacy_date_when_same_topic_resights(tmp_path, resighted_before_upgrade):
86 path = tmp_path / "legacy.db"
87 old = _create_legacy_findings(path)
88 finding = {"source": "reddit", "source_url": "https://example.test/legacy/1"}
89 with store.scoped_db(path):
90 if resighted_before_upgrade:
91 with sqlite3.connect(path) as conn:
92 for version in sorted(store.MIGRATIONS):
93 conn.executescript(store.MIGRATIONS[version])
94 conn.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))
95 run = store.record_run(1)
96 store.store_findings(run, 1, [finding])
97 store.init_db()
98 if not resighted_before_upgrade:
99 run = store.record_run(1)
100 counts = store.store_findings(run, 1, [finding], count_by_topic=True)
101 assert counts == {"new": 0, "updated": 1}
102 since = (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
103
104 assert store.get_new_findings(1, since) == []
105 assert {item["first_seen"] for item in store.get_new_findings(1)} == {old}
106 assert len(store.get_sightings_for_run(1, run)) == 1
107 assert store.get_sightings_for_run(1, 1) == []
108 assert store.get_trending()[0]["new_findings"] == 0
109
110
111 @pytest.mark.parametrize("count_by_topic", [False, True])
112 def test_resighting_preserves_legacy_latest_run_topic(tmp_path, count_by_topic):
113 path = tmp_path / "legacy.db"
114 owner_seen = _create_legacy_findings(path)
115 legacy_seen = (datetime.fromisoformat(owner_seen) + timedelta(days=1)).isoformat(" ")
116 url = "https://example.test/legacy/1"
117 finding = {"source": "reddit", "source_url": url}
118 with sqlite3.connect(path) as conn:
119 conn.execute("INSERT INTO topics (id, name) VALUES (2, 'B')")
120 conn.execute("INSERT INTO research_runs (id, topic_id, run_date) VALUES (2, 2, ?)", (legacy_seen,))
121 conn.execute("UPDATE findings SET run_id = 2 WHERE source_url = ?", (url,))
122
123 with store.scoped_db(path):
124 third = store.add_topic("C")["id"]
125 run = store.record_run(third)
126 store.store_findings(run, third, [finding], count_by_topic=count_by_topic)
127
128 assert [(row["source_url"], row["first_seen"]) for row in store.get_new_findings(2)] == [
129 (url, legacy_seen)
130 ]
131 assert store.get_sightings_for_run(2, 2) == []
132 repeat = store.record_run(2)
133 assert store.store_findings(repeat, 2, [finding], count_by_topic=True) == {"new": 0, "updated": 1}
134
135
136 def test_backfill_does_not_reattribute_old_date_after_owner_removal(tmp_path):
137 path = tmp_path / "legacy.db"
138 old = _create_legacy_findings(path)
139 with store.scoped_db(path):
140 store.init_db()
141 topic_b = store.add_topic("B")
142 run_b = store.record_run(topic_b["id"])
143 store.store_findings(run_b, topic_b["id"], [{
144 "source": "reddit", "source_url": "https://example.test/legacy/1",
145 }])
146 recent = store.get_sightings_for_run(topic_b["id"], run_b)[0]["seen_at"]
147
148 assert store.remove_topic("A")
149 store.init_db()
150 store.init_db()
151
152 findings = store.get_new_findings(topic_b["id"], since=recent)
153 assert len(findings) == 1
154 assert findings[0]["first_seen"] == recent
155 with sqlite3.connect(path) as conn:
156 assert conn.execute("SELECT first_seen FROM findings").fetchone()[0] == old
157 assert conn.execute("SELECT COUNT(*) FROM finding_sightings").fetchone()[0] == 1
158
159
160 def test_backfill_rolls_back_historical_sightings_and_marker_on_failure(tmp_path):
161 path = tmp_path / "legacy.db"
162 _create_legacy_findings(path)
163 with sqlite3.connect(path) as conn:
164 for version in sorted(store.MIGRATIONS):
165 conn.executescript(store.MIGRATIONS[version])
166 conn.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))
167 before_settings = conn.execute("SELECT * FROM settings ORDER BY key").fetchall()
168 conn.execute("""CREATE TRIGGER reject_backfill BEFORE INSERT ON settings
169 WHEN NEW.key = '_topic_sightings_backfilled_v1'
170 BEGIN SELECT RAISE(ABORT, 'backfill blocked'); END""")
171 with store.scoped_db(path):
172 with pytest.raises(sqlite3.IntegrityError, match="backfill blocked"):
173 store.init_db()
174
175 with sqlite3.connect(path) as conn:
176 assert conn.execute("SELECT COUNT(*) FROM finding_sightings").fetchone()[0] == 0
177 assert conn.execute("SELECT * FROM settings ORDER BY key").fetchall() == before_settings
178 conn.execute("DROP TRIGGER reject_backfill")
179 store.init_db()
180 store.init_db()
181 with sqlite3.connect(path) as conn:
182 assert conn.execute("SELECT COUNT(*) FROM finding_sightings").fetchone()[0] == 2
183 assert conn.execute(
184 "SELECT value FROM settings WHERE key = '_topic_sightings_backfilled_v1'"
185 ).fetchone()[0] == "1"
186
187
188 def test_completed_backfill_reads_marker_without_writer_transaction(tmp_path):
189 with store.scoped_db(tmp_path / "research.db"):
190 store.init_db()
191 writer = store._connect()
192 reader = store._connect()
193 statements = []
194 reader.set_trace_callback(statements.append)
195 try:
196 writer.execute("BEGIN IMMEDIATE")
197
198 store._backfill_owner_sightings(reader)
199
200 assert statements
201 assert not any(statement.lstrip().upper().startswith((
202 "BEGIN", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER",
203 )) for statement in statements)
204 finally:
205 writer.rollback()
206 writer.close()
207 reader.close()
208
209
210 @pytest.mark.parametrize("read", ["list_topics", "get_topic"])
211 def test_topic_reads_succeed_while_another_connection_holds_writer_lock(tmp_path, read):
212 with store.scoped_db(tmp_path / "research.db"):
213 store.add_topic("A")
214 writer = store._connect()
215 try:
216 writer.execute("BEGIN IMMEDIATE")
217
218 if read == "list_topics":
219 assert [topic["name"] for topic in store.list_topics()] == ["A"]
220 else:
221 assert store.get_topic("A")["name"] == "A"
222
223 assert writer.in_transaction
224 finally:
225 writer.rollback()
226 writer.close()
227
228
229 def test_initialization_repairs_missing_defaults_without_overwriting_settings(tmp_path):
230 path = tmp_path / "research.db"
231 with store.scoped_db(path):
232 store.init_db()
233 store.set_setting("delivery_channel", "existing-channel")
234 with sqlite3.connect(path) as conn:
235 conn.execute("DELETE FROM settings WHERE key = 'delivery_mode'")
236 conn.execute("DELETE FROM schema_version WHERE version = 1")
237
238 store.init_db()
239
240 with sqlite3.connect(path) as conn:
241 assert conn.execute(
242 "SELECT value FROM settings WHERE key = 'delivery_mode'"
243 ).fetchone()[0] == "announce"
244 assert conn.execute(
245 "SELECT value FROM settings WHERE key = 'delivery_channel'"
246 ).fetchone()[0] == "existing-channel"
247 assert conn.execute("SELECT version FROM schema_version WHERE version = 1").fetchone() == (1,)
248
249
250 def test_backfill_rechecks_marker_after_waiting_for_another_initializer(tmp_path):
251 with store.scoped_db(tmp_path / "research.db"):
252 store.init_db()
253 writer = store._connect()
254 try:
255 writer.execute("DELETE FROM settings WHERE key = '_topic_sightings_backfilled_v1'")
256 writer.commit()
257 writer.execute("BEGIN IMMEDIATE")
258 writer.execute(
259 "INSERT INTO settings (key, value) VALUES ('_topic_sightings_backfilled_v1', '1')"
260 )
261 waiting_for_writer = Event()
262
263 def initialize():
264 reader = store._connect()
265 try:
266 reader.set_trace_callback(lambda sql: (
267 waiting_for_writer.set() if sql == "BEGIN IMMEDIATE" else None
268 ))
269 store._backfill_owner_sightings(reader)
270 finally:
271 reader.close()
272
273 with ThreadPoolExecutor(max_workers=1) as executor:
274 future = executor.submit(initialize)
275 try:
276 assert waiting_for_writer.wait(timeout=2)
277 finally:
278 writer.commit()
279 future.result(timeout=2)
280 assert writer.execute(
281 "SELECT COUNT(*) FROM settings WHERE key = '_topic_sightings_backfilled_v1'"
282 ).fetchone()[0] == 1
283 finally:
284 writer.close()
285
286
287 @pytest.mark.parametrize("surface", ["findings", "trending", "daily", "weekly"])
288 def test_new_finding_window_uses_each_topics_first_sighting(later_topic_sighting, surface):
289 _, topics, old, recent = later_topic_sighting
290 since = (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
291 if surface == "findings":
292 assert store.get_new_findings(topics["A"]["id"], since) == []
293 findings = store.get_new_findings(topics["B"]["id"], since)
294 assert len(findings) == 1
295 assert findings[0]["first_seen"] == recent
296 elif surface == "trending":
297 trends = {item["name"]: item for item in store.get_trending()}
298 assert trends["A"]["new_findings"] == 0
299 assert trends["B"]["new_findings"] == 1
300 assert trends["B"]["total_engagement"] == 10
301 elif surface == "daily":
302 daily = briefing.generate_daily(since=since)
303 assert daily["total_new"] == 1
304 assert {item["name"]: item["new_count"] for item in daily["topics"]} == {"A": 0, "B": 1}
305 else:
306 weekly = {item["name"]: item for item in briefing.generate_weekly()["topics"]}
307 assert (weekly["A"]["this_week_count"], weekly["A"]["last_week_count"]) == (0, 1)
308 assert (weekly["B"]["this_week_count"], weekly["B"]["last_week_count"]) == (1, 0)
309
310
311 def test_removing_first_owner_preserves_survivors_first_sighting(later_topic_sighting):
312 path, topics, old, recent = later_topic_sighting
313 assert store.remove_topic("A")
314
315 findings = store.get_new_findings(topics["B"]["id"], since=recent)
316
317 assert len(findings) == 1
318 assert findings[0]["first_seen"] == recent
319 with sqlite3.connect(path) as conn:
320 assert conn.execute("SELECT first_seen FROM findings").fetchone()[0] == old
321
322
323 @pytest.mark.parametrize("removed", ["A", "B"])
324 def test_remove_topic_preserves_other_topic_history(shared_findings, removed):
325 path, topics, runs = shared_findings
326 survivor = "B" if removed == "A" else "A"
327 sightings = store.get_sightings_for_run(topics[survivor]["id"], runs[survivor])
328
329 assert store.remove_topic(removed)
330
331 assert store.get_sightings_for_run(topics[survivor]["id"], runs[survivor]) == sightings
332 findings = store.get_new_findings(topics[survivor]["id"])
333 assert {item["source_url"] for item in findings} == {
334 "https://example.test/shared", f"https://example.test/{survivor}",
335 }
336 shared = next(item for item in findings if item["source_title"] == "Shared research")
337 assert shared["run_id"] == runs[survivor]
338 assert shared["sighting_count"] == 2
339 assert store.search_findings("Shared")[0]["id"] == shared["id"]
340 assert store.get_topic(removed) is None
341 assert not store.remove_topic(removed)
342 with sqlite3.connect(path) as conn:
343 assert conn.execute("PRAGMA foreign_key_check").fetchall() == []
344 assert conn.execute("SELECT id FROM research_runs").fetchall() == [(runs[survivor],)]
345
346 assert store.remove_topic(survivor)
347 assert store.get_stats()["total_findings"] == 0
348
349
350 def test_topic_reads_include_shared_findings_once(shared_findings):
351 _, topics, _ = shared_findings
352 run = store.record_run(topics["B"]["id"])
353 store.store_findings(run, topics["B"]["id"], [{
354 "source": "reddit", "source_url": "https://example.test/shared",
355 "engagement_score": 10,
356 }])
357
358 assert {t["name"]: t["finding_count"] for t in store.list_topics()} == {"A": 2, "B": 2}
359 for topic in topics.values():
360 assert len(store.get_new_findings(topic["id"])) == 2
361 trending = {item["name"]: item for item in store.get_trending()}
362 assert {name: item["new_findings"] for name, item in trending.items()} == {"A": 2, "B": 2}
363 assert {name: item["total_engagement"] for name, item in trending.items()} == {"A": 15, "B": 15}
364
365
366 def test_removal_preserves_membership_between_first_and_latest_topic(shared_findings):
367 _, topics, _ = shared_findings
368 topic_c = store.add_topic("C")
369 run_c = store.record_run(topic_c["id"])
370 store.store_findings(run_c, topic_c["id"], [{
371 "source": "reddit", "source_url": "https://example.test/shared",
372 }])
373
374 assert store.remove_topic("A")
375
376 assert len(store.get_new_findings(topics["B"]["id"])) == 2
377 shared = store.get_new_findings(topic_c["id"])
378 assert len(shared) == 1
379 assert shared[0]["source_url"] == "https://example.test/shared"
380 assert shared[0]["run_id"] == run_c
381 assert store.remove_topic("C")
382 assert len(store.get_new_findings(topics["B"]["id"])) == 2
383
384
385 def test_removal_preserves_other_topic_delta(shared_findings):
386 _, topics, _ = shared_findings
387 run = store.record_run(topics["B"]["id"])
388 store.store_findings(run, topics["B"]["id"], [{
389 "source": "reddit", "source_url": "https://example.test/shared",
390 }])
391 before = store.compute_topic_delta(topics["B"]["id"])
392 assert before["continued"] == 1
393 assert before["dropped"] == 1
394
395 assert store.remove_topic("A")
396
397 assert store.compute_topic_delta(topics["B"]["id"]) == before
398
399
400 def test_weekly_briefing_counts_shared_findings_in_both_periods(shared_findings, monkeypatch):
401 path, _, _ = shared_findings
402 monkeypatch.setattr(briefing, "BRIEFS_DIR", path.parent / "briefs")
403 last_week = (datetime.now() - timedelta(days=10)).strftime("%Y-%m-%d %H:%M:%S")
404 with sqlite3.connect(path) as conn:
405 conn.execute(
406 "UPDATE findings SET first_seen = ? WHERE source_url = ?",
407 (last_week, "https://example.test/shared"),
408 )
409 conn.execute(
410 "UPDATE finding_sightings SET seen_at = ? WHERE source_url = ?",
411 (last_week, "https://example.test/shared"),
412 )
413
414 result = briefing.generate_weekly()
415
416 assert result["status"] == "ok"
417 assert len(result["topics"]) == 2
418 for topic in result["topics"]:
419 assert topic["this_week_count"] == 1
420 assert topic["last_week_count"] == 1
421 assert topic["engagement_change_pct"] == -50.0
422
423
424 def test_topic_findings_date_range_excludes_upper_boundary(shared_findings):
425 path, topics, _ = shared_findings
426 with sqlite3.connect(path) as conn:
427 conn.execute("UPDATE findings SET first_seen = '2026-01-01'")
428 conn.execute("UPDATE finding_sightings SET seen_at = '2026-01-01'")
429 conn.execute(
430 "UPDATE findings SET first_seen = '2026-01-08' WHERE source_url = ?",
431 ("https://example.test/shared",),
432 )
433 conn.execute(
434 "UPDATE finding_sightings SET seen_at = '2026-01-08' WHERE source_url = ?",
435 ("https://example.test/shared",),
436 )
437
438 findings = store.get_new_findings(topics["B"]["id"], "2026-01-01", before="2026-01-08")
439
440 assert [item["source_url"] for item in findings] == ["https://example.test/B"]
441 assert store.get_new_findings(topics["B"]["id"], before="2026-01-01") == []
442
443
444 @pytest.mark.parametrize("removed", ["A", "B"])
445 def test_remove_topic_preserves_legacy_aggregate_membership(shared_findings, removed):
446 path, topics, runs = shared_findings
447 survivor = "B" if removed == "A" else "A"
448 with sqlite3.connect(path) as conn:
449 conn.execute("DELETE FROM finding_sightings")
450
451 assert store.remove_topic(removed)
452
453 findings = store.get_new_findings(topics[survivor]["id"])
454 assert {item["source_url"] for item in findings} == {
455 "https://example.test/shared", f"https://example.test/{survivor}",
456 }
457 shared = next(item for item in findings if item["source_title"] == "Shared research")
458 assert shared["run_id"] == (runs["B"] if survivor == "B" else None)
459 with sqlite3.connect(path) as conn:
460 assert conn.execute("PRAGMA foreign_key_check").fetchall() == []
461
462
463 def test_remove_topic_rolls_back_when_deletion_fails(shared_findings):
464 path, topics, runs = shared_findings
465 with sqlite3.connect(path) as conn:
466 before = conn.execute("SELECT * FROM findings ORDER BY id").fetchall()
467 conn.execute("""CREATE TRIGGER reject_topic_delete BEFORE DELETE ON topics
468 BEGIN SELECT RAISE(ABORT, 'deletion blocked'); END""")
469
470 with pytest.raises(sqlite3.IntegrityError, match="deletion blocked"):
471 store.remove_topic("A")
472
473 assert store.get_topic("A") == topics["A"]
474 assert len(store.get_sightings_for_run(topics["A"]["id"], runs["A"])) == 2
475 with sqlite3.connect(path) as conn:
476 assert conn.execute("SELECT * FROM findings ORDER BY id").fetchall() == before
477 assert conn.execute("PRAGMA foreign_key_check").fetchall() == []
478
478 lines PYTHON