返回 last30days-skill
test_store.py
根目录 / tests / test_store.py
1 """Tests for store.py - SQLite research accumulator and watchlist storage."""
2
3 import json
4 import sqlite3
5 import sys
6 import tempfile
7 import threading
8 from concurrent.futures import ThreadPoolExecutor
9 from datetime import datetime, timedelta, timezone
10 from pathlib import Path
11
12 import pytest
13
14 # Import the module under test
15
16 import store
17 from lib import schema
18
19 @pytest.fixture
20
21
22 def temp_db(tmp_path):
23 """Create a temporary database for testing."""
24 db_path = tmp_path / "test_store.db"
25
26 # Override the database path
27 original_override = store._db_override
28 store._db_override = db_path
29
30 # Initialize fresh database
31 store.init_db()
32
33 yield db_path
34
35 # Cleanup
36 store._db_override = original_override
37 if db_path.exists():
38 db_path.unlink()
39
40 @pytest.fixture
41
42
43 def sample_report():
44 """Create a sample Report with multiple sources including HN and Polymarket."""
45 return schema.report_from_dict({
46 "topic": "Test Topic",
47 "range_from": "2026-01-01",
48 "range_to": "2026-04-03",
49 "generated_at": "2026-04-03T00:00:00Z",
50 "provider_runtime": {
51 "reasoning_provider": "gemini",
52 "planner_model": "gemini-2.0-flash-exp",
53 "rerank_model": "gemini-2.0-flash-exp",
54 },
55 "query_plan": {
56 "intent": "test",
57 "freshness_mode": "recent",
58 "cluster_mode": "standard",
59 "raw_topic": "test",
60 "subqueries": [],
61 "source_weights": {},
62 },
63 "clusters": [],
64 "ranked_candidates": [
65 {
66 "candidate_id": "c-r1",
67 "item_id": "R1",
68 "source": "reddit",
69 "title": "Test Reddit Post",
70 "url": "https://reddit.com/r/test/1",
71 "snippet": "Reddit snippet",
72 "subquery_labels": ["primary"],
73 "native_ranks": {"reddit": 1},
74 "local_relevance": 0.8,
75 "freshness": 100,
76 "engagement": 50.0,
77 "source_quality": 0.8,
78 "rrf_score": 1.0,
79 "final_score": 0.8,
80 "explanation": "Reddit snippet",
81 "source_items": [
82 {
83 "item_id": "R1",
84 "source": "reddit",
85 "title": "Test Reddit Post",
86 "body": "Reddit discussion content",
87 "url": "https://reddit.com/r/test/1",
88 "author": "testuser",
89 "engagement_score": 50.0,
90 "local_relevance": 0.8,
91 "snippet": "Reddit snippet",
92 }
93 ],
94 },
95 {
96 "candidate_id": "c-x1",
97 "item_id": "X1",
98 "source": "x",
99 "title": "Test X Post",
100 "url": "https://x.com/test/status/1",
101 "snippet": "X snippet",
102 "subquery_labels": ["primary"],
103 "native_ranks": {"x": 1},
104 "local_relevance": 0.85,
105 "freshness": 100,
106 "engagement": 75.0,
107 "source_quality": 0.8,
108 "rrf_score": 1.0,
109 "final_score": 0.85,
110 "explanation": "X snippet",
111 "source_items": [
112 {
113 "item_id": "X1",
114 "source": "x",
115 "title": "Test X Post",
116 "body": "X post content",
117 "url": "https://x.com/test/status/1",
118 "author": "xuser",
119 "engagement_score": 75.0,
120 "local_relevance": 0.85,
121 "snippet": "X snippet",
122 }
123 ],
124 },
125 ],
126 "items_by_source": {
127 "reddit": [
128 {
129 "item_id": "R1",
130 "source": "reddit",
131 "title": "Test Reddit Post",
132 "body": "Reddit discussion content",
133 "url": "https://reddit.com/r/test/1",
134 "author": "testuser",
135 "engagement_score": 50.0,
136 "local_relevance": 0.8,
137 "snippet": "Reddit snippet",
138 }
139 ],
140 "x": [
141 {
142 "item_id": "X1",
143 "source": "x",
144 "title": "Test X Post",
145 "body": "X post content",
146 "url": "https://x.com/test/status/1",
147 "author": "xuser",
148 "engagement_score": 75.0,
149 "local_relevance": 0.85,
150 "snippet": "X snippet",
151 }
152 ],
153 "hackernews": [
154 {
155 "item_id": "HN1",
156 "source": "hackernews",
157 "title": "Test HN Story",
158 "body": "HN story content with comments",
159 "url": "https://news.ycombinator.com/item?id=12345",
160 "author": "hnuser",
161 "engagement_score": 120.0,
162 "local_relevance": 0.9,
163 "snippet": "HN snippet",
164 }
165 ],
166 "polymarket": [
167 {
168 "item_id": "PM1",
169 "source": "polymarket",
170 "title": "Will event happen?",
171 "body": "Yes: 64% / No: 36%",
172 "url": "https://polymarket.com/event/test-event",
173 "author": None,
174 "engagement_score": 342000.0,
175 "local_relevance": 0.7,
176 "snippet": "Prediction market",
177 }
178 ],
179 },
180 "errors_by_source": {},
181 "warnings": [],
182 })
183
184 # === Tests for findings_from_report() ===
185
186
187 def test_findings_from_report_processes_all_sources(sample_report):
188 """Test that findings_from_report extracts items from all sources in items_by_source."""
189 findings = store.findings_from_report(sample_report)
190
191 # Should have 4 findings (reddit + x + hackernews + polymarket)
192 assert len(findings) == 4
193
194 # Check all sources are present
195 sources = {f["source"] for f in findings}
196 assert sources == {"reddit", "x", "hackernews", "polymarket"}
197
198
199 def test_findings_from_report_includes_hackernews(sample_report):
200 """Test that HN items are extracted correctly (PR #85 feature)."""
201 findings = store.findings_from_report(sample_report)
202
203 hn_findings = [f for f in findings if f["source"] == "hackernews"]
204 assert len(hn_findings) == 1
205
206 hn = hn_findings[0]
207 assert hn["source_url"] == "https://news.ycombinator.com/item?id=12345"
208 assert hn["source_title"] == "Test HN Story"
209 assert hn["engagement_score"] == 120.0
210 assert hn["relevance_score"] == 0.9
211 assert "HN story content" in hn["content"]
212
213
214 def test_findings_from_report_includes_polymarket(sample_report):
215 """Test that Polymarket items are extracted correctly (PR #85 feature)."""
216 findings = store.findings_from_report(sample_report)
217
218 pm_findings = [f for f in findings if f["source"] == "polymarket"]
219 assert len(pm_findings) == 1
220
221 pm = pm_findings[0]
222 assert pm["source_url"] == "https://polymarket.com/event/test-event"
223 assert pm["source_title"] == "Will event happen?"
224 assert pm["engagement_score"] == 342000.0
225 assert pm["relevance_score"] == 0.7
226 assert "Yes: 64%" in pm["content"]
227
228
229 def test_findings_from_report_respects_limit(sample_report):
230 """The limit applies across ranked and supplemental sources."""
231 findings = store.findings_from_report(sample_report, limit=2)
232 assert [(f["source"], f["source_url"]) for f in findings] == [
233 ("reddit", "https://reddit.com/r/test/1"),
234 ("x", "https://x.com/test/status/1"),
235 ]
236
237
238 def test_findings_from_report_handles_empty_sources():
239 """Test that empty sources in items_by_source don't cause issues."""
240 report = schema.report_from_dict({
241 "topic": "Test",
242 "range_from": "2026-01-01",
243 "range_to": "2026-04-03",
244 "generated_at": "2026-04-03T00:00:00Z",
245 "provider_runtime": {
246 "reasoning_provider": "gemini",
247 "planner_model": "gemini-2.0-flash-exp",
248 "rerank_model": "gemini-2.0-flash-exp",
249 },
250 "query_plan": {
251 "intent": "test",
252 "freshness_mode": "recent",
253 "cluster_mode": "standard",
254 "raw_topic": "test",
255 "subqueries": [],
256 "source_weights": {},
257 },
258 "clusters": [],
259 "ranked_candidates": [],
260 "items_by_source": {
261 "reddit": [],
262 "x": [],
263 "hackernews": [],
264 "polymarket": [],
265 },
266 "errors_by_source": {},
267 "warnings": [],
268 })
269
270 findings = store.findings_from_report(report)
271 assert len(findings) == 0
272
273
274 def test_findings_from_report_handles_missing_fields():
275 """Test that missing optional fields (author, snippet) are handled gracefully."""
276 report = schema.report_from_dict({
277 "topic": "Test",
278 "range_from": "2026-01-01",
279 "range_to": "2026-04-03",
280 "generated_at": "2026-04-03T00:00:00Z",
281 "provider_runtime": {
282 "reasoning_provider": "gemini",
283 "planner_model": "gemini-2.0-flash-exp",
284 "rerank_model": "gemini-2.0-flash-exp",
285 },
286 "query_plan": {
287 "intent": "test",
288 "freshness_mode": "recent",
289 "cluster_mode": "standard",
290 "raw_topic": "test",
291 "subqueries": [],
292 "source_weights": {},
293 },
294 "clusters": [],
295 "ranked_candidates": [],
296 "items_by_source": {
297 "hackernews": [
298 {
299 "item_id": "R1",
300 "source": "hackernews",
301 "title": "Test",
302 "body": "Content",
303 "url": "https://news.ycombinator.com/item?id=1",
304 "author": None, # Missing author
305 "engagement_score": None, # Missing engagement
306 "local_relevance": None, # Missing relevance
307 "snippet": None, # Missing snippet
308 }
309 ],
310 },
311 "errors_by_source": {},
312 "warnings": [],
313 })
314
315 findings = store.findings_from_report(report)
316 assert len(findings) == 1
317
318 f = findings[0]
319 assert f["author"] == ""
320 assert f["engagement_score"] == 0.0
321 assert f["relevance_score"] == 0.5
322 assert f["summary"] == "Content" # Falls back to body
323
324
325 def test_findings_from_report_merges_duplicate_url_scores(sample_report):
326 """Duplicate candidate URLs merge higher engagement and relevance into the first finding."""
327 duplicate_candidate = schema.Candidate(
328 candidate_id="c-r2",
329 item_id="R2",
330 source="reddit",
331 title="Duplicate Reddit Post",
332 url="https://reddit.com/r/test/1",
333 snippet="Higher engagement copy",
334 subquery_labels=["secondary"],
335 native_ranks={"reddit": 2},
336 local_relevance=0.95,
337 freshness=100,
338 engagement=125.0,
339 source_quality=0.8,
340 rrf_score=0.9,
341 final_score=0.95,
342 explanation="Duplicate copy with higher engagement",
343 source_items=[],
344 )
345 sample_report.ranked_candidates.append(duplicate_candidate)
346
347 findings = store.findings_from_report(sample_report)
348 reddit_findings = [
349 f for f in findings if f["source_url"] == "https://reddit.com/r/test/1"
350 ]
351 assert len(reddit_findings) == 1
352 assert reddit_findings[0]["source_title"] == "Test Reddit Post"
353 assert reddit_findings[0]["engagement_score"] == 125.0
354 assert reddit_findings[0]["relevance_score"] == 0.95
355
356
357 # === Tests for store_findings() ===
358
359
360 def test_store_findings_basic(temp_db, sample_report):
361 """Test basic storage of findings."""
362 topic = store.add_topic("Test Topic")
363 run_id = store.record_run(topic["id"], source_mode="v3")
364
365 findings = store.findings_from_report(sample_report)
366 counts = store.store_findings(run_id, topic["id"], findings)
367
368 assert counts["new"] == 4
369 assert counts["updated"] == 0
370
371 # Verify in database
372 conn = sqlite3.connect(str(temp_db))
373 total = conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0]
374 assert total == 4
375 conn.close()
376
377
378 def test_store_findings_deduplicates_by_url(temp_db, sample_report):
379 """Test that duplicate URLs are detected and updated, not duplicated."""
380 topic = store.add_topic("Test Topic")
381 run_id = store.record_run(topic["id"], source_mode="v3")
382
383 findings = store.findings_from_report(sample_report)
384
385 # Store once
386 counts1 = store.store_findings(run_id, topic["id"], findings)
387 assert counts1["new"] == 4
388 assert counts1["updated"] == 0
389
390 # Store again (same URLs)
391 counts2 = store.store_findings(run_id, topic["id"], findings)
392 assert counts2["new"] == 0
393 assert counts2["updated"] == 4
394
395 # Verify total count didn't double
396 conn = sqlite3.connect(str(temp_db))
397 total = conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0]
398 assert total == 4
399 conn.close()
400
401
402 def test_store_findings_updates_engagement_on_resighting(temp_db, sample_report):
403 """Test that re-sighting a finding updates engagement score if higher."""
404 topic = store.add_topic("Test Topic")
405 run_id = store.record_run(topic["id"], source_mode="v3")
406
407 findings = store.findings_from_report(sample_report)
408
409 # Store with initial engagement
410 store.store_findings(run_id, topic["id"], findings)
411
412 # Modify engagement score for HN finding
413 hn_finding = next(f for f in findings if f["source"] == "hackernews")
414 hn_finding["engagement_score"] = 200.0 # Higher than original 120.0
415
416 # Store again
417 store.store_findings(run_id, topic["id"], [hn_finding])
418
419 # Verify engagement was updated
420 conn = sqlite3.connect(str(temp_db))
421 score = conn.execute(
422 "SELECT engagement_score FROM findings WHERE source='hackernews'"
423 ).fetchone()[0]
424 assert score == 200.0
425 conn.close()
426
427
428 def test_store_findings_increments_sighting_count(temp_db, sample_report):
429 """Test that re-sighting increments sighting_count."""
430 topic = store.add_topic("Test Topic")
431 run_id = store.record_run(topic["id"], source_mode="v3")
432
433 findings = store.findings_from_report(sample_report)
434
435 # Store once
436 store.store_findings(run_id, topic["id"], findings)
437
438 # Store again
439 store.store_findings(run_id, topic["id"], findings)
440
441 # Verify sighting_count
442 conn = sqlite3.connect(str(temp_db))
443 counts = conn.execute(
444 "SELECT sighting_count FROM findings"
445 ).fetchall()
446
447 for (count,) in counts:
448 assert count == 2 # Seen twice
449 conn.close()
450
451
452 def test_store_findings_upserts_on_concurrent_duplicate_url(temp_db, monkeypatch):
453 """A stale dedup read (a concurrent run that inserted the same URL between
454 our SELECT and INSERT) must upsert, not raise IntegrityError and lose the
455 whole batch. Regression for the SELECT-then-INSERT race in store_findings."""
456 topic = store.add_topic("Test Topic")
457 finding = {
458 "source": "reddit",
459 "source_url": "https://reddit.com/race",
460 "source_title": "Race",
461 "engagement_score": 5.0,
462 }
463
464 # First run inserts the URL.
465 run1 = store.record_run(topic["id"], source_mode="v3")
466 store.store_findings(run1, topic["id"], [finding])
467
468 # Force the dedup lookup to miss the now-existing URL, so store_findings
469 # takes the INSERT path for a row that is already present — exactly what a
470 # racing writer's stale read produces.
471 real_connect = store._connect
472 dedup_prefix = (
473 "SELECT id, source_url, engagement_score FROM findings WHERE source_url IN"
474 )
475
476 class StaleReadConn:
477 def __init__(self, conn):
478 self._conn = conn
479
480 def execute(self, sql, params=()):
481 if sql.strip().startswith(dedup_prefix):
482 return self._conn.execute(
483 "SELECT id, source_url, engagement_score FROM findings WHERE 0"
484 )
485 return self._conn.execute(sql, params)
486
487 def __getattr__(self, name):
488 return getattr(self._conn, name)
489
490 monkeypatch.setattr(
491 store, "_connect", lambda *a, **k: StaleReadConn(real_connect(*a, **k))
492 )
493
494 run2 = store.record_run(topic["id"], source_mode="v3")
495 # Without ON CONFLICT this raises sqlite3.IntegrityError on the UNIQUE
496 # source_url and rolls back the batch.
497 counts = store.store_findings(run2, topic["id"], [{**finding, "engagement_score": 9.0}])
498
499 # The conflict-resolved row is an update, not a new finding. The counters
500 # must reflect that, not inflate findings_new.
501 assert counts == {"new": 0, "updated": 1}
502
503 conn = sqlite3.connect(str(temp_db))
504 rows = conn.execute(
505 "SELECT engagement_score, sighting_count FROM findings WHERE source_url = ?",
506 ("https://reddit.com/race",),
507 ).fetchall()
508 run_counts = conn.execute(
509 "SELECT findings_new, findings_updated FROM research_runs WHERE id = ?",
510 (run2,),
511 ).fetchone()
512 conn.close()
513
514 assert len(rows) == 1 # not duplicated, not crashed
515 assert rows[0][0] == 9.0 # engagement upgraded via max()
516 assert rows[0][1] == 2 # sighting_count bumped by the conflict update
517 assert run_counts == (0, 1) # research_runs counters not inflated
518
519
520 def test_store_findings_collapses_duplicate_urls_within_batch(temp_db):
521 """Duplicate URLs within the same batch must not self-conflict or inflate sighting_count."""
522 topic = store.add_topic("Test Topic")
523 run1 = store.record_run(topic["id"], source_mode="v3")
524 batch = [
525 {
526 "source": "reddit",
527 "source_url": "https://reddit.com/dup",
528 "source_title": "First",
529 "engagement_score": 25.0,
530 "relevance_score": 0.6,
531 },
532 {
533 "source": "reddit",
534 "source_url": "https://reddit.com/dup",
535 "source_title": "Second",
536 "engagement_score": 10.0,
537 "relevance_score": 0.9,
538 },
539 ]
540
541 counts1 = store.store_findings(run1, topic["id"], batch)
542 assert counts1 == {"new": 1, "updated": 0}
543
544 conn = sqlite3.connect(str(temp_db))
545 finding_row = conn.execute(
546 "SELECT source_title, engagement_score, relevance_score, sighting_count "
547 "FROM findings WHERE source_url = ?",
548 ("https://reddit.com/dup",),
549 ).fetchone()
550 sighting_row = conn.execute(
551 "SELECT engagement_score, relevance_score FROM finding_sightings WHERE source_url = ?",
552 ("https://reddit.com/dup",),
553 ).fetchone()
554 conn.close()
555
556 assert finding_row == ("First", 25.0, 0.9, 1)
557 assert sighting_row == (25.0, 0.9)
558
559 run2 = store.record_run(topic["id"], source_mode="v3")
560 counts2 = store.store_findings(run2, topic["id"], batch)
561 assert counts2 == {"new": 0, "updated": 1}
562
563 conn = sqlite3.connect(str(temp_db))
564 sighting_count = conn.execute(
565 "SELECT sighting_count FROM findings WHERE source_url = ?",
566 ("https://reddit.com/dup",),
567 ).fetchone()[0]
568 conn.close()
569 assert sighting_count == 2
570
571
572 def test_store_findings_conflict_upsert_coalesces_null_engagement(temp_db, monkeypatch):
573 """Conflict upsert against a row with NULL engagement_score must upgrade to the new score."""
574 topic = store.add_topic("Test Topic")
575 run1 = store.record_run(topic["id"], source_mode="v3")
576 conn = sqlite3.connect(str(temp_db))
577 conn.execute(
578 "INSERT INTO findings (run_id, topic_id, source, source_url, source_title, engagement_score) "
579 "VALUES (?, ?, 'reddit', 'https://reddit.com/null-eng', 'Null Eng', NULL)",
580 (run1, topic["id"]),
581 )
582 conn.commit()
583 conn.close()
584
585 real_connect = store._connect
586 dedup_prefix = (
587 "SELECT id, source_url, engagement_score FROM findings WHERE source_url IN"
588 )
589
590 class StaleReadConn:
591 def __init__(self, wrapped):
592 self._conn = wrapped
593
594 def execute(self, sql, params=()):
595 if sql.strip().startswith(dedup_prefix):
596 return self._conn.execute(
597 "SELECT id, source_url, engagement_score FROM findings WHERE 0"
598 )
599 return self._conn.execute(sql, params)
600
601 def __getattr__(self, name):
602 return getattr(self._conn, name)
603
604 monkeypatch.setattr(
605 store, "_connect", lambda *a, **k: StaleReadConn(real_connect(*a, **k))
606 )
607
608 run2 = store.record_run(topic["id"], source_mode="v3")
609 counts = store.store_findings(
610 run2,
611 topic["id"],
612 [
613 {
614 "source": "reddit",
615 "source_url": "https://reddit.com/null-eng",
616 "source_title": "Null Eng",
617 "engagement_score": 14.0,
618 }
619 ],
620 )
621 assert counts == {"new": 0, "updated": 1}
622
623 conn = sqlite3.connect(str(temp_db))
624 score = conn.execute(
625 "SELECT engagement_score FROM findings WHERE source_url = ?",
626 ("https://reddit.com/null-eng",),
627 ).fetchone()[0]
628 conn.close()
629 assert score == 14.0
630
631
632
633 def test_store_findings_skips_items_without_url(temp_db):
634 """Test that findings without URLs are skipped."""
635 topic = store.add_topic("Test Topic")
636 run_id = store.record_run(topic["id"], source_mode="v3")
637
638 findings = [
639 {
640 "source": "reddit",
641 "source_url": None, # Missing URL
642 "source_title": "Test",
643 "content": "Content",
644 },
645 {
646 "source": "reddit",
647 "source_url": "https://reddit.com/1", # Has URL
648 "source_title": "Test 2",
649 "content": "Content 2",
650 },
651 ]
652
653 counts = store.store_findings(run_id, topic["id"], findings)
654
655 # Only the one with URL should be stored
656 assert counts["new"] == 1
657
658
659 def test_init_db_creates_finding_sightings_table(temp_db):
660 """Test that the per-run sightings ledger is available on fresh databases."""
661 conn = sqlite3.connect(str(temp_db))
662 table = conn.execute(
663 "SELECT name FROM sqlite_master WHERE type='table' AND name='finding_sightings'"
664 ).fetchone()
665 columns = {
666 row[1]: row[3]
667 for row in conn.execute("PRAGMA table_info(finding_sightings)").fetchall()
668 }
669 conn.close()
670
671 assert table is not None
672 assert columns["finding_id"] == 1
673
674
675 def test_store_findings_records_sightings_for_new_findings(temp_db):
676 """Test that each stored finding is linked to the run that observed it."""
677 topic = store.add_topic("Test Topic")
678 run_id = store.record_run(topic["id"], source_mode="v3")
679 findings = [
680 {
681 "source": "reddit",
682 "source_url": "https://reddit.com/1",
683 "source_title": "Reddit 1",
684 "content": "Content 1",
685 "engagement_score": 10.0,
686 "relevance_score": 0.7,
687 },
688 {
689 "source": "x",
690 "source_url": "https://x.com/a/status/1",
691 "source_title": "X 1",
692 "content": "Content 2",
693 "engagement_score": 20.0,
694 "relevance_score": 0.8,
695 },
696 ]
697
698 store.store_findings(run_id, topic["id"], findings)
699
700 sightings = store.get_sightings_for_run(topic["id"], run_id)
701 assert [s["source_url"] for s in sightings] == [
702 "https://reddit.com/1",
703 "https://x.com/a/status/1",
704 ]
705 assert {s["source"] for s in sightings} == {"reddit", "x"}
706
707
708 def test_store_findings_records_sightings_for_resighted_findings(temp_db):
709 """Test that a re-seen finding is recorded for each run that observes it."""
710 topic = store.add_topic("Test Topic")
711 first_run_id = store.record_run(topic["id"], source_mode="v3")
712 second_run_id = store.record_run(topic["id"], source_mode="v3")
713 finding = {
714 "source": "reddit",
715 "source_url": "https://reddit.com/1",
716 "source_title": "Reddit 1",
717 "content": "Content",
718 "engagement_score": 10.0,
719 "relevance_score": 0.7,
720 }
721
722 store.store_findings(first_run_id, topic["id"], [finding])
723 store.store_findings(second_run_id, topic["id"], [{**finding, "engagement_score": 15.0}])
724
725 first_sightings = store.get_sightings_for_run(topic["id"], first_run_id)
726 second_sightings = store.get_sightings_for_run(topic["id"], second_run_id)
727
728 assert len(first_sightings) == 1
729 assert len(second_sightings) == 1
730 assert first_sightings[0]["source_url"] == second_sightings[0]["source_url"]
731 assert second_sightings[0]["engagement_score"] == 15.0
732
733
734 def test_store_findings_sightings_are_idempotent_per_run(temp_db):
735 """Test that storing the same finding twice for one run does not duplicate sightings."""
736 topic = store.add_topic("Test Topic")
737 run_id = store.record_run(topic["id"], source_mode="v3")
738 finding = {
739 "source": "reddit",
740 "source_url": "https://reddit.com/1",
741 "source_title": "Reddit 1",
742 "content": "Content",
743 "engagement_score": 10.0,
744 "relevance_score": 0.7,
745 }
746
747 store.store_findings(run_id, topic["id"], [finding])
748 store.store_findings(run_id, topic["id"], [finding])
749
750 sightings = store.get_sightings_for_run(topic["id"], run_id)
751 assert len(sightings) == 1
752
753
754 def test_store_findings_updates_existing_sighting_for_same_run(temp_db):
755 """Test that retrying a run refreshes its sighting snapshot instead of freezing it."""
756 topic = store.add_topic("Test Topic")
757 run_id = store.record_run(topic["id"], source_mode="v3")
758 finding = {
759 "source": "reddit",
760 "source_url": "https://reddit.com/1",
761 "source_title": "Reddit 1",
762 "content": "Content",
763 "engagement_score": 10.0,
764 "relevance_score": 0.7,
765 }
766
767 store.store_findings(run_id, topic["id"], [finding])
768 store.store_findings(
769 run_id,
770 topic["id"],
771 [{**finding, "source_title": "Reddit 1 updated", "engagement_score": 15.0}],
772 )
773
774 sightings = store.get_sightings_for_run(topic["id"], run_id)
775 assert len(sightings) == 1
776 assert sightings[0]["source_title"] == "Reddit 1 updated"
777 assert sightings[0]["engagement_score"] == 15.0
778
779
780 def test_get_latest_completed_runs_returns_newest_completed_only(temp_db):
781 """Test latest-run lookup ignores failed runs and orders newest first."""
782 topic = store.add_topic("Test Topic")
783 old_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
784 store.record_run(topic["id"], source_mode="v3", status="failed")
785 latest_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
786
787 runs = store.get_latest_completed_runs(topic["id"], limit=2)
788
789 assert [run["id"] for run in runs] == [latest_run_id, old_run_id]
790
791
792 def test_compute_topic_delta_compares_latest_two_runs(temp_db):
793 """Test watchlist delta classification using per-run sightings."""
794 topic = store.add_topic("Test Topic")
795 previous_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
796 store.store_findings(previous_run_id, topic["id"], [
797 {
798 "source": "reddit",
799 "source_url": "https://reddit.com/continued",
800 "source_title": "Continued",
801 "content": "Still present",
802 "engagement_score": 10.0,
803 "relevance_score": 0.7,
804 },
805 {
806 "source": "x",
807 "source_url": "https://x.com/dropped/status/1",
808 "source_title": "Dropped",
809 "content": "Dropped this run",
810 "engagement_score": 20.0,
811 "relevance_score": 0.8,
812 },
813 ])
814 current_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
815 store.store_findings(current_run_id, topic["id"], [
816 {
817 "source": "reddit",
818 "source_url": "https://reddit.com/continued",
819 "source_title": "Continued",
820 "content": "Still present",
821 "engagement_score": 15.0,
822 "relevance_score": 0.7,
823 },
824 {
825 "source": "github",
826 "source_url": "https://github.com/example/new",
827 "source_title": "New",
828 "content": "New this run",
829 "engagement_score": 30.0,
830 "relevance_score": 0.9,
831 },
832 ])
833
834 delta = store.compute_topic_delta(topic["id"])
835
836 assert delta["status"] == "ok"
837 assert delta["current_run_id"] == current_run_id
838 assert delta["previous_run_id"] == previous_run_id
839 assert delta["new"] == 1
840 assert delta["continued"] == 1
841 assert delta["dropped"] == 1
842 assert [f["source_url"] for f in delta["findings"]["new"]] == ["https://github.com/example/new"]
843 assert [f["source_url"] for f in delta["findings"]["continued"]] == ["https://reddit.com/continued"]
844 assert [f["source_url"] for f in delta["findings"]["dropped"]] == ["https://x.com/dropped/status/1"]
845 assert delta["sources"] == {
846 "github": {"new": 1, "continued": 0, "dropped": 0},
847 "reddit": {"new": 0, "continued": 1, "dropped": 0},
848 "x": {"new": 0, "continued": 0, "dropped": 1},
849 }
850
851
852 def test_compute_topic_delta_requires_two_completed_runs(temp_db):
853 """Test that delta reports insufficient history before two successful runs."""
854 topic = store.add_topic("Test Topic")
855 store.record_run(topic["id"], source_mode="v3", status="completed")
856
857 delta = store.compute_topic_delta(topic["id"])
858
859 assert delta["status"] == "insufficient_history"
860 assert "Need at least two completed runs" in delta["message"]
861
862
863 def test_update_validates_allowed_columns(temp_db, sample_report):
864 """Test update_run/update_finding accept valid keys and reject invalid keys."""
865 topic = store.add_topic("Test Topic")
866 run_id = store.record_run(topic["id"], source_mode="v3")
867
868 # Valid run update key should not raise
869 store.update_run(run_id, status="failed")
870
871 findings = store.findings_from_report(sample_report)
872 store.store_findings(run_id, topic["id"], findings[:1])
873
874 conn = sqlite3.connect(str(temp_db))
875 finding_id = conn.execute("SELECT id FROM findings LIMIT 1").fetchone()[0]
876 conn.close()
877
878 # Valid finding update key should not raise
879 store.update_finding(finding_id, dismissed=1)
880
881 with pytest.raises(ValueError, match="invalid_run_column"):
882 store.update_run(run_id, invalid_run_column="x")
883
884 with pytest.raises(ValueError, match="invalid_finding_column"):
885 store.update_finding(finding_id, invalid_finding_column="x")
886
887 # === Tests for topic management ===
888
889
890 def test_add_topic(temp_db):
891 """Test adding a topic."""
892 topic = store.add_topic("Test Topic", schedule="0 8 * * *")
893
894 assert topic["name"] == "Test Topic"
895 assert topic["schedule"] == "0 8 * * *"
896 assert topic["enabled"] == 1
897
898
899 def test_add_topic_with_search_queries(temp_db):
900 """Test adding a topic with custom search queries."""
901 topic = store.add_topic(
902 "Test Topic",
903 search_queries=["query1", "query2"],
904 schedule="0 8 * * *",
905 )
906
907 assert topic["name"] == "Test Topic"
908 assert json.loads(topic["search_queries"]) == ["query1", "query2"]
909
910
911 def test_persist_report_preserves_existing_watchlist_settings(temp_db, sample_report):
912 import last30days as cli
913
914 topic = store.add_topic(
915 sample_report.topic,
916 search_queries=["custom research query"],
917 schedule="0 8 * * 1",
918 )
919 before = store.get_topic(sample_report.topic)
920
921 counts = cli.persist_report(sample_report, store_db=temp_db)
922
923 after = store.get_topic(sample_report.topic)
924 assert after == before
925 assert after["id"] == topic["id"]
926 assert counts["new"] > 0
927 assert store.get_new_findings(topic["id"])
928
929
930 def test_persist_report_creates_a_missing_watchlist_topic(temp_db, sample_report):
931 import last30days as cli
932
933 assert store.get_topic(sample_report.topic) is None
934
935 counts = cli.persist_report(sample_report, store_db=temp_db)
936
937 topic = store.get_topic(sample_report.topic)
938 assert topic["schedule"] == "0 8 * * *"
939 assert counts["new"] > 0
940
941
942 def test_add_topic_still_updates_explicit_watchlist_configuration(temp_db):
943 first = store.add_topic("Configured topic", search_queries=["old"], schedule="0 8 * * 1")
944
945 updated = store.add_topic("Configured topic", search_queries=["new"], schedule="0 9 * * 2")
946
947 assert updated["id"] == first["id"]
948 assert json.loads(updated["search_queries"]) == ["new"]
949 assert updated["schedule"] == "0 9 * * 2"
950
951
952 def test_remove_topic_cascades_findings(temp_db, sample_report):
953 """Test that removing a topic deletes its findings and runs."""
954 topic = store.add_topic("Test Topic")
955 run_id = store.record_run(topic["id"], source_mode="v3")
956 findings = store.findings_from_report(sample_report)
957 store.store_findings(run_id, topic["id"], findings)
958
959 # Verify data exists
960 conn = sqlite3.connect(str(temp_db))
961 finding_count = conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0]
962 run_count = conn.execute("SELECT COUNT(*) FROM research_runs").fetchone()[0]
963 assert finding_count == 4
964 assert run_count == 1
965 conn.close()
966
967 # Remove topic
968 removed = store.remove_topic("Test Topic")
969 assert removed is True
970
971 # Verify cascade delete
972 conn = sqlite3.connect(str(temp_db))
973 finding_count = conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0]
974 run_count = conn.execute("SELECT COUNT(*) FROM research_runs").fetchone()[0]
975 assert finding_count == 0
976 assert run_count == 0
977 conn.close()
978
979
980 def test_removed_run_usage_preserves_utc_day(temp_db):
981 topic = store.add_topic("Recorded topic")
982 with sqlite3.connect(temp_db) as conn:
983 conn.executemany(
984 "INSERT INTO research_runs (topic_id, run_date, token_cost, cost_unknown) VALUES (?, ?, ?, ?)",
985 [
986 (topic["id"], "2025-03-05 23:59:59", 0.5, 1),
987 (topic["id"], "2025-03-06 00:00:00", 1.25, 0),
988 ],
989 )
990 assert store.remove_topic("Recorded topic")
991 assert store.get_daily_usage("2025-03-05") == (0.5, 1)
992 assert store.get_daily_usage("2025-03-06") == (1.25, 0)
993 assert store.get_daily_usage("2025-03-07") == (0, 0)
994
995
996 def test_list_topics(temp_db):
997 """Test listing topics with stats."""
998 # Add multiple topics
999 store.add_topic("Topic 1")
1000 store.add_topic("Topic 2")
1001 store.add_topic("Topic 3")
1002
1003 topics = store.list_topics()
1004
1005 assert len(topics) == 3
1006 assert {t["name"] for t in topics} == {"Topic 1", "Topic 2", "Topic 3"}
1007
1008 # Check that stats fields are present
1009 for topic in topics:
1010 assert "finding_count" in topic
1011 assert "last_run" in topic
1012 assert "last_status" in topic
1013
1014 # === Tests for get_new_findings() ===
1015
1016
1017 def test_get_new_findings(temp_db, sample_report):
1018 """Test retrieving new findings for a topic."""
1019 topic = store.add_topic("Test Topic")
1020 run_id = store.record_run(topic["id"], source_mode="v3")
1021 findings = store.findings_from_report(sample_report)
1022 store.store_findings(run_id, topic["id"], findings)
1023
1024 new_findings = store.get_new_findings(topic["id"])
1025
1026 assert len(new_findings) == 4
1027 sources = {f["source"] for f in new_findings}
1028 assert "hackernews" in sources
1029 assert "polymarket" in sources
1030
1031
1032 def test_get_new_findings_filters_by_date(temp_db, sample_report):
1033 """Test that since parameter filters findings correctly."""
1034 topic = store.add_topic("Test Topic")
1035 run_id = store.record_run(topic["id"], source_mode="v3")
1036 findings = store.findings_from_report(sample_report)
1037 store.store_findings(run_id, topic["id"], findings)
1038
1039 # Use UTC because store writes first_seen via SQLite's datetime('now') (UTC).
1040 # Local-time math here would flake near midnight UTC.
1041 tomorrow = (datetime.now(timezone.utc) + timedelta(days=1)).strftime("%Y-%m-%d")
1042 new_findings = store.get_new_findings(topic["id"], since=tomorrow)
1043
1044 assert len(new_findings) == 0
1045
1046 yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y-%m-%d")
1047 new_findings = store.get_new_findings(topic["id"], since=yesterday)
1048
1049 assert len(new_findings) == 4
1050
1051 # === Tests for the discovery topic queue (migration 3, U6) ===
1052
1053
1054 def test_init_db_reaches_migration_5_with_discovery_topics_table(temp_db):
1055 """A fresh database lands on migration 5 with the queue table present."""
1056 conn = sqlite3.connect(str(temp_db))
1057 version = conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0]
1058 table = conn.execute(
1059 "SELECT name FROM sqlite_master WHERE type='table' AND name='discovery_topics'"
1060 ).fetchone()
1061 columns = {
1062 row[1] for row in conn.execute("PRAGMA table_info(discovery_topics)").fetchall()
1063 }
1064 conn.close()
1065
1066 assert version == 5
1067 assert table is not None
1068 assert {
1069 "id", "name", "normalized_name", "entity_key", "domain",
1070 "first_surfaced", "last_surfaced", "surface_count", "status",
1071 "covered_at", "last_run_ref",
1072 } <= columns
1073
1074
1075 def test_migration_2_db_upgrades_to_5_without_data_loss(tmp_path, monkeypatch):
1076 """A database built at migration 2 gains the queue table without losing rows."""
1077 db_path = tmp_path / "research.db"
1078 monkeypatch.setattr(store, "_db_override", db_path)
1079 full_migrations = store.MIGRATIONS
1080
1081 monkeypatch.setattr(store, "MIGRATIONS", {2: full_migrations[2]})
1082 store.init_db()
1083 topic = store.add_topic("Preexisting Topic")
1084 with sqlite3.connect(db_path) as conn:
1085 run_id = conn.execute(
1086 "INSERT INTO research_runs (topic_id, run_date, source_mode) VALUES (?, datetime('now'), 'v3')",
1087 (topic["id"],),
1088 ).lastrowid
1089 store.store_findings(run_id, topic["id"], [{
1090 "source": "reddit",
1091 "source_url": "https://reddit.com/preexisting",
1092 "source_title": "Preexisting",
1093 "content": "Content",
1094 }])
1095
1096 conn = sqlite3.connect(str(db_path))
1097 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 2
1098 assert conn.execute(
1099 "SELECT name FROM sqlite_master WHERE type='table' AND name='discovery_topics'"
1100 ).fetchone() is None
1101 conn.close()
1102
1103 monkeypatch.setattr(store, "MIGRATIONS", full_migrations)
1104 store.init_db()
1105
1106 conn = sqlite3.connect(str(db_path))
1107 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 5
1108 assert conn.execute(
1109 "SELECT name FROM sqlite_master WHERE type='table' AND name='discovery_topics'"
1110 ).fetchone() is not None
1111 assert conn.execute("SELECT COUNT(*) FROM topics").fetchone()[0] == 1
1112 assert conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0] == 1
1113 conn.close()
1114
1115
1116 def test_cost_migration_preserves_known_spend_and_marks_legacy_zero_unknown(tmp_path, monkeypatch):
1117 db_path = tmp_path / "research.db"
1118 monkeypatch.setattr(store, "_db_override", db_path)
1119 full_migrations = store.MIGRATIONS
1120 monkeypatch.setattr(store, "MIGRATIONS", {key: value for key, value in full_migrations.items() if key < 4})
1121 store.init_db()
1122 topic = store.add_topic("Legacy")
1123 conn = sqlite3.connect(db_path)
1124 try:
1125 conn.executemany(
1126 "INSERT INTO research_runs (topic_id, run_date, token_cost) VALUES (?, datetime('now'), ?)",
1127 [(topic["id"], 0), (topic["id"], 1.25)],
1128 )
1129 conn.commit()
1130 finally:
1131 conn.close()
1132 monkeypatch.setattr(store, "MIGRATIONS", full_migrations)
1133 store.init_db()
1134 store.init_db()
1135 assert store.get_daily_cost() == 1.25
1136 assert store.get_daily_unknown_cost_runs() == 1
1137 assert store.remove_topic("Legacy")
1138 assert store.get_latest_completed_runs(topic["id"]) == []
1139 assert store.get_daily_cost() == 1.25
1140 assert store.get_daily_unknown_cost_runs() == 1
1141
1142
1143 def test_record_discovery_surfacing_inserts_fresh_row(temp_db):
1144 row = store.record_discovery_surfacing(
1145 "Gemma 4 chat templates",
1146 domain="AI agents",
1147 run_ref="discover:AI agents:2026-07-20T00:00:00+00:00",
1148 as_of="2026-07-20",
1149 )
1150
1151 assert row["name"] == "Gemma 4 chat templates"
1152 assert row["normalized_name"] == "gemma 4 chat templates"
1153 assert row["domain"] == "AI agents"
1154 assert row["surface_count"] == 1
1155 assert row["first_surfaced"] == "2026-07-20"
1156 assert row["last_surfaced"] == "2026-07-20"
1157 assert row["status"] == "surfaced"
1158 assert row["covered_at"] is None
1159 assert row["entity_key"] # computed at write time from entity tokens
1160
1161
1162 def test_record_discovery_surfacing_resurfacing_increments_count(temp_db):
1163 store.record_discovery_surfacing(
1164 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1165 )
1166 # Same normalized identity: casefold, punctuation-stripped, whitespace-collapsed.
1167 row = store.record_discovery_surfacing(
1168 " GEMMA 4 chat, templates! ", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1169 )
1170
1171 assert row["surface_count"] == 2
1172 assert row["first_surfaced"] == "2026-07-13"
1173 assert row["last_surfaced"] == "2026-07-20"
1174 assert row["last_run_ref"] == "run-2"
1175
1176 conn = sqlite3.connect(str(temp_db))
1177 assert conn.execute("SELECT COUNT(*) FROM discovery_topics").fetchone()[0] == 1
1178 conn.close()
1179
1180
1181 def test_record_discovery_surfacing_blank_domain_resurfacing_preserves_prior_domain(temp_db):
1182 """A bare global-trending resurfacing (domain='') must not blank a domain
1183 recorded by an earlier, domain-scoped surfacing of the same topic."""
1184 store.record_discovery_surfacing(
1185 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1186 )
1187
1188 row = store.record_discovery_surfacing(
1189 "Gemma 4 chat templates", domain="", run_ref="run-2", as_of="2026-07-20",
1190 )
1191
1192 assert row["domain"] == "AI agents"
1193 assert row["surface_count"] == 2
1194
1195
1196 def test_record_discovery_surfacing_none_domain_resurfacing_preserves_prior_domain(temp_db):
1197 """If the API is called with domain=None (bypassing the str default),
1198 that must not bind NULL and blank a previously recorded domain either."""
1199 store.record_discovery_surfacing(
1200 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1201 )
1202
1203 row = store.record_discovery_surfacing(
1204 "Gemma 4 chat templates", domain=None, run_ref="run-2", as_of="2026-07-20",
1205 )
1206
1207 assert row["domain"] == "AI agents"
1208 assert row["surface_count"] == 2
1209
1210
1211 def test_record_discovery_surfacing_new_nonempty_domain_still_updates(temp_db):
1212 """A resurfacing that supplies a NEW non-empty domain should still update
1213 the stored domain - only a blank/None incoming domain preserves history."""
1214 store.record_discovery_surfacing(
1215 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1216 )
1217
1218 row = store.record_discovery_surfacing(
1219 "Gemma 4 chat templates", domain="LLM tooling", run_ref="run-2", as_of="2026-07-20",
1220 )
1221
1222 assert row["domain"] == "LLM tooling"
1223 assert row["surface_count"] == 2
1224
1225
1226 def test_match_discovery_topic_exact_normalized_name(temp_db):
1227 store.record_discovery_surfacing(
1228 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-20",
1229 )
1230
1231 match = store.match_discovery_topic("gemma 4 CHAT templates!")
1232
1233 assert match is not None
1234 assert match["normalized_name"] == "gemma 4 chat templates"
1235
1236
1237 def test_match_discovery_topic_cross_matches_near_duplicates_without_merging(temp_db):
1238 """Two angles on the same subject cross-match for annotation, but recording
1239 both keeps both rows - matching NEVER merges."""
1240 store.record_discovery_surfacing(
1241 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1242 )
1243
1244 match = store.match_discovery_topic("Gemma 4 tool calling fixes")
1245 assert match is not None
1246 assert match["normalized_name"] == "gemma 4 chat templates"
1247
1248 store.record_discovery_surfacing(
1249 "Gemma 4 tool calling fixes", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1250 )
1251
1252 conn = sqlite3.connect(str(temp_db))
1253 rows = conn.execute(
1254 "SELECT normalized_name, surface_count FROM discovery_topics ORDER BY id"
1255 ).fetchall()
1256 conn.close()
1257 assert rows == [
1258 ("gemma 4 chat templates", 1),
1259 ("gemma 4 tool calling fixes", 1),
1260 ]
1261
1262
1263 def test_match_discovery_topic_unrelated_names_do_not_match(temp_db):
1264 store.record_discovery_surfacing(
1265 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-20",
1266 )
1267
1268 assert store.match_discovery_topic("OpenAI Agent SDK pricing") is None
1269 assert store.match_discovery_topic("Rust async runtime debates") is None
1270
1271
1272 def test_match_discovery_topic_empty_queue_returns_none(temp_db):
1273 assert store.match_discovery_topic("Anything at all") is None
1274
1275
1276 def test_record_discovery_surfacing_inherit_covered_creates_row_born_covered(temp_db):
1277 """A fresh row recorded with inherit_covered_at is born covered - the
1278 caller passes it when the name fuzzy-matched an already-covered prior,
1279 so a user's covered mark survives judge naming drift (review #7)."""
1280 row = store.record_discovery_surfacing(
1281 "Gemma 4 template fixes", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1282 inherit_covered_at="2026-07-14",
1283 )
1284
1285 assert row["status"] == "covered"
1286 assert row["covered_at"] == "2026-07-14"
1287 assert row["surface_count"] == 1
1288
1289
1290 def test_record_discovery_surfacing_inherit_never_alters_existing_row_status(temp_db):
1291 """The ON CONFLICT path ignores inherit_covered_at: an existing surfaced
1292 row stays surfaced, and an existing covered row stays covered with its
1293 original covered_at."""
1294 store.record_discovery_surfacing(
1295 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1296 )
1297 row = store.record_discovery_surfacing(
1298 "Gemma 4 chat templates", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1299 inherit_covered_at="2026-07-14",
1300 )
1301 assert row["status"] == "surfaced"
1302 assert row["covered_at"] is None
1303
1304 store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-21")
1305 row = store.record_discovery_surfacing(
1306 "Gemma 4 chat templates", domain="AI agents", run_ref="run-3", as_of="2026-07-22",
1307 inherit_covered_at=None,
1308 )
1309 assert row["status"] == "covered"
1310 assert row["covered_at"] == "2026-07-21"
1311
1312
1313 def test_covered_status_survives_judge_rename_across_runs(temp_db):
1314 """Flip-flop regression (review #7): cover name A; a fuzzy-matching
1315 rename B is recorded born-covered; resurfacing B exact-matches its own
1316 covered row, so the covered mark never silently evaporates."""
1317 store.record_discovery_surfacing(
1318 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1319 )
1320 store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-14")
1321
1322 prior = store.match_discovery_topic("Gemma 4 template fixes")
1323 assert prior is not None and prior["status"] == "covered"
1324 store.record_discovery_surfacing(
1325 "Gemma 4 template fixes", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1326 inherit_covered_at=prior["covered_at"],
1327 )
1328
1329 exact = store.match_discovery_topic("Gemma 4 template fixes")
1330 assert exact is not None
1331 assert exact["status"] == "covered"
1332 assert exact["covered_at"] == "2026-07-14"
1333
1334
1335 def test_record_discovery_surfacing_same_run_ref_is_idempotent(temp_db):
1336 """AE6: a retry within the same run identity (e.g. --finalize re-run with
1337 a corrected angles file) never double-counts - the guarded call returns
1338 the row unchanged."""
1339 first = store.record_discovery_surfacing(
1340 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1341 )
1342 retry = store.record_discovery_surfacing(
1343 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-20",
1344 )
1345
1346 assert retry["surface_count"] == 1
1347 assert retry["last_surfaced"] == "2026-07-13"
1348 assert retry == first
1349
1350
1351 def test_record_discovery_surfacing_same_run_ref_is_idempotent_concurrently(temp_db, monkeypatch):
1352 real_connect = store._connect
1353 barrier = threading.Barrier(2)
1354
1355 class CoordinatedConnection:
1356 def __init__(self, conn):
1357 self._conn = conn
1358
1359 def execute(self, sql, params=()):
1360 if sql.strip().startswith("INSERT INTO discovery_topics"):
1361 barrier.wait(timeout=5)
1362 return self._conn.execute(sql, params)
1363
1364 def __getattr__(self, name):
1365 return getattr(self._conn, name)
1366
1367 monkeypatch.setattr(store, "init_db", lambda: None)
1368 monkeypatch.setattr(
1369 store,
1370 "_connect",
1371 lambda *args, **kwargs: CoordinatedConnection(real_connect(*args, **kwargs)),
1372 )
1373
1374 with ThreadPoolExecutor(max_workers=2) as pool:
1375 futures = [
1376 pool.submit(
1377 store.record_discovery_surfacing,
1378 "Gemma 4 chat templates",
1379 domain="AI agents",
1380 run_ref="run-1",
1381 as_of="2026-11-30",
1382 )
1383 for _ in range(2)
1384 ]
1385 rows = [future.result(timeout=10) for future in futures]
1386
1387 assert [row["surface_count"] for row in rows] == [1, 1]
1388 conn = sqlite3.connect(str(temp_db))
1389 try:
1390 count = conn.execute(
1391 "SELECT surface_count FROM discovery_topics WHERE normalized_name = ?",
1392 (store._normalize_discovery_name("Gemma 4 chat templates"),),
1393 ).fetchone()[0]
1394 finally:
1395 conn.close()
1396 assert count == 1
1397
1398
1399 def test_record_discovery_surfacing_guard_is_per_run_not_global(temp_db):
1400 """A later run with a DIFFERENT run_ref still increments: the idempotency
1401 guard binds to one run identity, never to the row."""
1402 store.record_discovery_surfacing(
1403 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1404 )
1405 store.record_discovery_surfacing(
1406 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1407 )
1408 row = store.record_discovery_surfacing(
1409 "Gemma 4 chat templates", domain="AI agents", run_ref="run-2", as_of="2026-07-20",
1410 )
1411
1412 assert row["surface_count"] == 2
1413 assert row["last_surfaced"] == "2026-07-20"
1414 assert row["last_run_ref"] == "run-2"
1415
1416
1417 def test_record_discovery_surfacing_same_run_ref_never_touches_covered(temp_db):
1418 """The guard obeys the existing never-mutate rule: a retry against a
1419 covered row leaves status/covered_at exactly as the user set them."""
1420 store.record_discovery_surfacing(
1421 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1422 )
1423 store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-14")
1424
1425 retry = store.record_discovery_surfacing(
1426 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-20",
1427 inherit_covered_at="2026-07-19",
1428 )
1429
1430 assert retry["surface_count"] == 1
1431 assert retry["status"] == "covered"
1432 assert retry["covered_at"] == "2026-07-14"
1433
1434
1435 def test_record_discovery_surfacing_blank_run_ref_keeps_legacy_increment(temp_db):
1436 """Callers that pass no run_ref (blank) keep the pre-guard behavior:
1437 every surfacing increments. The guard only binds real run identities."""
1438 store.record_discovery_surfacing(
1439 "Gemma 4 chat templates", domain="AI agents", as_of="2026-07-13",
1440 )
1441 row = store.record_discovery_surfacing(
1442 "Gemma 4 chat templates", domain="AI agents", as_of="2026-07-20",
1443 )
1444
1445 assert row["surface_count"] == 2
1446
1447
1448 def test_mark_discovery_covered_by_exact_name(temp_db):
1449 store.record_discovery_surfacing(
1450 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1451 )
1452
1453 row = store.mark_discovery_covered("Gemma 4 chat templates", as_of="2026-07-20")
1454
1455 assert row is not None
1456 assert row["status"] == "covered"
1457 assert row["covered_at"] == "2026-07-20"
1458
1459
1460 def test_mark_discovery_covered_unknown_name_returns_none(temp_db):
1461 store.record_discovery_surfacing(
1462 "Gemma 4 chat templates", domain="AI agents", run_ref="run-1", as_of="2026-07-13",
1463 )
1464
1465 # Exact normalized match required: a near-duplicate must NOT cover the row.
1466 assert store.mark_discovery_covered("Gemma 4 tool calling fixes", as_of="2026-07-20") is None
1467 assert store.mark_discovery_covered("No Such Topic", as_of="2026-07-20") is None
1468
1469
1470 def test_list_discovery_queue_orders_by_last_surfaced_and_filters_status(temp_db):
1471 store.record_discovery_surfacing("Older topic", domain="d", run_ref="r1", as_of="2026-07-01")
1472 store.record_discovery_surfacing("Newer topic", domain="d", run_ref="r2", as_of="2026-07-19")
1473 store.record_discovery_surfacing("Covered topic", domain="d", run_ref="r3", as_of="2026-07-10")
1474 store.mark_discovery_covered("Covered topic", as_of="2026-07-20")
1475
1476 all_rows = store.list_discovery_queue()
1477 assert [r["name"] for r in all_rows] == ["Newer topic", "Covered topic", "Older topic"]
1478
1479 surfaced = store.list_discovery_queue(status="surfaced")
1480 assert [r["name"] for r in surfaced] == ["Newer topic", "Older topic"]
1481
1482 covered = store.list_discovery_queue(status="covered")
1483 assert [r["name"] for r in covered] == ["Covered topic"]
1484
1485
1486 def test_store_findings_none_engagement_on_update_does_not_crash(temp_db):
1487 """Regression: store_findings must not TypeError when an update-path finding
1488 carries engagement_score=None.
1489
1490 .get("engagement_score", 0) only substitutes 0 for an *absent* key, so a
1491 present-but-None value reached max(None, existing) on the update branch.
1492 store_findings accepts arbitrary List[Dict[str, Any]] callers, so the
1493 boundary must stay null-safe (engagement_score is float | None in schema.py).
1494 """
1495 topic_id = store.add_topic("None Engagement Topic")["id"]
1496 url = "https://example.com/none-engagement"
1497 base = {
1498 "source": "reddit",
1499 "source_url": url,
1500 "source_title": "T",
1501 "author": "",
1502 "content": "",
1503 "summary": "",
1504 "relevance_score": 0.5,
1505 }
1506
1507 # First sighting carries a real engagement score.
1508 run1 = store.record_run(topic_id, source_mode="test", status="running")
1509 store.store_findings(run1, topic_id, [{**base, "engagement_score": 5.0}])
1510
1511 # Re-sighting the same URL with engagement_score=None takes the UPDATE branch;
1512 # before the fix this raised TypeError from max(None, 5.0).
1513 run2 = store.record_run(topic_id, source_mode="test", status="running")
1514 counts = store.store_findings(run2, topic_id, [{**base, "engagement_score": None}])
1515 assert counts["updated"] == 1
1516
1517 con = sqlite3.connect(str(temp_db))
1518 try:
1519 stored = con.execute(
1520 "SELECT engagement_score FROM findings WHERE source_url = ?", (url,)
1521 ).fetchone()[0]
1522 finally:
1523 con.close()
1524 # max(None -> 0, existing 5.0) keeps the higher real score.
1525 assert stored == 5.0
1526
1527
1528 if __name__ == "__main__":
1529 pytest.main([__file__, "-v"])
1530
1531
1532 def test_scoped_db_routes_all_store_access_and_restores(tmp_path):
1533 scoped = tmp_path / "client" / "research.db"
1534 scoped.parent.mkdir()
1535 before = store._db_override
1536
1537 with store.scoped_db(scoped):
1538 assert store._get_db_path() == scoped
1539 store.init_db()
1540
1541 assert store._db_override == before
1542 assert scoped.is_file()
1543
1544
1545 def test_scoped_db_with_none_is_a_no_op(tmp_path):
1546 before = store._db_override
1547 with store.scoped_db(None):
1548 assert store._get_db_path() == (before or store.DB_PATH)
1549 assert store._db_override == before
1550
1551
1552 def test_persist_report_with_scoped_store_writes_inside_save_dir(tmp_path, sample_report):
1553 import last30days as cli
1554
1555 shared = tmp_path / "shared.db"
1556 scoped = tmp_path / "client" / "research.db"
1557 scoped.parent.mkdir()
1558 original_override = store._db_override
1559 store._db_override = shared
1560 try:
1561 store.init_db()
1562 counts = cli.persist_report(sample_report, store_db=scoped)
1563 finally:
1564 store._db_override = original_override
1565
1566 assert counts["new"] > 0
1567 assert scoped.is_file()
1568 with sqlite3.connect(scoped) as conn:
1569 assert conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0] > 0
1570 # The shared store saw no findings from the scoped run.
1571 with sqlite3.connect(shared) as conn:
1572 assert conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0] == 0
1573
1574
1575 @pytest.mark.parametrize("value", ["7dd", "-1d", "d", "7", "1w", "7D", ""])
1576 def test_store_query_since_rejects_malformed_durations(value, monkeypatch, capsys):
1577 monkeypatch.setattr(sys, "argv", ["store.py", "query", "Test", f"--since={value}"])
1578 monkeypatch.setattr(
1579 store, "init_db", lambda: pytest.fail("malformed --since reached database setup")
1580 )
1581
1582 with pytest.raises(SystemExit) as exc_info:
1583 store.main()
1584
1585 assert exc_info.value.code == 2
1586 assert "non-negative integer duration" in capsys.readouterr().err
1587
1588
1589 @pytest.mark.parametrize(
1590 "value",
1591 [
1592 pytest.param("1000000000d", id="timedelta-overflow"),
1593 pytest.param("10000000d", id="datetime-underflow"),
1594 ],
1595 )
1596 def test_store_query_since_rejects_out_of_range_durations(value, monkeypatch, capsys):
1597 monkeypatch.setattr(sys, "argv", ["store.py", "query", "Test", f"--since={value}"])
1598 monkeypatch.setattr(
1599 store, "init_db", lambda: pytest.fail("out-of-range --since reached database setup")
1600 )
1601
1602 with pytest.raises(SystemExit) as exc_info:
1603 store.main()
1604
1605 assert exc_info.value.code == 2
1606 assert "argument --since: duration is out of range" in capsys.readouterr().err
1607
1608
1609 @pytest.mark.parametrize(
1610 ("value", "expected"),
1611 [("0d", "2026-11-30"), ("7d", "2026-11-23"), ("30d", "2026-10-31")],
1612 )
1613 def test_store_query_since_accepts_non_negative_day_durations(
1614 value, expected, monkeypatch
1615 ):
1616 class FixedDateTime:
1617 @staticmethod
1618 def now(tz):
1619 return datetime(2026, 11, 30, tzinfo=timezone.utc)
1620
1621 seen = []
1622 monkeypatch.setattr(store, "datetime", FixedDateTime)
1623 monkeypatch.setattr(store, "init_db", lambda: None)
1624 monkeypatch.setattr(store, "get_topic", lambda name: {"id": 1, "name": name})
1625 monkeypatch.setattr(
1626 store, "get_new_findings", lambda topic_id, since: seen.append(since) or []
1627 )
1628 monkeypatch.setattr(sys, "argv", ["store.py", "query", "Test", f"--since={value}"])
1629
1630 store.main()
1631
1632 assert seen == [expected]
1633
1633 lines PYTHON