Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(store): count conflict-resolved upserts as updates, not new

Ilia Alshanetsky87d2be30b1b8
diff --git a/skills/last30days/scripts/store.py b/skills/last30days/scripts/store.py
index 22e1f7f4..4e058c01 100644
--- a/skills/last30days/scripts/store.py
+++ b/skills/last30days/scripts/store.py
@@ -476,6 +476,21 @@ def store_findings(
new_count = len(insert_rows)
updated_count = len(update_rows)
+ if insert_rows:
+ # A row whose URL was inserted by a concurrent run between our SELECT
+ # and the upsert resolves via ON CONFLICT (an update, not a new row),
+ # bumping its sighting_count above 1. Re-derive the split so
+ # research_runs.findings_new isn't inflated by conflict-resolved rows
+ # (source_url is field index 3 in each insert tuple).
+ inserted_urls = [row[3] for row in insert_rows]
+ placeholders = ",".join("?" for _ in inserted_urls)
+ conflicted = conn.execute(
+ f"SELECT COUNT(*) FROM findings "
+ f"WHERE source_url IN ({placeholders}) AND sighting_count > 1",
+ inserted_urls,
+ ).fetchone()[0]
+ new_count -= conflicted
+ updated_count += conflicted
_record_sightings(conn, run_id, topic_id, with_urls, existing_by_url)
conn.execute(
"UPDATE research_runs SET findings_new = ?, findings_updated = ? WHERE id = ?",
diff --git a/tests/test_store.py b/tests/test_store.py
index 523d554d..dccf620b 100644
--- a/tests/test_store.py
+++ b/tests/test_store.py
@@ -464,18 +464,27 @@ def test_store_findings_upserts_on_concurrent_duplicate_url(temp_db, monkeypatch
run2 = store.record_run(topic["id"], source_mode="v3")
# Without ON CONFLICT this raises sqlite3.IntegrityError on the UNIQUE
# source_url and rolls back the batch.
- store.store_findings(run2, topic["id"], [{**finding, "engagement_score": 9.0}])
+ counts = store.store_findings(run2, topic["id"], [{**finding, "engagement_score": 9.0}])
+
+ # The conflict-resolved row is an update, not a new finding. The counters
+ # must reflect that, not inflate findings_new.
+ assert counts == {"new": 0, "updated": 1}
conn = sqlite3.connect(str(temp_db))
rows = conn.execute(
"SELECT engagement_score, sighting_count FROM findings WHERE source_url = ?",
("https://reddit.com/race",),
).fetchall()
+ run_counts = conn.execute(
+ "SELECT findings_new, findings_updated FROM research_runs WHERE id = ?",
+ (run2,),
+ ).fetchone()
conn.close()
assert len(rows) == 1 # not duplicated, not crashed
assert rows[0][0] == 9.0 # engagement upgraded via max()
assert rows[0][1] == 2 # sighting_count bumped by the conflict update
+ assert run_counts == (0, 1) # research_runs counters not inflated
def test_store_findings_skips_items_without_url(temp_db):