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): serialize concurrent writers and upsert on URL conflict

Ilia Alshanetsky6ef466d43f1d
diff --git a/skills/last30days/scripts/store.py b/skills/last30days/scripts/store.py
index ddf33661..22e1f7f4 100644
--- a/skills/last30days/scripts/store.py
+++ b/skills/last30days/scripts/store.py
@@ -193,6 +193,10 @@ def _connect(db_path: Optional[Path] = None) -> sqlite3.Connection:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
+ # WAL lets readers coexist with one writer, but two writers (cron + user)
+ # still contend for the write lock. Default busy_timeout is 0, so the loser
+ # raises "database is locked" instantly; wait instead.
+ conn.execute("PRAGMA busy_timeout=5000")
return conn
@@ -452,11 +456,21 @@ def store_findings(
update_rows,
)
if insert_rows:
+ # source_url is UNIQUE. The SELECT above is not atomic with this
+ # write, so a concurrent run (cron + user) can insert the same URL
+ # between our read and write. Upsert on conflict instead of letting
+ # IntegrityError abort the whole batch and lose every finding.
conn.executemany(
"""INSERT INTO findings
(run_id, topic_id, source, source_url, source_title,
author, content, summary, engagement_score, relevance_score)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(source_url) DO UPDATE SET
+ last_seen = datetime('now'),
+ sighting_count = sighting_count + 1,
+ engagement_score = max(
+ engagement_score, excluded.engagement_score),
+ run_id = excluded.run_id""",
insert_rows,
)
diff --git a/tests/test_store.py b/tests/test_store.py
index 3de24fc9..523d554d 100644
--- a/tests/test_store.py
+++ b/tests/test_store.py
@@ -419,6 +419,65 @@ def test_store_findings_increments_sighting_count(temp_db, sample_report):
conn.close()
+def test_store_findings_upserts_on_concurrent_duplicate_url(temp_db, monkeypatch):
+ """A stale dedup read (a concurrent run that inserted the same URL between
+ our SELECT and INSERT) must upsert, not raise IntegrityError and lose the
+ whole batch. Regression for the SELECT-then-INSERT race in store_findings."""
+ topic = store.add_topic("Test Topic")
+ finding = {
+ "source": "reddit",
+ "source_url": "https://reddit.com/race",
+ "source_title": "Race",
+ "engagement_score": 5.0,
+ }
+
+ # First run inserts the URL.
+ run1 = store.record_run(topic["id"], source_mode="v3")
+ store.store_findings(run1, topic["id"], [finding])
+
+ # Force the dedup lookup to miss the now-existing URL, so store_findings
+ # takes the INSERT path for a row that is already present — exactly what a
+ # racing writer's stale read produces.
+ real_connect = store._connect
+ dedup_prefix = (
+ "SELECT id, source_url, engagement_score FROM findings WHERE source_url IN"
+ )
+
+ class StaleReadConn:
+ def __init__(self, conn):
+ self._conn = conn
+
+ def execute(self, sql, params=()):
+ if sql.strip().startswith(dedup_prefix):
+ return self._conn.execute(
+ "SELECT id, source_url, engagement_score FROM findings WHERE 0"
+ )
+ return self._conn.execute(sql, params)
+
+ def __getattr__(self, name):
+ return getattr(self._conn, name)
+
+ monkeypatch.setattr(
+ store, "_connect", lambda *a, **k: StaleReadConn(real_connect(*a, **k))
+ )
+
+ 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}])
+
+ conn = sqlite3.connect(str(temp_db))
+ rows = conn.execute(
+ "SELECT engagement_score, sighting_count FROM findings WHERE source_url = ?",
+ ("https://reddit.com/race",),
+ ).fetchall()
+ 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
+
+
def test_store_findings_skips_items_without_url(temp_db):
"""Test that findings without URLs are skipped."""
topic = store.add_topic("Test Topic")