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(hackernews): order top comments by HN kids, not Algolia id order (#1288)

yi111f7cbadcb1c46
diff --git a/changelog.d/1285.fixed.md b/changelog.d/1285.fixed.md
new file mode 100644
index 00000000..f6e13698
--- /dev/null
+++ b/changelog.d/1285.fixed.md
@@ -0,0 +1 @@
+Hacker News top comments now follow the thread's display order from the official HN item API instead of Algolia's oldest-first order, so quoted comments are the ones HN ranks highest. If that lookup fails, comments keep the previous order and the Hacker News source is not marked degraded.
diff --git a/skills/last30days/scripts/lib/hackernews.py b/skills/last30days/scripts/lib/hackernews.py
index a2f130de..76b3e32b 100644
--- a/skills/last30days/scripts/lib/hackernews.py
+++ b/skills/last30days/scripts/lib/hackernews.py
@@ -10,6 +10,7 @@ import math
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
+from http.client import HTTPException
from typing import Any, Dict, List, Optional
import re
@@ -24,6 +25,9 @@ _HN_PREFIXES = re.compile(r"^(Tell HN|Show HN|Ask HN|Launch HN)\s*:\s*", re.IGNO
ALGOLIA_SEARCH_URL = "https://hn.algolia.com/api/v1/search"
ALGOLIA_SEARCH_BY_DATE_URL = "https://hn.algolia.com/api/v1/search_by_date"
ALGOLIA_ITEM_URL = "https://hn.algolia.com/api/v1/items"
+# Official HN Firebase item API — `kids` is in the order the thread displays
+# top-level comments (Algolia's /items children do not carry useful points).
+FIREBASE_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item"
DEPTH_CONFIG = {
"quick": 15,
@@ -309,6 +313,68 @@ def _hn_item_url(item_id: Any) -> str:
return f"https://news.ycombinator.com/item?id={item_id}"
+# Ordering is optional, so a slow Firebase must not hold up the report.
+FIREBASE_KIDS_TIMEOUT = 5
+FIREBASE_KIDS_RETRIES = 2
+FIREBASE_KIDS_BUDGET = 8.0
+
+
+def _fetch_hn_kids(object_id: str) -> Optional[List[Any]]:
+ """Return HN's display order for a story's top-level comments, or None on failure.
+
+ Algolia's `/items/<id>` children list is effectively id-order with `points`
+ always null, so sorting by points is a no-op (#1285). The Firebase item
+ endpoint returns `kids` in the same order the HN thread UI shows.
+ """
+ url = f"{FIREBASE_ITEM_URL}/{object_id}.json"
+ # Comment order is a refinement over comments Algolia already returned, so a
+ # Firebase failure must not reach the pipeline's sink and mark HN degraded.
+ try:
+ with http.capture_failures():
+ data = http.request(
+ "GET",
+ url,
+ timeout=FIREBASE_KIDS_TIMEOUT,
+ retries=FIREBASE_KIDS_RETRIES,
+ deadline_monotonic=time.monotonic() + FIREBASE_KIDS_BUDGET,
+ )
+ # http.request wraps HTTP and socket errors, but a truncated or non-UTF-8
+ # body escapes as IncompleteRead or UnicodeDecodeError.
+ except (http.HTTPError, HTTPException, UnicodeDecodeError) as e:
+ _log(f"Failed to fetch HN kids for {object_id}: {e}")
+ return None
+ if not isinstance(data, dict):
+ return None
+ kids = data.get("kids")
+ if not isinstance(kids, list):
+ return None
+ return kids
+
+
+def _order_comments_by_kids(
+ comments: List[Dict[str, Any]],
+ kids: List[Any],
+) -> List[Dict[str, Any]]:
+ """Reorder Algolia children to match HN `kids` order; unknowns keep relative order."""
+ by_id: Dict[Any, Dict[str, Any]] = {}
+ for comment in comments:
+ cid = comment.get("id")
+ if cid is not None and cid not in by_id:
+ by_id[cid] = comment
+ ordered: List[Dict[str, Any]] = []
+ seen = set()
+ for kid in kids:
+ comment = by_id.get(kid)
+ if comment is not None:
+ ordered.append(comment)
+ seen.add(kid)
+ for comment in comments:
+ cid = comment.get("id")
+ if cid not in seen:
+ ordered.append(comment)
+ return ordered
+
+
def _fetch_item_comments(object_id: str, max_comments: int = 5) -> Dict[str, Any]:
"""Fetch top-level comments for a story from Algolia items endpoint.
@@ -329,12 +395,18 @@ def _fetch_item_comments(object_id: str, max_comments: int = 5) -> Dict[str, Any
children = data.get("children", [])
- # Sort by points (highest first), filter to actual comments
+ # Filter to actual comments. Prefer HN's Firebase `kids` order (#1285);
+ # Algolia children have null points, so a points sort is a no-op and leaves
+ # earliest-posted replies first. Fall back to points only when kids is unavailable.
real_comments = [
c for c in children
if c.get("text") and c.get("author")
]
- real_comments.sort(key=lambda c: c.get("points") or 0, reverse=True)
+ kids = _fetch_hn_kids(object_id)
+ if kids is not None:
+ real_comments = _order_comments_by_kids(real_comments, kids)
+ else:
+ real_comments.sort(key=lambda c: c.get("points") or 0, reverse=True)
comments = []
insights = []
diff --git a/tests/eval/fixtures/breaking-event/http.json b/tests/eval/fixtures/breaking-event/http.json
index e5b077ad..6381bf5e 100644
--- a/tests/eval/fixtures/breaking-event/http.json
+++ b/tests/eval/fixtures/breaking-event/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/breaking-event-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "breaking-event-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/breaking-event-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "breaking-event-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/breaking-event-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "breaking-event-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/comparison/http.json b/tests/eval/fixtures/comparison/http.json
index 12c45408..3911e944 100644
--- a/tests/eval/fixtures/comparison/http.json
+++ b/tests/eval/fixtures/comparison/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/comparison-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "comparison-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/comparison-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "comparison-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/comparison-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "comparison-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/emerging-event/http.json b/tests/eval/fixtures/emerging-event/http.json
index df49bbdb..88148485 100644
--- a/tests/eval/fixtures/emerging-event/http.json
+++ b/tests/eval/fixtures/emerging-event/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/emerging-event-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "emerging-event-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/emerging-event-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "emerging-event-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/emerging-event-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "emerging-event-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/niche/http.json b/tests/eval/fixtures/niche/http.json
index d96976ff..54046f7d 100644
--- a/tests/eval/fixtures/niche/http.json
+++ b/tests/eval/fixtures/niche/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/niche-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "niche-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/niche-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "niche-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/niche-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "niche-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/non-english-cjk/http.json b/tests/eval/fixtures/non-english-cjk/http.json
index 6435376c..68416c67 100644
--- a/tests/eval/fixtures/non-english-cjk/http.json
+++ b/tests/eval/fixtures/non-english-cjk/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/non-english-cjk-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "non-english-cjk-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -102,6 +121,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/non-english-cjk-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "non-english-cjk-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/person/http.json b/tests/eval/fixtures/person/http.json
index e0f4a52f..6485578e 100644
--- a/tests/eval/fixtures/person/http.json
+++ b/tests/eval/fixtures/person/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/person-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "person-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/person-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "person-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/person-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "person-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/fixtures/tech-product/http.json b/tests/eval/fixtures/tech-product/http.json
index 02845a96..f73988f9 100644
--- a/tests/eval/fixtures/tech-product/http.json
+++ b/tests/eval/fixtures/tech-product/http.json
@@ -91,6 +91,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/tech-product-hn-1.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_1",
+ "id": "tech-product-hn-1",
+ "kids": [
+ 42000013,
+ 42000011,
+ 42000012
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -103,6 +122,25 @@
}
}
},
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/tech-product-hn-2.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_2",
+ "id": "tech-product-hn-2",
+ "kids": [
+ 42000023,
+ 42000021,
+ 42000022
+ ],
+ "type": "story"
+ }
+ }
+ },
{
"request": {
"method": "GET",
@@ -114,6 +152,25 @@
"children": []
}
}
+ },
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://hacker-news.firebaseio.com/v0/item/tech-product-hn-3.json",
+ "raw": false
+ },
+ "response": {
+ "value": {
+ "by": "fixture_author_3",
+ "id": "tech-product-hn-3",
+ "kids": [
+ 42000033,
+ 42000031,
+ 42000032
+ ],
+ "type": "story"
+ }
+ }
}
]
}
diff --git a/tests/eval/test_eval_harness.py b/tests/eval/test_eval_harness.py
index f648b5d7..fc855af0 100644
--- a/tests/eval/test_eval_harness.py
+++ b/tests/eval/test_eval_harness.py
@@ -198,3 +198,46 @@ def test_star_enrichment_apply_map_offline():
)
assert enriched == 1
assert candidate.metadata["github_stars"]["mvanhorn/last30days-skill"] == 51436
+
+
+def test_hn_comment_replay_follows_firebase_kids_order(tmp_path):
+ source = next(f for f in harness.load_fixtures() if f.name == "breaking-event")
+ payload = json.loads((source.path / "http.json").read_text(encoding="utf-8"))
+ story_id = "breaking-event-hn-1"
+ algolia_children = [
+ {"id": 41000101, "author": "posted_first", "text": "<p>First reply.</p>", "points": None},
+ {"id": 41000102, "author": "posted_second", "text": "<p>Second reply.</p>", "points": None},
+ {"id": 41000103, "author": "posted_third", "text": "<p>Third reply.</p>", "points": None},
+ ]
+ kids = [41000103, 41000101, 41000102]
+ patched = {"algolia": False, "firebase": False}
+ for exchange in payload["exchanges"]:
+ url = exchange["request"]["url"]
+ if url == f"https://hn.algolia.com/api/v1/items/{story_id}":
+ exchange["response"]["value"]["children"] = algolia_children
+ patched["algolia"] = True
+ elif url == f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json":
+ exchange["response"]["value"]["kids"] = kids
+ patched["firebase"] = True
+ assert patched == {"algolia": True, "firebase": True}
+ fixture_path = tmp_path / source.name
+ fixture_path.mkdir()
+ (fixture_path / "http.json").write_text(json.dumps(payload), encoding="utf-8")
+ fixture = harness.EvalFixture(
+ name=source.name,
+ path=fixture_path,
+ manifest=deepcopy(source.manifest),
+ input_urls=source.input_urls,
+ )
+
+ report = harness._run_once(fixture)
+
+ story = next(
+ item for item in report.items_by_source["hackernews"]
+ if item.item_id == story_id
+ )
+ assert [c["author"] for c in story.metadata["top_comments"]] == [
+ "posted_third",
+ "posted_first",
+ "posted_second",
+ ]
diff --git a/tests/test_hackernews.py b/tests/test_hackernews.py
index ebd35904..dc7decf1 100644
--- a/tests/test_hackernews.py
+++ b/tests/test_hackernews.py
@@ -2,7 +2,7 @@
import json
from datetime import datetime, timezone
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
from urllib.parse import parse_qs, urlsplit
import pytest
@@ -618,5 +618,174 @@ def test_pipeline_hackernews_reports_failed_comment_enrichment(
assert artifact["_source_outcome_detail_state"] == schema.RATE_LIMITED
+# === HN kids ordering (#1285) ===
+
+
+@patch("lib.hackernews.http.request")
+def test_fetch_item_comments_orders_by_firebase_kids(mock_request):
+ """Quoted comments follow HN thread order, not Algolia child / id order."""
+
+ def fake_request(method, url, **kwargs):
+ if url.startswith(hackernews.FIREBASE_ITEM_URL):
+ # HN ranks B then A then C; Algolia listed them A, B, C (id order).
+ return {"kids": [2, 1, 3]}
+ if url.startswith(hackernews.ALGOLIA_ITEM_URL):
+ return {
+ "children": [
+ {"id": 1, "author": "alice", "text": "<p>First posted.</p>", "points": None},
+ {"id": 2, "author": "bob", "text": "<p>Top-ranked reply.</p>", "points": None},
+ {"id": 3, "author": "carol", "text": "<p>Third.</p>", "points": None},
+ ]
+ }
+ raise AssertionError(f"unexpected url: {url}")
+
+ mock_request.side_effect = fake_request
+ result = hackernews._fetch_item_comments("50019911", max_comments=2)
+
+ assert [c["author"] for c in result["comments"]] == ["bob", "alice"]
+ assert result["comments"][0]["url"] == "https://news.ycombinator.com/item?id=2"
+
+
+@patch("lib.hackernews.http.request")
+def test_fetch_item_comments_falls_back_to_points_when_kids_unavailable(mock_request):
+ """If the Firebase kids fetch fails, keep the previous points ordering."""
+
+ def fake_request(method, url, **kwargs):
+ if url.startswith(hackernews.FIREBASE_ITEM_URL):
+ raise hackernews.http.HTTPError("firebase down", status_code=503)
+ return {
+ "children": [
+ {"id": 1, "author": "alice", "text": "low", "points": 1},
+ {"id": 2, "author": "bob", "text": "high", "points": 9},
+ ]
+ }
+
+ mock_request.side_effect = fake_request
+ result = hackernews._fetch_item_comments("123", max_comments=2)
+ assert [c["author"] for c in result["comments"]] == ["bob", "alice"]
+
+
+def test_order_comments_by_kids_appends_unknowns():
+ comments = [
+ {"id": 1, "author": "a"},
+ {"id": 2, "author": "b"},
+ {"id": 99, "author": "extra"},
+ ]
+ ordered = hackernews._order_comments_by_kids(comments, [2, 1])
+ assert [c["id"] for c in ordered] == [2, 1, 99]
+
+
+@patch("lib.http.time.sleep")
+@patch("lib.http.urllib.request.urlopen")
+def test_firebase_kids_failure_stays_out_of_failure_sink(mock_urlopen, _mock_sleep):
+ """A Firebase outage keeps the Algolia comments and records no run failure."""
+ import urllib.error
+
+ from lib import http as lib_http
+
+ algolia_body = json.dumps({
+ "children": [
+ {"id": 1, "author": "alice", "text": "low", "points": 1},
+ {"id": 2, "author": "bob", "text": "high", "points": 9},
+ ]
+ }).encode("utf-8")
+ firebase_calls = []
+
+ def fake_urlopen(req, timeout=None):
+ url = req.full_url
+ if url.startswith(hackernews.FIREBASE_ITEM_URL):
+ firebase_calls.append(url)
+ raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, None)
+ response = MagicMock()
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ response.read.return_value = algolia_body
+ response.status = 200
+ return response
+
+ mock_urlopen.side_effect = fake_urlopen
+ with lib_http.capture_failures() as failures:
+ result = hackernews._fetch_item_comments("123", max_comments=2)
+
+ assert firebase_calls
+ assert failures == []
+ assert [c["author"] for c in result["comments"]] == ["bob", "alice"]
+
+
+
[email protected]("firebase_read", ["incomplete", "non_utf8"])
+@patch("lib.http.time.sleep")
+@patch("lib.http.urllib.request.urlopen")
+def test_firebase_kids_unwrapped_read_errors_fall_back(mock_urlopen, _mock_sleep, firebase_read):
+ """A truncated or undecodable Firebase body keeps the Algolia comments."""
+ import http.client
+
+ from lib import http as lib_http
+
+ algolia_body = json.dumps({
+ "children": [
+ {"id": 1, "author": "alice", "text": "low", "points": 1},
+ {"id": 2, "author": "bob", "text": "high", "points": 9},
+ ]
+ }).encode("utf-8")
+
+ def fake_urlopen(req, timeout=None):
+ response = MagicMock()
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ response.status = 200
+ if req.full_url.startswith(hackernews.FIREBASE_ITEM_URL):
+ if firebase_read == "incomplete":
+ response.read.side_effect = http.client.IncompleteRead(b'{"kids": [1')
+ else:
+ response.read.return_value = b"\xff\xfe"
+ else:
+ response.read.return_value = algolia_body
+ return response
+
+ mock_urlopen.side_effect = fake_urlopen
+ with lib_http.capture_failures() as failures:
+ result = hackernews._fetch_item_comments("123", max_comments=2)
+
+ assert failures == []
+ assert [c["author"] for c in result["comments"]] == ["bob", "alice"]
+
+
+
+@patch("lib.http.time.sleep")
+@patch("lib.http.urllib.request.urlopen")
+def test_firebase_kids_timeouts_are_bounded(mock_urlopen, _mock_sleep):
+ """A hanging Firebase gets a short retry budget, not the default five attempts."""
+ from lib import http as lib_http
+
+ algolia_body = json.dumps({
+ "children": [
+ {"id": 1, "author": "alice", "text": "low", "points": 1},
+ {"id": 2, "author": "bob", "text": "high", "points": 9},
+ ]
+ }).encode("utf-8")
+ firebase_timeouts = []
+
+ def fake_urlopen(req, timeout=None):
+ if req.full_url.startswith(hackernews.FIREBASE_ITEM_URL):
+ firebase_timeouts.append(timeout)
+ raise TimeoutError("timed out")
+ response = MagicMock()
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ response.status = 200
+ response.read.return_value = algolia_body
+ return response
+
+ mock_urlopen.side_effect = fake_urlopen
+ with lib_http.capture_failures() as failures:
+ result = hackernews._fetch_item_comments("123", max_comments=2)
+
+ assert 1 <= len(firebase_timeouts) <= hackernews.FIREBASE_KIDS_RETRIES
+ assert all(t <= hackernews.FIREBASE_KIDS_TIMEOUT for t in firebase_timeouts)
+ assert failures == []
+ assert [c["author"] for c in result["comments"]] == ["bob", "alice"]
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v"])