Spaces:
Running

siddhm11 commited on
Commit
752a985
Β·
unverified Β·
2 Parent(s): 8e329f7e1332a9

Merge pull request #80 from siddhm11/feat/hn-data

Browse files

feat(daily): record every Hacker News link to an arXiv paper

scripts/daily_refresh.py CHANGED
@@ -20,16 +20,20 @@ Stages, each with a check that fails the run
20
  2. hf_daily the last two weeks of Hugging Face Daily Papers lists, with
21
  each paper's upvotes as of today, into hf_daily_papers and
22
  hf_upvote_history (reported, never fails the run)
23
- 3. ingest scripts/ingest_arxiv.py over [today - lookback, today + 1);
 
 
 
 
24
  re-run once if its coverage check reports a gap (exit 3)
25
- 4. citations Semantic Scholar counts for papers from the last 3 months;
26
  only changed rows are written
27
- 5. verify new Qdrant points == new Turso rows == papers the ingest
28
  reported; sampled new vectors are 1024-dim unit vectors and
29
  their Turso rows are complete
30
- 6. licences how many new papers have a `paper_licences` row, and how many
31
  of those may show figures (reported, never fails the run)
32
- 7. summary printed as JSON, and to $GITHUB_STEP_SUMMARY when set
33
 
34
  Re-running is always safe: the ingest skips papers already stored and point
35
  ids are derived from the arXiv id, so overlapping runs cannot collide.
@@ -39,6 +43,8 @@ Usage
39
  python scripts/daily_refresh.py # the daily run
40
  python scripts/daily_refresh.py --dry-run # stages 1 and 6 only
41
  python scripts/daily_refresh.py --hf-only --hf-days 182 # backfill the history
 
 
42
  """
43
  from __future__ import annotations
44
 
@@ -61,6 +67,8 @@ import httpx
61
  HERE = Path(__file__).resolve().parent
62
  sys.path.insert(0, str(HERE.parent))
63
  from app import hf_papers_svc, licences # noqa: E402 (standard library and httpx only)
 
 
64
 
65
  REQUIRED_ENV = ("QDRANT_RECENT_URL", "QDRANT_RECENT_API_KEY", "TURSO_URL", "TURSO_DB_TOKEN")
66
  COLLECTION = os.getenv("QDRANT_RECENT_COLLECTION", "arxiv_recent")
@@ -419,6 +427,15 @@ def stage_hf_daily(st: Stores, today: dt.date, days: int = HF_DAYS,
419
  return out
420
 
421
 
 
 
 
 
 
 
 
 
 
422
  def licence_coverage(codes: list[str | None]) -> dict:
423
  """One code per new paper; None or "" when it has no licence row."""
424
  known = [c for c in codes if c]
@@ -482,6 +499,10 @@ def main() -> int:
482
  help="Daily Papers lists to record, today included")
483
  ap.add_argument("--skip-hf", action="store_true")
484
  ap.add_argument("--hf-only", action="store_true", help="record the lists, then stop")
 
 
 
 
485
  args = ap.parse_args()
486
 
487
  summary: dict = {"started": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
@@ -503,12 +524,18 @@ def main() -> int:
503
  return _finish(summary, 0)
504
 
505
  # Before the ingest, so a failed ingest cannot cost a day of history.
506
- if not args.skip_hf:
507
  t0 = time.time()
508
  summary["hf_daily"] = stage_hf_daily(st, today, args.hf_days)
509
  summary["hf_daily"]["minutes"] = round((time.time() - t0) / 60, 1)
510
  if args.hf_only:
511
  return _finish(summary, 0)
 
 
 
 
 
 
512
 
513
  t0 = time.time()
514
  ingest_new, _log = stage_ingest(since, until, args.ingest_timeout_min * 60)
 
20
  2. hf_daily the last two weeks of Hugging Face Daily Papers lists, with
21
  each paper's upvotes as of today, into hf_daily_papers and
22
  hf_upvote_history (reported, never fails the run)
23
+ 3. hn Hacker News comments and stories linking arXiv papers since
24
+ the last run, with their threads' points, into hn_mentions,
25
+ hn_comments and hn_threads (scripts/hn_harvest.py; reported,
26
+ never fails the run)
27
+ 4. ingest scripts/ingest_arxiv.py over [today - lookback, today + 1);
28
  re-run once if its coverage check reports a gap (exit 3)
29
+ 5. citations Semantic Scholar counts for papers from the last 3 months;
30
  only changed rows are written
31
+ 6. verify new Qdrant points == new Turso rows == papers the ingest
32
  reported; sampled new vectors are 1024-dim unit vectors and
33
  their Turso rows are complete
34
+ 7. licences how many new papers have a `paper_licences` row, and how many
35
  of those may show figures (reported, never fails the run)
36
+ 8. summary printed as JSON, and to $GITHUB_STEP_SUMMARY when set
37
 
38
  Re-running is always safe: the ingest skips papers already stored and point
39
  ids are derived from the arXiv id, so overlapping runs cannot collide.
 
43
  python scripts/daily_refresh.py # the daily run
44
  python scripts/daily_refresh.py --dry-run # stages 1 and 6 only
45
  python scripts/daily_refresh.py --hf-only --hf-days 182 # backfill the history
46
+ python scripts/daily_refresh.py --hn-only --hn-since 2007-01-01 --hn-workers 6
47
+ # every HN mention since 2007
48
  """
49
  from __future__ import annotations
50
 
 
67
  HERE = Path(__file__).resolve().parent
68
  sys.path.insert(0, str(HERE.parent))
69
  from app import hf_papers_svc, licences # noqa: E402 (standard library and httpx only)
70
+ sys.path.append(str(HERE)) # hn_harvest sits beside this file
71
+ import hn_harvest # noqa: E402
72
 
73
  REQUIRED_ENV = ("QDRANT_RECENT_URL", "QDRANT_RECENT_API_KEY", "TURSO_URL", "TURSO_DB_TOKEN")
74
  COLLECTION = os.getenv("QDRANT_RECENT_COLLECTION", "arxiv_recent")
 
427
  return out
428
 
429
 
430
+ def stage_hn(st: Stores, since: str = "", workers: int = 1) -> dict:
431
+ """Hacker News mentions of arXiv papers since the last run (or `since`,
432
+ YYYY-MM-DD, for a backfill). Never fails the run: the watermark only moves
433
+ when every window came back, so the next run fetches a missed one again."""
434
+ since_ts = (int(dt.datetime.fromisoformat(since).replace(tzinfo=dt.timezone.utc).timestamp())
435
+ if since else None)
436
+ return hn_harvest.harvest(st, int(time.time()), since_ts=since_ts, workers=workers)
437
+
438
+
439
  def licence_coverage(codes: list[str | None]) -> dict:
440
  """One code per new paper; None or "" when it has no licence row."""
441
  known = [c for c in codes if c]
 
499
  help="Daily Papers lists to record, today included")
500
  ap.add_argument("--skip-hf", action="store_true")
501
  ap.add_argument("--hf-only", action="store_true", help="record the lists, then stop")
502
+ ap.add_argument("--skip-hn", action="store_true")
503
+ ap.add_argument("--hn-only", action="store_true", help="record Hacker News mentions, then stop")
504
+ ap.add_argument("--hn-since", default="", help="YYYY-MM-DD: fetch from this day, not the watermark")
505
+ ap.add_argument("--hn-workers", type=int, default=1, help="parallel searches (a backfill can use 6)")
506
  args = ap.parse_args()
507
 
508
  summary: dict = {"started": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
 
524
  return _finish(summary, 0)
525
 
526
  # Before the ingest, so a failed ingest cannot cost a day of history.
527
+ if not args.skip_hf and not args.hn_only:
528
  t0 = time.time()
529
  summary["hf_daily"] = stage_hf_daily(st, today, args.hf_days)
530
  summary["hf_daily"]["minutes"] = round((time.time() - t0) / 60, 1)
531
  if args.hf_only:
532
  return _finish(summary, 0)
533
+ if not args.skip_hn:
534
+ t0 = time.time()
535
+ summary["hn"] = stage_hn(st, args.hn_since, args.hn_workers)
536
+ summary["hn"]["minutes"] = round((time.time() - t0) / 60, 1)
537
+ if args.hn_only:
538
+ return _finish(summary, 0)
539
 
540
  t0 = time.time()
541
  ingest_new, _log = stage_ingest(since, until, args.ingest_timeout_min * 60)
scripts/hn_harvest.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hacker News mentions of arXiv papers, recorded for the "On Hacker News" block
3
+ on paper pages and the Lasting list (doc 06 changelog, 2026-11-03).
4
+
5
+ Where they come from
6
+ --------------------
7
+ The HN Search API by Algolia (https://hn.algolia.com/api) indexes every story
8
+ and comment since 2007 and needs no key. A search returns at most 1,000 hits,
9
+ so a time range is split in half until each part holds 1,000 or fewer. Every
10
+ comment whose text names arXiv, alphaXiv, ar5iv or Hugging Face Papers and every
11
+ story submitted with such a URL is fetched; the regexes below then decide which
12
+ papers it actually links. Measured on 3 Nov 2026 over 2007 to that day: about
13
+ 160,000 hits, 49,436 links to 28,379 papers, in roughly 750 requests.
14
+
15
+ What is stored (Turso, all keyed so a re-run overwrites instead of adding)
16
+ --------------------------------------------------------------------------
17
+ hn_mentions one row per (HN item, paper): who, when, which thread, and
18
+ whether the item is the story the paper was submitted as
19
+ hn_comments the plain text of each comment that links a paper, cut to
20
+ TEXT_MAX characters, for labelling how a paper is used later
21
+ hn_threads each thread a mention sits in: title, points, comment count
22
+ hn_state fetched_to (the end of the last complete fetch, unix seconds)
23
+ and loaded_at (when it finished), which the app polls
24
+
25
+ Each run fetches from fetched_to minus OVERLAP_S, so stories still collecting
26
+ points and comments edited after posting are read again for three days. The
27
+ watermark moves only when every window came back, so a failed window is
28
+ fetched again next time. Nothing here ever fails the daily run.
29
+
30
+ Standard library and httpx only, like the rest of the daily job.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import datetime as dt
35
+ import html
36
+ import re
37
+ import time
38
+ from concurrent.futures import ThreadPoolExecutor
39
+
40
+ import httpx
41
+
42
+ SEARCH_BY_DATE = "https://hn.algolia.com/api/v1/search_by_date"
43
+ SEARCH = "https://hn.algolia.com/api/v1/search"
44
+ FIRST_TS = 1167609600 # 2007-01-01, before HN's first item
45
+ OVERLAP_S = 3 * 86400
46
+ MAX_HITS = 1000 # Algolia's ceiling per search
47
+ PROBE_FIRST_S = 30 * 86400 # longer windows are counted before being fetched
48
+ LOOKUP_BATCH = 100 # threads looked up per request
49
+ WRITE_BATCH = 200 # rows per INSERT
50
+ TEXT_MAX = 1200
51
+ ATTRS = ("objectID,author,created_at_i,story_id,comment_text,story_title,story_url,"
52
+ "title,url,points,num_comments")
53
+
54
+ # (kind, search parameters). Comments are matched on their text, stories on
55
+ # their URL only, so a story merely titled "arXiv ..." is not a submission.
56
+ QUERIES: tuple[tuple[str, dict], ...] = (
57
+ ("comment", {"query": "arxiv", "tags": "comment"}),
58
+ ("comment", {"query": "alphaxiv", "tags": "comment"}),
59
+ ("comment", {"query": "ar5iv", "tags": "comment"}),
60
+ ("comment", {"query": "huggingface.co/papers", "tags": "comment"}),
61
+ ("story", {"query": "arxiv", "tags": "story", "restrictSearchableAttributes": "url"}),
62
+ ("story", {"query": "alphaxiv", "tags": "story", "restrictSearchableAttributes": "url"}),
63
+ ("story", {"query": "ar5iv", "tags": "story", "restrictSearchableAttributes": "url"}),
64
+ ("story", {"query": "huggingface.co/papers", "tags": "story", "restrictSearchableAttributes": "url"}),
65
+ )
66
+
67
+
68
+ # ── Which papers an item links (pure) ────────────────────────────────────────
69
+
70
+ _HOSTS = (r"(?:www\.)?(?:arxiv\.org|export\.arxiv\.org|alphaxiv\.org|ar5iv\.org|ar5iv\.labs\.arxiv\.org"
71
+ r"|huggingface\.co/papers|arxiv-sanity-lite\.com|arxiv-sanity\.com|semanticscholar\.org/arxiv)")
72
+ _NEW = re.compile(_HOSTS + r"/(?:[a-z]+/)*?(\d{4}\.\d{4,5})(?:v\d+)?", re.I)
73
+ _OLD = re.compile(r"(?:arxiv\.org|ar5iv\.org|ar5iv\.labs\.arxiv\.org)/(?:abs|pdf|html)/"
74
+ r"([a-z][a-z\-]*(?:\.[A-Z]{2})?/\d{7})", re.I)
75
+ _CITE = re.compile(r"\barxiv:\s?(\d{4}\.\d{4,5})(?:v\d+)?", re.I)
76
+ _TAGS = re.compile(r"<[^>]+>")
77
+
78
+
79
+ def _valid_new(aid: str, last_year: int) -> bool:
80
+ """yymm.nnnn ids ran from April 2007; five digits after the dot from 2015."""
81
+ yy, mm = int(aid[:2]), int(aid[2:4])
82
+ if not (1 <= mm <= 12 and 7 <= yy <= last_year % 100):
83
+ return False
84
+ return len(aid.split(".")[1]) == (4 if yy < 15 else 5)
85
+
86
+
87
+ def arxiv_ids(text: str | None, last_year: int) -> list[str]:
88
+ """The arXiv ids `text` links or cites, in order, each once, without a
89
+ version suffix. Old-style ids take their canonical form, archive and
90
+ number: "math.GT/0309136" is stored as "math/0309136", as the corpus has it."""
91
+ if not text:
92
+ return []
93
+ t = html.unescape(text)
94
+ found = [m for m in _NEW.findall(t) if _valid_new(m, last_year)]
95
+ found += [m for m in _CITE.findall(t) if _valid_new(m, last_year)]
96
+ for m in _OLD.findall(t):
97
+ archive, number = m.split("/")
98
+ found.append(f"{archive.split('.')[0].lower()}/{number}")
99
+ return list(dict.fromkeys(found))
100
+
101
+
102
+ def plain(comment_html: str | None) -> str:
103
+ """A comment's HTML as text: paragraphs on their own lines, entities decoded."""
104
+ t = (comment_html or "").replace("<p>", "\n\n")
105
+ t = html.unescape(_TAGS.sub("", t))
106
+ t = re.sub(r"[ \t]+", " ", t)
107
+ return re.sub(r"\n{3,}", "\n\n", t).strip()
108
+
109
+
110
+ def _int(v) -> int | None:
111
+ return v if type(v) is int and v >= 0 else None
112
+
113
+
114
+ def rows_from_hit(kind: str, hit: dict, checked_on: str, last_year: int) -> dict:
115
+ """What one search hit contributes: mention rows, a comment row, and the
116
+ thread as far as the hit itself describes it.
117
+
118
+ A story's paper is in its URL (or, rarely, its title); a comment's papers
119
+ are in its text. Items without an id or a time are dropped."""
120
+ item, ts = str(hit.get("objectID") or ""), _int(hit.get("created_at_i"))
121
+ if not item.isdigit() or ts is None:
122
+ return {"mentions": [], "comment": None, "thread": None, "fallback": None}
123
+ author = hit.get("author") or ""
124
+ if kind == "story":
125
+ ids = arxiv_ids(f"{hit.get('url') or ''} {hit.get('title') or ''}", last_year)
126
+ story = item
127
+ thread = (story, " ".join((hit.get("title") or "").split())[:300], (hit.get("url") or "")[:500],
128
+ _int(hit.get("points")), _int(hit.get("num_comments")), ts, checked_on)
129
+ comment = None
130
+ else:
131
+ ids = arxiv_ids(hit.get("comment_text"), last_year)
132
+ story = str(hit.get("story_id") or "")
133
+ thread = None
134
+ comment = (item, story, plain(hit.get("comment_text"))[:TEXT_MAX], len(ids), checked_on) if ids else None
135
+ if not story.isdigit():
136
+ return {"mentions": [], "comment": None, "thread": None, "fallback": None}
137
+ mentions = [(item, aid, kind, author, ts, story, checked_on) for aid in ids]
138
+ # Comments name their thread; the lookup fills in its points, and this is
139
+ # kept only if the lookup cannot find it (a deleted story, a poll).
140
+ fallback = None
141
+ if kind == "comment" and ids:
142
+ fallback = (story, " ".join((hit.get("story_title") or "").split())[:300],
143
+ (hit.get("story_url") or "")[:500], None, None, None, checked_on)
144
+ return {"mentions": mentions, "comment": comment, "thread": thread if ids else None,
145
+ "fallback": fallback}
146
+
147
+
148
+ # ── Fetching ─────────────────────────────────────────────────────────────────
149
+
150
+ def _get(client: httpx.Client, url: str, params: dict, attempts: int = 5) -> dict:
151
+ for attempt in range(attempts):
152
+ try:
153
+ r = client.get(url, params=params)
154
+ if r.status_code == 429 or r.status_code >= 500:
155
+ raise httpx.HTTPStatusError(f"HTTP {r.status_code}", request=r.request, response=r)
156
+ r.raise_for_status()
157
+ return r.json()
158
+ except (httpx.HTTPError, ValueError):
159
+ if attempt == attempts - 1:
160
+ raise
161
+ time.sleep(min(60, 3 * 2 ** attempt))
162
+ raise AssertionError("unreachable")
163
+
164
+
165
+ def fetch_window(client: httpx.Client, base: dict, lo: int, hi: int, out: list, stats: dict) -> None:
166
+ """Every hit of `base` created in [lo, hi) into `out`, splitting the range
167
+ while it holds more than MAX_HITS. Long ranges are counted first
168
+ (hitsPerPage=0 costs almost nothing), so the backfill never downloads a
169
+ thousand hits only to throw them away."""
170
+ nf = f"created_at_i>={lo},created_at_i<{hi}"
171
+ if hi - lo > PROBE_FIRST_S:
172
+ n = _get(client, SEARCH_BY_DATE, {**base, "numericFilters": nf, "hitsPerPage": 0})["nbHits"]
173
+ stats["requests"] += 1
174
+ if n == 0:
175
+ return
176
+ if n > MAX_HITS:
177
+ mid = (lo + hi) // 2
178
+ fetch_window(client, base, lo, mid, out, stats)
179
+ fetch_window(client, base, mid, hi, out, stats)
180
+ return
181
+ d = _get(client, SEARCH_BY_DATE, {**base, "numericFilters": nf, "hitsPerPage": MAX_HITS,
182
+ "attributesToRetrieve": ATTRS, "attributesToHighlight": ""})
183
+ stats["requests"] += 1
184
+ hits = d.get("hits") or []
185
+ if d.get("nbHits", 0) > len(hits):
186
+ if hi - lo > 60:
187
+ mid = (lo + hi) // 2
188
+ fetch_window(client, base, lo, mid, out, stats)
189
+ fetch_window(client, base, mid, hi, out, stats)
190
+ return
191
+ stats["lost"] += d["nbHits"] - len(hits)
192
+ out.extend(hits)
193
+
194
+
195
+ def _year_ranges(lo: int, hi: int) -> list[tuple[int, int]]:
196
+ """[lo, hi) cut at each 1 January (UTC), so a backfill runs years in parallel."""
197
+ cuts, y = [lo], dt.datetime.fromtimestamp(lo, dt.timezone.utc).year + 1
198
+ while True:
199
+ edge = int(dt.datetime(y, 1, 1, tzinfo=dt.timezone.utc).timestamp())
200
+ if edge >= hi:
201
+ break
202
+ cuts.append(edge)
203
+ y += 1
204
+ cuts.append(hi)
205
+ return list(zip(cuts, cuts[1:]))
206
+
207
+
208
+ def fetch_items(client: httpx.Client, lo: int, hi: int, workers: int = 1) -> tuple[list[tuple[str, dict]], dict]:
209
+ """(kind, hit) for every query over [lo, hi), and request counts.
210
+
211
+ Raises if any window fails after its retries: the caller must not move
212
+ the watermark past a hole."""
213
+ stats = {"requests": 0, "lost": 0}
214
+ jobs = [(kind, base, a, b) for kind, base in QUERIES for a, b in _year_ranges(lo, hi)]
215
+
216
+ def run(job):
217
+ kind, base, a, b = job
218
+ hits: list = []
219
+ part = {"requests": 0, "lost": 0}
220
+ fetch_window(client, base, a, b, hits, part)
221
+ return kind, hits, part
222
+
223
+ out: list[tuple[str, dict]] = []
224
+ with ThreadPoolExecutor(max(1, workers)) as pool:
225
+ for kind, hits, part in pool.map(run, jobs):
226
+ out += [(kind, h) for h in hits]
227
+ stats["requests"] += part["requests"]
228
+ stats["lost"] += part["lost"]
229
+ return out, stats
230
+
231
+
232
+ def lookup_threads(client: httpx.Client, story_ids: list[str], checked_on: str,
233
+ stats: dict | None = None) -> dict[str, tuple]:
234
+ """Thread rows for stories by id, LOOKUP_BATCH a request. Ids Algolia does
235
+ not return as stories (deleted, polls, jobs) are left out."""
236
+ out: dict[str, tuple] = {}
237
+ for i in range(0, len(story_ids), LOOKUP_BATCH):
238
+ chunk = story_ids[i:i + LOOKUP_BATCH]
239
+ d = _get(client, SEARCH, {"tags": "story,(" + ",".join(f"story_{s}" for s in chunk) + ")",
240
+ "hitsPerPage": len(chunk), "attributesToRetrieve": ATTRS,
241
+ "attributesToHighlight": ""})
242
+ if stats is not None:
243
+ stats["requests"] += 1
244
+ for h in d.get("hits") or []:
245
+ sid, ts = str(h.get("objectID") or ""), _int(h.get("created_at_i"))
246
+ if sid in chunk and ts is not None:
247
+ out[sid] = (sid, " ".join((h.get("title") or "").split())[:300], (h.get("url") or "")[:500],
248
+ _int(h.get("points")), _int(h.get("num_comments")), ts, checked_on)
249
+ return out
250
+
251
+
252
+ # ── Storing ──────────────────────────────────────────────────────────────────
253
+
254
+ MENTIONS_DDL = ("CREATE TABLE IF NOT EXISTS hn_mentions ("
255
+ "item_id TEXT NOT NULL, arxiv_id TEXT NOT NULL, kind TEXT NOT NULL, "
256
+ "author TEXT NOT NULL, created_at INTEGER NOT NULL, story_id TEXT NOT NULL, "
257
+ "checked_on TEXT NOT NULL, PRIMARY KEY (item_id, arxiv_id))")
258
+ MENTIONS_INDEX = "CREATE INDEX IF NOT EXISTS hn_mentions_paper ON hn_mentions (arxiv_id)"
259
+ COMMENTS_DDL = ("CREATE TABLE IF NOT EXISTS hn_comments ("
260
+ "item_id TEXT PRIMARY KEY, story_id TEXT NOT NULL, text TEXT NOT NULL, "
261
+ "papers INTEGER NOT NULL, checked_on TEXT NOT NULL)")
262
+ THREADS_DDL = ("CREATE TABLE IF NOT EXISTS hn_threads ("
263
+ "story_id TEXT PRIMARY KEY, title TEXT NOT NULL, url TEXT NOT NULL, "
264
+ "points INTEGER, comments INTEGER, created_at INTEGER, checked_on TEXT NOT NULL)")
265
+ STATE_DDL = "CREATE TABLE IF NOT EXISTS hn_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
266
+ DDL = (MENTIONS_DDL, MENTIONS_INDEX, COMMENTS_DDL, THREADS_DDL, STATE_DDL)
267
+
268
+
269
+ def _arg(v) -> dict:
270
+ if v is None:
271
+ return {"type": "null"}
272
+ return {"type": "integer" if isinstance(v, int) else "text", "value": str(v)}
273
+
274
+
275
+ def upsert(head: str, rows: list[tuple], conflict: str) -> dict:
276
+ """One multi-row INSERT; NULLs pass as NULL, not as the text 'None'."""
277
+ marks = "(" + ", ".join("?" * len(rows[0])) + ")"
278
+ return {"sql": f"{head} VALUES {', '.join([marks] * len(rows))} {conflict}",
279
+ "args": [_arg(v) for row in rows for v in row]}
280
+
281
+
282
+ def statements(mentions: list[tuple], comments: list[tuple], threads: list[tuple]) -> list[list[dict]]:
283
+ """Transactions of at most WRITE_BATCH rows per table. A thread that was
284
+ looked up keeps its points if a later row only knows its title (the
285
+ fallback from a comment), so a lookup that misses never wipes a count."""
286
+ txs: list[list[dict]] = []
287
+ for i in range(0, len(mentions), WRITE_BATCH):
288
+ txs.append([upsert("INSERT INTO hn_mentions (item_id, arxiv_id, kind, author, created_at, story_id, "
289
+ "checked_on)", mentions[i:i + WRITE_BATCH],
290
+ "ON CONFLICT (item_id, arxiv_id) DO UPDATE SET author = excluded.author, "
291
+ "checked_on = excluded.checked_on")])
292
+ for i in range(0, len(comments), WRITE_BATCH):
293
+ txs.append([upsert("INSERT INTO hn_comments (item_id, story_id, text, papers, checked_on)",
294
+ comments[i:i + WRITE_BATCH],
295
+ "ON CONFLICT (item_id) DO UPDATE SET text = excluded.text, "
296
+ "papers = excluded.papers, checked_on = excluded.checked_on")])
297
+ for i in range(0, len(threads), WRITE_BATCH):
298
+ txs.append([upsert("INSERT INTO hn_threads (story_id, title, url, points, comments, created_at, "
299
+ "checked_on)", threads[i:i + WRITE_BATCH],
300
+ "ON CONFLICT (story_id) DO UPDATE SET "
301
+ "title = CASE WHEN excluded.title != '' THEN excluded.title ELSE hn_threads.title END, "
302
+ "url = CASE WHEN excluded.url != '' THEN excluded.url ELSE hn_threads.url END, "
303
+ "points = COALESCE(excluded.points, hn_threads.points), "
304
+ "comments = COALESCE(excluded.comments, hn_threads.comments), "
305
+ "created_at = COALESCE(excluded.created_at, hn_threads.created_at), "
306
+ "checked_on = excluded.checked_on")])
307
+ return txs
308
+
309
+
310
+ def collect(items: list[tuple[str, dict]], checked_on: str, last_year: int) -> dict:
311
+ """Mention, comment and thread rows from fetched hits, each item once."""
312
+ mentions: dict[tuple, tuple] = {}
313
+ comments: dict[str, tuple] = {}
314
+ threads: dict[str, tuple] = {}
315
+ fallbacks: dict[str, tuple] = {}
316
+ for kind, hit in items:
317
+ r = rows_from_hit(kind, hit, checked_on, last_year)
318
+ for m in r["mentions"]:
319
+ mentions.setdefault((m[0], m[1]), m)
320
+ if r["comment"]:
321
+ comments[r["comment"][0]] = r["comment"]
322
+ if r["thread"]:
323
+ threads[r["thread"][0]] = r["thread"]
324
+ if r.get("fallback"):
325
+ fallbacks.setdefault(r["fallback"][0], r["fallback"])
326
+ return {"mentions": list(mentions.values()), "comments": list(comments.values()),
327
+ "threads": threads, "fallbacks": fallbacks}
328
+
329
+
330
+ def harvest(st, now_ts: int, since_ts: int | None = None, workers: int = 1,
331
+ client: httpx.Client | None = None) -> dict:
332
+ """Fetch and store everything from the watermark (or `since_ts`) to now.
333
+
334
+ `st` is daily_refresh.Stores (its t and t_many). Never raises: the result
335
+ says what happened, with an `error` when the run stopped early."""
336
+ out: dict = {"mentions": 0, "comments": 0, "threads": 0, "papers": 0, "requests": 0, "lost": 0}
337
+ own = client is None
338
+ client = client or httpx.Client(timeout=60, headers={"User-Agent": "ResearchIT daily refresh"})
339
+ try:
340
+ for sql in DDL:
341
+ st.t(sql)
342
+ if since_ts is None:
343
+ got = st.t("SELECT value FROM hn_state WHERE key = 'fetched_to'")
344
+ since_ts = int(got[0][0]) - OVERLAP_S if got else now_ts - OVERLAP_S
345
+ since_ts = max(FIRST_TS, since_ts)
346
+ out["from"] = dt.datetime.fromtimestamp(since_ts, dt.timezone.utc).isoformat(timespec="seconds")
347
+ checked_on = dt.datetime.fromtimestamp(now_ts, dt.timezone.utc).date().isoformat()
348
+ last_year = dt.datetime.fromtimestamp(now_ts, dt.timezone.utc).year
349
+ items, stats = fetch_items(client, since_ts, now_ts, workers)
350
+ out["requests"], out["lost"] = stats["requests"], stats["lost"]
351
+ rows = collect(items, checked_on, last_year)
352
+ need = sorted(set(rows["fallbacks"]) - set(rows["threads"]))
353
+ looked = lookup_threads(client, need, checked_on, out)
354
+ threads = {**rows["fallbacks"], **looked, **rows["threads"]}
355
+ for tx in statements(rows["mentions"], rows["comments"], list(threads.values())):
356
+ st.t_many(tx)
357
+ out.update(mentions=len(rows["mentions"]), comments=len(rows["comments"]), threads=len(threads),
358
+ papers=len({m[1] for m in rows["mentions"]}),
359
+ threads_not_found=len(set(need) - set(looked)))
360
+ loaded = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
361
+ st.t_many([upsert("INSERT INTO hn_state (key, value)", [("fetched_to", str(now_ts)), ("loaded_at", loaded)],
362
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value")])
363
+ out["fetched_to"] = now_ts
364
+ except (httpx.HTTPError, RuntimeError, ValueError, KeyError) as e:
365
+ out["error"] = f"{type(e).__name__}: {e}"[:300]
366
+ finally:
367
+ if own:
368
+ client.close()
369
+ return out
tests/test_hn_harvest.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """scripts/hn_harvest.py: which papers an HN item links, fetching past
2
+ Algolia's 1,000-hit ceiling, and what the daily job stores."""
3
+ import importlib.util
4
+ import re
5
+ import sqlite3
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+ import pytest
11
+
12
+ _SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
13
+ sys.path.append(str(_SCRIPTS))
14
+ _spec = importlib.util.spec_from_file_location("hn_harvest", _SCRIPTS / "hn_harvest.py")
15
+ hn = importlib.util.module_from_spec(_spec)
16
+ _spec.loader.exec_module(hn)
17
+
18
+ YEAR = 2026
19
+
20
+
21
+ @pytest.fixture(autouse=True)
22
+ def _no_sleep(monkeypatch):
23
+ monkeypatch.setattr(hn.time, "sleep", lambda s: None)
24
+
25
+
26
+ # ── Which papers an item links ───────────────────────────────────────────────
27
+
28
+ def test_ids_from_links_of_every_kind_without_versions():
29
+ text = ("Attention: https://arxiv.org/abs/1706.03762v5, the PDF arxiv.org/pdf/2401.00001.pdf, "
30
+ "https://www.alphaxiv.org/abs/2502.12345 and https://huggingface.co/papers/2510.01234 "
31
+ "and ar5iv.labs.arxiv.org/html/1512.03385")
32
+ assert hn.arxiv_ids(text, YEAR) == ["1706.03762", "2401.00001", "2502.12345", "2510.01234", "1512.03385"]
33
+
34
+
35
+ def test_ids_from_escaped_html_and_citations():
36
+ html_text = ('<a href="https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;2310.06825" rel="nofollow">'
37
+ 'https:&#x2F;&#x2F;arxiv.org&#x2F;abs&#x2F;2310.06825</a> and arXiv:2005.14165')
38
+ assert hn.arxiv_ids(html_text, YEAR) == ["2310.06825", "2005.14165"]
39
+
40
+
41
+ def test_old_style_ids_take_the_corpus_form():
42
+ text = "arxiv.org/abs/hep-th/9711200 and https://arxiv.org/abs/math.GT/0309136 and arxiv.org/pdf/cs/0101001"
43
+ assert hn.arxiv_ids(text, YEAR) == ["hep-th/9711200", "math/0309136", "cs/0101001"]
44
+
45
+
46
+ def test_impossible_ids_and_bare_numbers_are_ignored():
47
+ assert hn.arxiv_ids("arxiv.org/abs/2413.00001", YEAR) == [] # month 13
48
+ assert hn.arxiv_ids("arxiv.org/abs/2701.00001", YEAR) == [] # next year
49
+ assert hn.arxiv_ids("arxiv.org/abs/1501.0001", YEAR) == [] # 2015 ids have five digits
50
+ assert hn.arxiv_ids("arxiv.org/abs/0612.0001", YEAR) == [] # before April 2007's scheme
51
+ assert hn.arxiv_ids("the number 1706.03762 alone", YEAR) == []
52
+ assert hn.arxiv_ids("arxiv.org/abs/1706.03762 arxiv.org/pdf/1706.03762v2", YEAR) == ["1706.03762"]
53
+ assert hn.arxiv_ids(None, YEAR) == []
54
+
55
+
56
+ def test_plain_keeps_paragraphs_and_decodes_entities():
57
+ assert hn.plain("First &amp; foremost<p>See <a href=\"x\">this</a> &#x2F; <i>that</i>") == \
58
+ "First & foremost\n\nSee this / that"
59
+
60
+
61
+ def _story(item="100", url="https://arxiv.org/abs/2401.00001", ts=1_790_000_000, points=120):
62
+ return {"objectID": item, "author": "alice", "created_at_i": ts, "title": "A paper", "url": url,
63
+ "points": points, "num_comments": 40}
64
+
65
+
66
+ def _comment(item="200", text="see arxiv.org/abs/2401.00001 and arxiv.org/abs/1706.03762", story=100,
67
+ ts=1_790_000_100, author="bob"):
68
+ return {"objectID": item, "author": author, "created_at_i": ts, "story_id": story,
69
+ "comment_text": text, "story_title": "Some thread", "story_url": "https://example.com"}
70
+
71
+
72
+ def test_a_story_is_a_submission_with_its_thread():
73
+ r = hn.rows_from_hit("story", _story(), "2026-11-03", YEAR)
74
+ assert r["mentions"] == [("100", "2401.00001", "story", "alice", 1_790_000_000, "100", "2026-11-03")]
75
+ assert r["thread"] == ("100", "A paper", "https://arxiv.org/abs/2401.00001", 120, 40, 1_790_000_000,
76
+ "2026-11-03")
77
+ assert r["comment"] is None
78
+ assert hn.rows_from_hit("story", _story(url="https://example.com/arxiv-is-great"), "d", YEAR)["mentions"] == []
79
+
80
+
81
+ def test_a_comment_names_every_paper_and_its_thread():
82
+ r = hn.rows_from_hit("comment", _comment(), "2026-11-03", YEAR)
83
+ assert [m[1] for m in r["mentions"]] == ["2401.00001", "1706.03762"]
84
+ assert all(m[2] == "comment" and m[5] == "100" for m in r["mentions"])
85
+ assert r["comment"][0] == "200" and r["comment"][3] == 2
86
+ assert r["fallback"] == ("100", "Some thread", "https://example.com", None, None, None, "2026-11-03")
87
+ assert hn.rows_from_hit("comment", _comment(text="I love arxiv"), "d", YEAR)["comment"] is None
88
+ assert hn.rows_from_hit("comment", {**_comment(), "story_id": None}, "d", YEAR)["mentions"] == []
89
+
90
+
91
+ # ── Fetching ─────────────────────────────────────────────────────────────────
92
+
93
+ def _index_handler(items, calls):
94
+ """A fake search_by_date over `items` (dicts with created_at_i), honouring
95
+ the numeric filter and the 1,000-hit ceiling, like Algolia."""
96
+ def handler(request):
97
+ calls.append(dict(request.url.params))
98
+ lo, hi = map(int, re.findall(r"created_at_i[<>]=?(\d+)", request.url.params["numericFilters"]))
99
+ hits = [h for h in items if lo <= h["created_at_i"] < hi]
100
+ per = int(request.url.params["hitsPerPage"])
101
+ return httpx.Response(200, json={"nbHits": len(hits), "hits": hits[:min(per, 1000)]})
102
+ return handler
103
+
104
+
105
+ def test_a_window_past_the_ceiling_is_split_until_every_hit_is_fetched():
106
+ items = [{"objectID": str(i), "created_at_i": 1_000_000 + i * 300} for i in range(2500)]
107
+ calls: list = []
108
+ client = httpx.Client(transport=httpx.MockTransport(_index_handler(items, calls)))
109
+ out: list = []
110
+ stats = {"requests": 0, "lost": 0}
111
+ hn.fetch_window(client, {"query": "arxiv"}, 1_000_000, 1_000_000 + 2500 * 300, out, stats)
112
+ assert sorted(int(h["objectID"]) for h in out) == list(range(2500))
113
+ assert stats["lost"] == 0 and stats["requests"] == len(calls)
114
+
115
+
116
+ def test_long_windows_are_counted_before_being_downloaded():
117
+ items = [{"objectID": "1", "created_at_i": 5_000_000}]
118
+ calls: list = []
119
+ client = httpx.Client(transport=httpx.MockTransport(_index_handler(items, calls)))
120
+ out: list = []
121
+ hn.fetch_window(client, {"query": "arxiv"}, 0, 100 * 86400, out, {"requests": 0, "lost": 0})
122
+ assert [c["hitsPerPage"] for c in calls] == ["0", "1000"]
123
+ calls.clear()
124
+ hn.fetch_window(client, {"query": "arxiv"}, 60 * 86400, 100 * 86400, [], {"requests": 0, "lost": 0})
125
+ assert [c["hitsPerPage"] for c in calls] == ["0"] # empty: nothing downloaded
126
+
127
+
128
+ def test_year_ranges_cut_at_new_year():
129
+ lo = 1_703_980_800 # 2023-12-31
130
+ hi = 1_735_776_000 # 2025-01-02
131
+ got = hn._year_ranges(lo, hi)
132
+ assert got[0][0] == lo and got[-1][1] == hi and len(got) == 3
133
+ assert all(a < b for a, b in got) and all(got[i][1] == got[i + 1][0] for i in range(len(got) - 1))
134
+
135
+
136
+ def test_thread_lookup_asks_by_id_and_leaves_out_unknown_ids():
137
+ seen = []
138
+
139
+ def handler(request):
140
+ tags = request.url.params["tags"]
141
+ seen.append(tags)
142
+ ids = re.findall(r"story_(\d+)", tags)
143
+ hits = [{"objectID": i, "title": f"T{i}", "url": "", "points": 7, "num_comments": 3,
144
+ "created_at_i": 1_700_000_000} for i in ids if i != "999"]
145
+ return httpx.Response(200, json={"hits": hits})
146
+
147
+ client = httpx.Client(transport=httpx.MockTransport(handler))
148
+ got = hn.lookup_threads(client, ["1", "2", "999"], "2026-11-03")
149
+ assert set(got) == {"1", "2"} and got["1"][3] == 7
150
+ assert seen == ["story,(story_1,story_2,story_999)"]
151
+
152
+
153
+ # ── Storing ──────────────────────────────────────────────────────────────────
154
+
155
+ def _run(conn, stmt):
156
+ def val(a):
157
+ if a["type"] == "null":
158
+ return None
159
+ return int(a["value"]) if a["type"] == "integer" else a["value"]
160
+ conn.execute(stmt["sql"], [val(a) for a in stmt.get("args", [])])
161
+
162
+
163
+ class FakeStores:
164
+ def __init__(self):
165
+ self.conn = sqlite3.connect(":memory:")
166
+
167
+ def t(self, sql, args=()):
168
+ return [list(r) for r in self.conn.execute(sql, args).fetchall()]
169
+
170
+ def t_many(self, stmts):
171
+ for s in stmts:
172
+ _run(self.conn, s)
173
+
174
+
175
+ def test_a_title_only_row_never_wipes_a_looked_up_thread():
176
+ st = FakeStores()
177
+ for sql in hn.DDL:
178
+ st.t(sql)
179
+ looked = ("100", "A paper", "https://arxiv.org/abs/2401.00001", 120, 40, 1_790_000_000, "2026-11-02")
180
+ for tx in hn.statements([], [], [looked]):
181
+ st.t_many(tx)
182
+ fallback = ("100", "", "", None, None, None, "2026-11-03")
183
+ for tx in hn.statements([], [], [fallback]):
184
+ st.t_many(tx)
185
+ assert st.t("SELECT title, url, points, comments, created_at, checked_on FROM hn_threads") == [
186
+ ["A paper", "https://arxiv.org/abs/2401.00001", 120, 40, 1_790_000_000, "2026-11-03"]]
187
+
188
+
189
+ def test_writes_are_batched():
190
+ mentions = [(str(i), "2401.00001", "comment", "a", 1, "9", "d") for i in range(hn.WRITE_BATCH + 1)]
191
+ txs = hn.statements(mentions, [], [])
192
+ assert len(txs) == 2 and txs[0][0]["sql"].count("(?, ?, ?, ?, ?, ?, ?)") == hn.WRITE_BATCH
193
+
194
+
195
+ def _api(items_by_kind, fail=False):
196
+ """search_by_date answering per kind (comment or story), plus the thread lookup."""
197
+ def handler(request):
198
+ if fail:
199
+ return httpx.Response(503)
200
+ p = request.url.params
201
+ if request.url.path.endswith("/search"):
202
+ ids = re.findall(r"story_(\d+)", p["tags"])
203
+ return httpx.Response(200, json={"hits": [
204
+ {"objectID": i, "title": "Thread " + i, "url": "", "points": 55, "num_comments": 9,
205
+ "created_at_i": 1_790_000_000} for i in ids]})
206
+ lo, hi = map(int, re.findall(r"created_at_i[<>]=?(\d+)", p["numericFilters"]))
207
+ kind = "story" if p["tags"] == "story" else "comment"
208
+ mine = items_by_kind.get((kind, p["query"]), [])
209
+ hits = [h for h in mine if lo <= h["created_at_i"] < hi]
210
+ return httpx.Response(200, json={"nbHits": len(hits), "hits": hits[:int(p["hitsPerPage"])]})
211
+ return handler
212
+
213
+
214
+ def test_harvest_stores_mentions_threads_and_the_watermark():
215
+ st = FakeStores()
216
+ now = 1_790_100_000
217
+ items = {("story", "arxiv"): [_story(ts=now - 5000)],
218
+ ("comment", "arxiv"): [_comment(ts=now - 4000), _comment(item="201", story=300, ts=now - 3000,
219
+ author="carol")]}
220
+ client = httpx.Client(transport=httpx.MockTransport(_api(items)))
221
+ got = hn.harvest(st, now, client=client)
222
+ assert "error" not in got
223
+ assert got["mentions"] == 5 and got["papers"] == 2 and got["comments"] == 2 and got["threads"] == 2
224
+ assert st.t("SELECT value FROM hn_state WHERE key = 'fetched_to'") == [[str(now)]]
225
+ # The story came with its points; thread 300 was looked up.
226
+ assert st.t("SELECT story_id, points FROM hn_threads ORDER BY story_id") == [["100", 120], ["300", 55]]
227
+ assert st.t("SELECT COUNT(DISTINCT author) FROM hn_mentions WHERE arxiv_id = '2401.00001'") == [[3]]
228
+
229
+ # The next run starts OVERLAP_S before the watermark and adds nothing twice.
230
+ later = now + 86400
231
+ client = httpx.Client(transport=httpx.MockTransport(_api(items)))
232
+ again = hn.harvest(st, later, client=client)
233
+ assert again["from"].startswith("2026") and again["mentions"] == 5
234
+ assert st.t("SELECT COUNT(*) FROM hn_mentions") == [[5]]
235
+
236
+
237
+ def test_a_failed_harvest_reports_and_keeps_the_watermark():
238
+ st = FakeStores()
239
+ for sql in hn.DDL:
240
+ st.t(sql)
241
+ st.t("INSERT INTO hn_state (key, value) VALUES ('fetched_to', '1790000000')")
242
+ client = httpx.Client(transport=httpx.MockTransport(_api({}, fail=True)))
243
+ got = hn.harvest(st, 1_790_100_000, client=client)
244
+ assert got["error"].startswith("HTTPStatusError")
245
+ assert st.t("SELECT value FROM hn_state WHERE key = 'fetched_to'") == [["1790000000"]]