siddhm11 Claude Opus 5.5 commited on
Commit
38f3b7d
·
1 Parent(s): 9cdb19f

feat(daily): keep a history of citation counts

Browse files

The citation step overwrote about 7,700 changed counts a day and kept no
earlier value, so citation growth could never be computed. Each overwrite now
also writes (before, after) to a citation_history table in Turso, in the same
transaction as the update, one row per paper per day the count moved. Growth
over any window is the sum of (citations - citations_before) for its rows.

Same-day re-runs upsert and keep the first run's before value. Checked on
Turso inside a rolled-back transaction; the table exists and is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

scripts/daily_refresh.py CHANGED
@@ -137,6 +137,36 @@ def changed_counts(current: dict[str, tuple[int, int]], fetched: dict[str, dict
137
  return out
138
 
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  def verify_counts(before: dict, after: dict, ingest_new: int | None) -> list[str]:
141
  problems = []
142
  dq = after["recent_points"] - before["recent_points"]
@@ -202,13 +232,20 @@ def stage_citations(st: Stores, prefix: str) -> dict:
202
  raise SystemExit(f"Semantic Scholar batch failed at {chunk[0]}")
203
  fetched.update(zip(chunk, res))
204
  changes = changed_counts(current, fetched)
 
 
205
  sql = "UPDATE papers SET citation_count = ?, influential_citations = ? WHERE arxiv_id = ?"
206
  for i in range(0, len(changes), 500):
207
- st.t_many([{"sql": sql, "args": [{"type": "integer", "value": str(c)},
208
- {"type": "integer", "value": str(f)},
209
- {"type": "text", "value": a}]} for a, c, f in changes[i:i + 500]])
 
 
 
 
 
210
  found = sum(1 for v in fetched.values() if v)
211
- return {"papers": len(ids), "found": found, "changed": len(changes)}
212
 
213
 
214
  def licence_coverage(codes: list[str | None]) -> dict:
 
137
  return out
138
 
139
 
140
+ # Citation history. The papers table keeps only the latest count, so before the
141
+ # update overwrites a count, the old and new values are written here. Growth over
142
+ # any window is then the sum of (citations - citations_before) for the rows in it,
143
+ # with no baseline snapshot. Trending in every field reads this (doc 06,
144
+ # 2026-10-23); until it existed every overwritten count was lost.
145
+ HISTORY_DDL = ("CREATE TABLE IF NOT EXISTS citation_history ("
146
+ "arxiv_id TEXT NOT NULL, checked_on TEXT NOT NULL, "
147
+ "citations_before INTEGER NOT NULL, citations INTEGER NOT NULL, "
148
+ "influential_before INTEGER NOT NULL, influential INTEGER NOT NULL, "
149
+ "PRIMARY KEY (arxiv_id, checked_on))")
150
+
151
+
152
+ def history_rows(current: dict[str, tuple[int, int]], changes: list[tuple[str, int, int]],
153
+ day: str) -> list[tuple[str, str, int, int, int, int]]:
154
+ """(arxiv_id, day, citations_before, citations, influential_before, influential)."""
155
+ return [(a, day, current[a][0], c, current[a][1], f) for a, c, f in changes]
156
+
157
+
158
+ def history_insert(rows: list[tuple]) -> dict:
159
+ """One multi-row upsert. A second run on the same day keeps the first run's
160
+ `before` values, so a day's row always spans the whole day's change."""
161
+ sql = ("INSERT INTO citation_history (arxiv_id, checked_on, citations_before, citations, "
162
+ "influential_before, influential) VALUES " + ", ".join(["(?, ?, ?, ?, ?, ?)"] * len(rows))
163
+ + " ON CONFLICT (arxiv_id, checked_on) DO UPDATE SET "
164
+ "citations = excluded.citations, influential = excluded.influential")
165
+ args = [{"type": "integer" if isinstance(v, int) else "text", "value": str(v)}
166
+ for row in rows for v in row]
167
+ return {"sql": sql, "args": args}
168
+
169
+
170
  def verify_counts(before: dict, after: dict, ingest_new: int | None) -> list[str]:
171
  problems = []
172
  dq = after["recent_points"] - before["recent_points"]
 
232
  raise SystemExit(f"Semantic Scholar batch failed at {chunk[0]}")
233
  fetched.update(zip(chunk, res))
234
  changes = changed_counts(current, fetched)
235
+ day = dt.datetime.now(dt.timezone.utc).date().isoformat()
236
+ st.t(HISTORY_DDL)
237
  sql = "UPDATE papers SET citation_count = ?, influential_citations = ? WHERE arxiv_id = ?"
238
  for i in range(0, len(changes), 500):
239
+ batch = changes[i:i + 500]
240
+ # One transaction per batch: a history row without its update would be
241
+ # counted again by the next run, and an update without its row is lost.
242
+ st.t_many([{"sql": "BEGIN"}]
243
+ + [{"sql": sql, "args": [{"type": "integer", "value": str(c)},
244
+ {"type": "integer", "value": str(f)},
245
+ {"type": "text", "value": a}]} for a, c, f in batch]
246
+ + [history_insert(history_rows(current, batch, day)), {"sql": "COMMIT"}])
247
  found = sum(1 for v in fetched.values() if v)
248
+ return {"papers": len(ids), "found": found, "changed": len(changes), "history_rows": len(changes)}
249
 
250
 
251
  def licence_coverage(codes: list[str | None]) -> dict:
tests/test_daily_refresh.py CHANGED
@@ -35,6 +35,30 @@ def test_only_changed_known_counts_are_written():
35
  assert dr.changed_counts(current, fetched) == [("b", 12, 2)]
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def test_verify_counts_catches_mismatches():
39
  before = {"recent_points": 100, "turso_rows": 1000, "turso_max_rowid": 1000}
40
  ok = {"recent_points": 150, "turso_rows": 1050, "turso_max_rowid": 1050}
 
35
  assert dr.changed_counts(current, fetched) == [("b", 12, 2)]
36
 
37
 
38
+ def test_history_rows_keep_the_count_being_overwritten():
39
+ current = {"a": (5, 1), "b": (0, 0)}
40
+ assert dr.history_rows(current, [("b", 12, 2)], "2026-10-24") == [("b", "2026-10-24", 0, 12, 0, 2)]
41
+
42
+
43
+ def _run(conn, stmt):
44
+ conn.execute(stmt["sql"], [int(a["value"]) if a["type"] == "integer" else a["value"]
45
+ for a in stmt.get("args", [])])
46
+
47
+
48
+ def test_history_upsert_spans_the_whole_day_and_sums_to_the_growth():
49
+ import sqlite3
50
+ conn = sqlite3.connect(":memory:")
51
+ conn.execute(dr.HISTORY_DDL)
52
+ _run(conn, dr.history_insert([("b", "2026-10-24", 0, 12, 0, 2), ("c", "2026-10-24", 3, 4, 0, 0)]))
53
+ _run(conn, dr.history_insert([("b", "2026-10-24", 12, 15, 2, 3)])) # second run, same day
54
+ _run(conn, dr.history_insert([("b", "2026-10-25", 15, 16, 3, 3)]))
55
+ assert conn.execute("SELECT citations_before, citations FROM citation_history "
56
+ "WHERE arxiv_id = 'b' ORDER BY checked_on").fetchall() == [(0, 15), (15, 16)]
57
+ gain = conn.execute("SELECT SUM(citations - citations_before) FROM citation_history "
58
+ "WHERE arxiv_id = 'b'").fetchone()[0]
59
+ assert gain == 16
60
+
61
+
62
  def test_verify_counts_catches_mismatches():
63
  before = {"recent_points": 100, "turso_rows": 1000, "turso_max_rowid": 1000}
64
  ok = {"recent_points": 150, "turso_rows": 1050, "turso_max_rowid": 1050}