| 1 | """Regression tests for PR 25: ranking, fusion, normalization & grounding integrity. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-099: Out-of-window floor bypass, sort partitioning, and 0-vs-None engagement tie-break |
| 5 | - HIGH-100: Forward primary_entity and subject_handles on LLM-omitted fallback rows |
| 6 | - HIGH-101: Hardened LLM score parsing (non-list scores, TypeError, NaN/inf, per-row fallback) |
| 7 | - HIGH-105: True primary_scores tracking, url/source_items[0] sync, same-stream RRF guard, spoken_caption |
| 8 | - HIGH-106: Recompute engagement_score on merge, longer enrichment strings, non-mutating weighted_rrf |
| 9 | - HIGH-107: Preserve Arctic Reddit top_comments/attribution/dates through grounding -> normalize |
| 10 | - HIGH-108: UTC clock in grounding._now() so east-of-UTC users keep fresh Serper relative results |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import math |
| 16 | from datetime import datetime, timezone |
| 17 | from unittest.mock import patch |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | from lib import fusion, grounding, normalize, pipeline, reddit_hydrate, reddit_refs, render, rerank, schema, signals |
| 22 | |
| 23 | |
| 24 | def _plan(topic: str = "Hermes Agent", sources: list[str] | None = None) -> schema.QueryPlan: |
| 25 | srcs = sources or ["reddit", "x", "hackernews", "instagram"] |
| 26 | return schema.QueryPlan( |
| 27 | intent="breaking_news", |
| 28 | freshness_mode="strict_recent", |
| 29 | cluster_mode="story", |
| 30 | raw_topic=topic, |
| 31 | subqueries=[ |
| 32 | schema.SubQuery( |
| 33 | label="primary", |
| 34 | search_query=topic, |
| 35 | ranking_query=topic, |
| 36 | sources=srcs, |
| 37 | weight=1.0, |
| 38 | ), |
| 39 | schema.SubQuery( |
| 40 | label="secondary", |
| 41 | search_query=f"{topic} discussion", |
| 42 | ranking_query=f"{topic} discussion", |
| 43 | sources=srcs, |
| 44 | weight=0.8, |
| 45 | ), |
| 46 | ], |
| 47 | source_weights={s: 1.0 for s in srcs}, |
| 48 | ) |
| 49 | |
| 50 | |
| 51 | def _cand( |
| 52 | cid: str, |
| 53 | *, |
| 54 | source: str = "x", |
| 55 | title: str = "Hermes Agent update", |
| 56 | snippet: str = "Hermes Agent release notes", |
| 57 | author: str | None = "someone", |
| 58 | published_at: str | None = "2026-10-20", |
| 59 | date_confidence: str = "high", |
| 60 | range_from: str = "2026-10-01", |
| 61 | range_to: str = "2026-10-31", |
| 62 | local_relevance: float = 0.6, |
| 63 | freshness: int = 80, |
| 64 | engagement: float | int | None = 50, |
| 65 | source_quality: float = 0.68, |
| 66 | rrf_score: float = 0.02, |
| 67 | mentions: list[str] | None = None, |
| 68 | ) -> schema.Candidate: |
| 69 | item = schema.SourceItem( |
| 70 | item_id=cid, |
| 71 | source=source, |
| 72 | title=title, |
| 73 | body=f"{title} {snippet}", |
| 74 | url=f"https://example.com/{source}/{cid}", |
| 75 | author=author, |
| 76 | published_at=published_at, |
| 77 | date_confidence=date_confidence, |
| 78 | snippet=snippet, |
| 79 | metadata={"mentioned_handles": list(mentions)} if mentions else {}, |
| 80 | ) |
| 81 | return schema.Candidate( |
| 82 | candidate_id=cid, |
| 83 | item_id=cid, |
| 84 | source=source, |
| 85 | title=title, |
| 86 | url=item.url, |
| 87 | snippet=snippet, |
| 88 | subquery_labels=["primary"], |
| 89 | native_ranks={f"primary:{source}": 1}, |
| 90 | local_relevance=local_relevance, |
| 91 | freshness=freshness, |
| 92 | engagement=engagement, |
| 93 | source_quality=source_quality, |
| 94 | rrf_score=rrf_score, |
| 95 | sources=[source], |
| 96 | source_items=[item], |
| 97 | metadata={"range_from": range_from, "range_to": range_to}, |
| 98 | ) |
| 99 | |
| 100 | |
| 101 | class _FakeProvider: |
| 102 | def __init__(self, payload=None, *, exc: Exception | None = None): |
| 103 | self.payload = payload |
| 104 | self.exc = exc |
| 105 | |
| 106 | def generate_json(self, _model: str, _prompt: str): |
| 107 | if self.exc is not None: |
| 108 | raise self.exc |
| 109 | return self.payload |
| 110 | |
| 111 | |
| 112 | # --------------------------------------------------------------------------- |
| 113 | # HIGH-099: Out-of-window floor bypass, sort partitioning & 0-vs-None tiebreak |
| 114 | # --------------------------------------------------------------------------- |
| 115 | |
| 116 | |
| 117 | class TestHigh099OutOfWindowAndTieBreaker: |
| 118 | def test_post_scoring_floors_never_lift_out_of_window_candidates(self): |
| 119 | stale_fp = _cand( |
| 120 | "stale-fp", |
| 121 | author="steipete", |
| 122 | title="Old post", |
| 123 | snippet="Old post", |
| 124 | published_at="2024-05-01", |
| 125 | engagement=100, |
| 126 | mentions=["friend"], |
| 127 | ) |
| 128 | stale_fp.final_score = 12.0 |
| 129 | assert schema.candidate_out_of_window(stale_fp) |
| 130 | |
| 131 | in_win_low = _cand( |
| 132 | "fresh-low", |
| 133 | author="observer", |
| 134 | title="Peter Steinberger update", |
| 135 | snippet="Peter Steinberger update", |
| 136 | published_at="2026-10-20", |
| 137 | engagement=10, |
| 138 | ) |
| 139 | in_win_low.final_score = 5.0 |
| 140 | in_win_high = _cand( |
| 141 | "fresh-high", |
| 142 | author="observer2", |
| 143 | title="Peter Steinberger release", |
| 144 | snippet="Peter Steinberger release", |
| 145 | published_at="2026-10-22", |
| 146 | engagement=80, |
| 147 | ) |
| 148 | in_win_high.final_score = 5.0 |
| 149 | |
| 150 | rerank._apply_first_party_floor( |
| 151 | [stale_fp], |
| 152 | resolved_handles={"steipete"}, |
| 153 | primary_entity="Peter Steinberger", |
| 154 | topic="Peter Steinberger", |
| 155 | primary_handle="steipete", |
| 156 | ) |
| 157 | assert stale_fp.final_score == 12.0 |
| 158 | |
| 159 | rerank._apply_interaction_signal( |
| 160 | [stale_fp], |
| 161 | resolved_handles={"steipete"}, |
| 162 | primary_entity="Peter Steinberger", |
| 163 | topic="Peter Steinberger", |
| 164 | primary_handle="steipete", |
| 165 | ) |
| 166 | assert stale_fp.final_score == 12.0 |
| 167 | assert stale_fp.metadata.get("interaction_targets") == ["friend"] |
| 168 | |
| 169 | # Stale viral X post is excluded from engagement rescue AND must not |
| 170 | # suppress the in-window top X post's rescue floor. |
| 171 | rerank._apply_engagement_rescue( |
| 172 | [stale_fp, in_win_low, in_win_high], |
| 173 | primary_entity="Peter Steinberger", |
| 174 | resolved_handles={"steipete"}, |
| 175 | topic="Peter Steinberger", |
| 176 | primary_handle="steipete", |
| 177 | ) |
| 178 | assert stale_fp.final_score == 12.0 |
| 179 | assert in_win_high.final_score == pytest.approx(rerank.RESCUE_FLOOR_MAX) |
| 180 | |
| 181 | def test_rerank_candidates_partitions_in_window_ahead_of_stale_viral_subject_post(self): |
| 182 | stale_viral = _cand( |
| 183 | "stale-viral", |
| 184 | source="x", |
| 185 | author="steipete", |
| 186 | title="Peter Steinberger viral 2024 thread", |
| 187 | snippet="Huge viral thread from two years ago", |
| 188 | published_at="2024-06-15", |
| 189 | local_relevance=0.95, |
| 190 | freshness=90, |
| 191 | engagement=100, |
| 192 | mentions=["someone"], |
| 193 | ) |
| 194 | stale_low = _cand( |
| 195 | "stale-low", |
| 196 | source="x", |
| 197 | author="steipete", |
| 198 | title="Old short post", |
| 199 | snippet="Old short post", |
| 200 | published_at="2024-06-10", |
| 201 | local_relevance=0.1, |
| 202 | freshness=20, |
| 203 | engagement=5, |
| 204 | mentions=["friend"], |
| 205 | ) |
| 206 | fresh_modest = _cand( |
| 207 | "fresh-modest", |
| 208 | source="x", |
| 209 | author="observer", |
| 210 | title="Peter Steinberger note today", |
| 211 | snippet="Short note mentioning Peter Steinberger", |
| 212 | published_at="2026-10-25", |
| 213 | local_relevance=0.3, |
| 214 | freshness=60, |
| 215 | engagement=5, |
| 216 | ) |
| 217 | ranked = rerank.rerank_candidates( |
| 218 | topic="Peter Steinberger", |
| 219 | plan=_plan("Peter Steinberger", ["x"]), |
| 220 | candidates=[stale_viral, stale_low, fresh_modest], |
| 221 | provider=None, |
| 222 | model=None, |
| 223 | shortlist_size=10, |
| 224 | resolved_handles={"steipete"}, |
| 225 | primary_handle="steipete", |
| 226 | ) |
| 227 | # In-window candidate always partitions ahead of out-of-window candidates, |
| 228 | # even when stale_viral has a higher scaled final_score than fresh_modest. |
| 229 | assert [c.candidate_id for c in ranked] == ["fresh-modest", "stale-viral", "stale-low"] |
| 230 | # Neither INTERACTION_FLOOR (35) nor RESCUE_FLOOR_MAX (40) nor FIRST_PARTY_FLOOR (25) |
| 231 | # lifted the out-of-window candidates above their 0.35x-scaled _final_score. |
| 232 | assert stale_viral.final_score == pytest.approx(rerank._final_score(stale_viral)) |
| 233 | assert stale_viral.final_score < rerank.INTERACTION_FLOOR |
| 234 | assert stale_low.final_score == pytest.approx(rerank._final_score(stale_low)) |
| 235 | assert stale_low.final_score < rerank.FIRST_PARTY_FLOOR |
| 236 | |
| 237 | def test_engagement_tie_breaker_prefers_measured_zero_over_unknown_none(self): |
| 238 | measured_zero = _cand( |
| 239 | "z-measured", |
| 240 | source="reddit", |
| 241 | title="ZZZ Hermes Agent thread", |
| 242 | engagement=0, |
| 243 | local_relevance=0.5, |
| 244 | freshness=70, |
| 245 | ) |
| 246 | unknown_none = _cand( |
| 247 | "a-unknown", |
| 248 | source="reddit", |
| 249 | title="AAA Hermes Agent thread", |
| 250 | engagement=None, |
| 251 | local_relevance=0.5, |
| 252 | freshness=70, |
| 253 | ) |
| 254 | ranked = rerank.rerank_candidates( |
| 255 | topic="Hermes Agent", |
| 256 | plan=_plan("Hermes Agent", ["reddit"]), |
| 257 | candidates=[unknown_none, measured_zero], |
| 258 | provider=None, |
| 259 | model=None, |
| 260 | shortlist_size=10, |
| 261 | ) |
| 262 | assert measured_zero.final_score == pytest.approx(unknown_none.final_score) |
| 263 | assert [c.candidate_id for c in ranked] == ["z-measured", "a-unknown"] |
| 264 | |
| 265 | def test_pipeline_final_sort_shares_candidate_sort_key_zero_beats_none(self): |
| 266 | measured_zero = _cand( |
| 267 | "measured-zero", |
| 268 | source="reddit", |
| 269 | title="ZZZ Hermes Agent thread", |
| 270 | engagement=0, |
| 271 | local_relevance=0.5, |
| 272 | freshness=70, |
| 273 | ) |
| 274 | measured_zero.native_ranks = {"primary:reddit": 5} |
| 275 | measured_zero.final_score = 45.0 |
| 276 | |
| 277 | unknown_none = _cand( |
| 278 | "unknown-none", |
| 279 | source="reddit", |
| 280 | title="AAA Hermes Agent thread", |
| 281 | engagement=None, |
| 282 | local_relevance=0.5, |
| 283 | freshness=70, |
| 284 | ) |
| 285 | unknown_none.native_ranks = {"primary:reddit": 1} |
| 286 | unknown_none.final_score = 45.0 |
| 287 | |
| 288 | assert rerank.candidate_sort_key(measured_zero) < rerank.candidate_sort_key(unknown_none) |
| 289 | |
| 290 | with patch.object(pipeline, "_retrieve_stream", return_value=([], {})), \ |
| 291 | patch.object(rerank, "rerank_candidates", side_effect=[[unknown_none, measured_zero], []]): |
| 292 | report = pipeline.run( |
| 293 | topic="Hermes Agent", |
| 294 | config={}, |
| 295 | depth="quick", |
| 296 | mock=True, |
| 297 | requested_sources=["reddit"], |
| 298 | web_backend="none", |
| 299 | as_of_date="2026-10-31", |
| 300 | ) |
| 301 | assert [c.candidate_id for c in report.ranked_candidates] == [ |
| 302 | "measured-zero", |
| 303 | "unknown-none", |
| 304 | ] |
| 305 | |
| 306 | |
| 307 | # --------------------------------------------------------------------------- |
| 308 | # HIGH-100: Forward primary_entity and subject_handles on LLM-omitted rows |
| 309 | # --------------------------------------------------------------------------- |
| 310 | |
| 311 | |
| 312 | class TestHigh100LlmOmittedFallbackGrounding: |
| 313 | def test_omitted_off_topic_candidate_gets_entity_miss_and_is_pruned(self): |
| 314 | scored = _cand("on-topic", source="youtube", title="Hermes Agent guide", snippet="Hermes Agent") |
| 315 | omitted_off = _cand( |
| 316 | "omitted-off", |
| 317 | source="youtube", |
| 318 | title="Managed Agents by Anthropic", |
| 319 | snippet="Completely unrelated workflow", |
| 320 | local_relevance=0.3, |
| 321 | ) |
| 322 | provider = _FakeProvider( |
| 323 | {"scores": [{"candidate_id": "on-topic", "relevance": 85, "reason": "direct match"}]} |
| 324 | ) |
| 325 | ranked = rerank.rerank_candidates( |
| 326 | topic="Hermes Agent use cases", |
| 327 | plan=_plan("Hermes Agent use cases", ["youtube"]), |
| 328 | candidates=[scored, omitted_off], |
| 329 | provider=provider, |
| 330 | model="test-model", |
| 331 | shortlist_size=10, |
| 332 | ) |
| 333 | assert omitted_off.explanation == rerank._FALLBACK_ENTITY_MISS_EXPLANATION |
| 334 | assert rerank._is_fallback_scored(omitted_off) |
| 335 | pruned = rerank.prune_fallback_entity_misses(ranked, topic="Hermes Agent use cases") |
| 336 | assert [c.candidate_id for c in pruned] == ["on-topic"] |
| 337 | |
| 338 | def test_omitted_off_topic_related_handle_does_not_get_first_party_credit(self): |
| 339 | scored = _cand("scored", source="x", author="observer", title="Ghostty 1.3", snippet="Ghostty") |
| 340 | related_off = _cand( |
| 341 | "related-off", |
| 342 | source="x", |
| 343 | author="mitchellh", |
| 344 | title="@friend Nanit", |
| 345 | snippet="@friend Nanit", |
| 346 | local_relevance=0.0, |
| 347 | freshness=70, |
| 348 | engagement=10, |
| 349 | ) |
| 350 | subject_omitted = _cand( |
| 351 | "subject-omitted", |
| 352 | source="x", |
| 353 | author="ghostty", |
| 354 | title="shipping tonight", |
| 355 | snippet="shipping tonight", |
| 356 | local_relevance=0.0, |
| 357 | freshness=70, |
| 358 | engagement=10, |
| 359 | ) |
| 360 | provider = _FakeProvider( |
| 361 | {"scores": [{"candidate_id": "scored", "relevance": 90, "reason": "on topic"}]} |
| 362 | ) |
| 363 | rerank.rerank_candidates( |
| 364 | topic="Ghostty terminal", |
| 365 | plan=_plan("Ghostty terminal", ["x"]), |
| 366 | candidates=[scored, related_off, subject_omitted], |
| 367 | provider=provider, |
| 368 | model="test-model", |
| 369 | shortlist_size=10, |
| 370 | resolved_handles={"mitchellh", "ghostty"}, |
| 371 | primary_handle="ghostty", |
| 372 | ) |
| 373 | # Related off-topic handle omits entity -> no +5.0 credit, no floor lift. |
| 374 | expected_base = (0.0 * 70.0) + (related_off.source_quality * 10.0) |
| 375 | assert related_off.rerank_score == pytest.approx(expected_base) |
| 376 | assert related_off.final_score < rerank.FIRST_PARTY_FLOOR |
| 377 | # Subject handle ("ghostty" matches "Ghostty terminal") keeps +5.0 credit. |
| 378 | assert subject_omitted.rerank_score == pytest.approx(expected_base + rerank.FIRST_PARTY_AUTHOR_CREDIT) |
| 379 | assert subject_omitted.final_score >= rerank.FIRST_PARTY_FLOOR |
| 380 | |
| 381 | |
| 382 | # --------------------------------------------------------------------------- |
| 383 | # HIGH-101: Hardened LLM score parsing and TypeError / NaN / inf safety |
| 384 | # --------------------------------------------------------------------------- |
| 385 | |
| 386 | |
| 387 | class TestHigh101MalformedLlmPayloads: |
| 388 | @pytest.mark.parametrize("bad_payload", [ |
| 389 | {"scores": 123}, |
| 390 | {"scores": True}, |
| 391 | {"scores": "not-a-list"}, |
| 392 | {"scores": {"c1": 90}}, |
| 393 | None, |
| 394 | ["not-a-dict"], |
| 395 | ]) |
| 396 | def test_non_list_scores_and_non_dict_payloads_fall_back_without_crashing(self, bad_payload): |
| 397 | c1 = _cand("c1", title="Hermes Agent news", snippet="Hermes Agent") |
| 398 | provider = _FakeProvider(bad_payload) |
| 399 | ranked = rerank.rerank_candidates( |
| 400 | topic="Hermes Agent", |
| 401 | plan=_plan("Hermes Agent", ["x"]), |
| 402 | candidates=[c1], |
| 403 | provider=provider, |
| 404 | model="test-model", |
| 405 | shortlist_size=5, |
| 406 | ) |
| 407 | assert len(ranked) == 1 |
| 408 | assert rerank._is_fallback_scored(c1) |
| 409 | assert math.isfinite(c1.final_score) |
| 410 | |
| 411 | rerank.score_fun( |
| 412 | topic="Hermes Agent", |
| 413 | candidates=[c1], |
| 414 | provider=provider, |
| 415 | model="test-model", |
| 416 | ) |
| 417 | assert c1.fun_explanation == "heuristic-fallback" |
| 418 | assert c1.fun_score is not None and math.isfinite(c1.fun_score) |
| 419 | |
| 420 | def test_provider_raising_type_error_is_caught_by_rerank_and_score_fun(self): |
| 421 | c1 = _cand("c1", title="Hermes Agent", snippet="Hermes Agent") |
| 422 | provider = _FakeProvider(exc=TypeError("bad wire payload")) |
| 423 | ranked = rerank.rerank_candidates( |
| 424 | topic="Hermes Agent", |
| 425 | plan=_plan("Hermes Agent", ["x"]), |
| 426 | candidates=[c1], |
| 427 | provider=provider, |
| 428 | model="test-model", |
| 429 | shortlist_size=5, |
| 430 | ) |
| 431 | assert len(ranked) == 1 |
| 432 | assert rerank._is_fallback_scored(c1) |
| 433 | |
| 434 | rerank.score_fun(topic="Hermes Agent", candidates=[c1], provider=provider, model="test-model") |
| 435 | assert c1.fun_explanation == "heuristic-fallback" |
| 436 | |
| 437 | @pytest.mark.parametrize("bad_val", [ |
| 438 | "high", |
| 439 | "85/100", |
| 440 | [85], |
| 441 | {"score": 90}, |
| 442 | True, |
| 443 | False, |
| 444 | None, |
| 445 | "NaN", |
| 446 | float("nan"), |
| 447 | "inf", |
| 448 | "-inf", |
| 449 | float("inf"), |
| 450 | "1e500", |
| 451 | 10**400, |
| 452 | ]) |
| 453 | def test_bad_row_only_falls_back_that_candidate_and_preserves_batch(self, bad_val): |
| 454 | good = _cand("good", title="Hermes Agent launch", snippet="Hermes Agent") |
| 455 | zero = _cand("zero", title="Hermes Agent note", snippet="Hermes Agent") |
| 456 | bad = _cand("bad", title="Hermes Agent misc", snippet="Hermes Agent", local_relevance=0.2) |
| 457 | payload = { |
| 458 | "scores": [ |
| 459 | {"candidate_id": "good", "relevance": 88, "reason": "strong hit"}, |
| 460 | {"candidate_id": "zero", "relevance": 0, "reason": "explicit zero"}, |
| 461 | {"candidate_id": "bad", "relevance": bad_val, "reason": "corrupt"}, |
| 462 | ] |
| 463 | } |
| 464 | rerank._apply_llm_scores([good, zero, bad], payload, primary_entity="Hermes Agent") |
| 465 | assert good.rerank_score == 88.0 |
| 466 | assert good.explanation == "strong hit" |
| 467 | assert not rerank._is_fallback_scored(good) |
| 468 | assert zero.rerank_score == 0.0 |
| 469 | assert zero.explanation == "explicit zero" |
| 470 | assert not rerank._is_fallback_scored(zero) |
| 471 | # Corrupted row falls back instead of becoming 100.0 or aborting the batch. |
| 472 | assert rerank._is_fallback_scored(bad) |
| 473 | assert bad.rerank_score is not None |
| 474 | assert math.isfinite(bad.rerank_score) |
| 475 | assert bad.rerank_score < 50.0 |
| 476 | |
| 477 | fun_payload = { |
| 478 | "scores": [ |
| 479 | {"candidate_id": "good", "fun": 77, "reason": "witty"}, |
| 480 | {"candidate_id": "zero", "fun": 0, "reason": "dry"}, |
| 481 | {"candidate_id": "bad", "fun": bad_val, "reason": "corrupt"}, |
| 482 | ] |
| 483 | } |
| 484 | rerank._apply_fun_scores([good, zero, bad], fun_payload) |
| 485 | assert good.fun_score == 77.0 |
| 486 | assert good.fun_explanation == "witty" |
| 487 | assert zero.fun_score == 0.0 |
| 488 | assert zero.fun_explanation == "dry" |
| 489 | assert bad.fun_explanation == "heuristic-fallback" |
| 490 | assert bad.fun_score is not None and math.isfinite(bad.fun_score) and bad.fun_score < 100.0 |
| 491 | |
| 492 | |
| 493 | # --------------------------------------------------------------------------- |
| 494 | # HIGH-105: Primary scores, url/source_items sync, same-stream RRF, spoken_caption |
| 495 | # --------------------------------------------------------------------------- |
| 496 | |
| 497 | |
| 498 | class TestHigh105FusionMultiItemIntegrity: |
| 499 | def _item( |
| 500 | self, |
| 501 | item_id: str, |
| 502 | source: str, |
| 503 | url: str, |
| 504 | title: str, |
| 505 | *, |
| 506 | rel: float, |
| 507 | fresh: int, |
| 508 | qual: float, |
| 509 | snippet: str = "", |
| 510 | engagement: dict | None = None, |
| 511 | metadata: dict | None = None, |
| 512 | ) -> schema.SourceItem: |
| 513 | it = schema.SourceItem( |
| 514 | item_id=item_id, |
| 515 | source=source, |
| 516 | title=title, |
| 517 | body=title, |
| 518 | url=url, |
| 519 | snippet=snippet or title, |
| 520 | engagement=dict(engagement or {}), |
| 521 | metadata=dict(metadata or {}), |
| 522 | ) |
| 523 | it.local_relevance = rel |
| 524 | it.freshness = fresh |
| 525 | it.source_quality = qual |
| 526 | return it |
| 527 | |
| 528 | def test_true_primary_score_prevents_synthetic_max_lockout(self): |
| 529 | # Item 1: 90 + 10 + 6.8 = 106.8 |
| 530 | # Item 2: 20 + 90 + 6.0 = 116.0 (beats Item 1; synthetic max would be 90+90+6.8=186.8!) |
| 531 | # Item 3: 85 + 85 + 8.0 = 178.0 (must beat Item 2's true 116.0!) |
| 532 | shared_url = "https://example.com/story" |
| 533 | i1 = self._item("x1", "x", f"{shared_url}?utm_source=x", "X copy", rel=0.9, fresh=10, qual=0.68) |
| 534 | i2 = self._item("r1", "reddit", f"{shared_url}?utm_source=r", "Reddit copy", rel=0.2, fresh=90, qual=0.60) |
| 535 | i3 = self._item("hn1", "hackernews", shared_url, "HN best copy", rel=0.85, fresh=85, qual=0.80, |
| 536 | metadata={"hn_url": "https://news.ycombinator.com/item?id=999"}) |
| 537 | plan = _plan("story", ["x", "reddit", "hackernews"]) |
| 538 | streams = { |
| 539 | ("primary", "x"): [i1], |
| 540 | ("primary", "reddit"): [i2], |
| 541 | ("primary", "hackernews"): [i3], |
| 542 | } |
| 543 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 544 | assert cand.item_id == "hn1" |
| 545 | assert cand.source == "hackernews" |
| 546 | assert cand.title == "HN best copy" |
| 547 | assert cand.url == shared_url |
| 548 | assert cand.source_items[0].item_id == "hn1" |
| 549 | assert schema.candidate_primary_item(cand).item_id == "hn1" |
| 550 | |
| 551 | @pytest.mark.parametrize("primary_first", [True, False]) |
| 552 | @pytest.mark.parametrize("spoken", [True, False]) |
| 553 | def test_cross_source_evidence_stays_with_its_primary_submission(self, primary_first, spoken): |
| 554 | url = "https://www.instagram.com/reel/abc123/" |
| 555 | primary = self._item( |
| 556 | "web", "grounding", url, "Article title", rel=0.95, fresh=80, qual=0.8, |
| 557 | snippet="The article's evidence.", |
| 558 | ) |
| 559 | reel = self._item( |
| 560 | "ig", "instagram", url, "Reel title", rel=0.3, fresh=60, qual=0.58, |
| 561 | snippet="A different and much longer caption from the Instagram submission.", |
| 562 | metadata={"spoken_caption": spoken}, |
| 563 | ) |
| 564 | items = [primary, reel] if primary_first else [reel, primary] |
| 565 | streams = {("primary", item.source): [item] for item in items} |
| 566 | [candidate] = fusion.weighted_rrf(streams, _plan("topic", ["grounding", "instagram"]), pool_limit=10) |
| 567 | assert candidate.source == "grounding" |
| 568 | assert candidate.snippet == primary.snippet |
| 569 | assert len(candidate.source_items) == 2 |
| 570 | |
| 571 | def test_higher_scoring_hn_sibling_syncs_url_source_items_and_snippet(self): |
| 572 | hn1 = self._item( |
| 573 | "100", "hackernews", "https://sqlite.org/release.html?utm_source=first", "Weak HN title", |
| 574 | rel=0.3, fresh=60, qual=0.8, snippet="Weak first submission snippet", |
| 575 | engagement={"points": 5, "comments": 1}, |
| 576 | metadata={"hn_url": "https://news.ycombinator.com/item?id=100"}, |
| 577 | ) |
| 578 | hn2 = self._item( |
| 579 | "200", "hackernews", "https://sqlite.org/release.html", "Strong HN title", |
| 580 | rel=0.9, fresh=85, qual=0.8, snippet="Strong winning submission snippet", |
| 581 | engagement={"points": 400, "comments": 120}, |
| 582 | metadata={"hn_url": "https://news.ycombinator.com/item?id=200"}, |
| 583 | ) |
| 584 | plan = _plan("sqlite", ["hackernews"]) |
| 585 | streams = { |
| 586 | ("primary", "hackernews"): [hn1], |
| 587 | ("secondary", "hackernews"): [hn2], |
| 588 | } |
| 589 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 590 | assert cand.item_id == "200" |
| 591 | assert cand.title == "Strong HN title" |
| 592 | assert cand.url == "https://sqlite.org/release.html" |
| 593 | assert cand.source_items[0].item_id == "200" |
| 594 | primary = schema.candidate_primary_item(cand) |
| 595 | assert primary is not None |
| 596 | assert primary.item_id == "200" |
| 597 | assert cand.snippet == "Strong winning submission snippet" |
| 598 | |
| 599 | def test_same_stream_duplicate_candidate_key_does_not_double_rrf_or_worsen_rank(self): |
| 600 | hn1 = self._item( |
| 601 | "100", "hackernews", "https://example.com/post", "Article (submission 1)", |
| 602 | rel=0.8, fresh=80, qual=0.8, |
| 603 | metadata={"hn_url": "https://news.ycombinator.com/item?id=100"}, |
| 604 | ) |
| 605 | other = self._item( |
| 606 | "150", "hackernews", "https://example.com/other", "Other article", |
| 607 | rel=0.7, fresh=80, qual=0.8, |
| 608 | metadata={"hn_url": "https://news.ycombinator.com/item?id=150"}, |
| 609 | ) |
| 610 | hn2 = self._item( |
| 611 | "200", "hackernews", "https://example.com/post", "Article (submission 2)", |
| 612 | rel=0.6, fresh=80, qual=0.8, |
| 613 | metadata={"hn_url": "https://news.ycombinator.com/item?id=200"}, |
| 614 | ) |
| 615 | plan = _plan("test", ["hackernews"]) |
| 616 | streams = {("primary", "hackernews"): [hn1, other, hn2]} |
| 617 | cands = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 618 | merged = next(c for c in cands if c.candidate_id == "https://example.com/post") |
| 619 | expected_rrf = 1.0 / (fusion.RRF_K + 1) |
| 620 | assert merged.rrf_score == pytest.approx(expected_rrf) |
| 621 | assert merged.native_ranks["primary:hackernews"] == 1 |
| 622 | assert len(merged.source_items) == 2 |
| 623 | |
| 624 | def test_weighted_rrf_preserves_spoken_caption_in_both_orders(self): |
| 625 | url = "https://www.instagram.com/reel/abc123/" |
| 626 | spoken_text = "Short spoken quote." |
| 627 | written_text = "Very long written description full of hashtags and filler words for engagement." |
| 628 | plan = _plan("topic", ["instagram"]) |
| 629 | |
| 630 | for order in ("spoken_first", "written_first"): |
| 631 | spoken = self._item( |
| 632 | "ig-s", "instagram", url, "Reel", rel=0.4, fresh=80, qual=0.58, |
| 633 | snippet=spoken_text, metadata={"spoken_caption": True}, |
| 634 | ) |
| 635 | written = self._item( |
| 636 | "ig-w", "instagram", url, "Reel", rel=0.9, fresh=90, qual=0.58, |
| 637 | snippet=written_text, metadata={"spoken_caption": False}, |
| 638 | ) |
| 639 | streams = ( |
| 640 | {("primary", "instagram"): [spoken], ("secondary", "instagram"): [written]} |
| 641 | if order == "spoken_first" |
| 642 | else {("primary", "instagram"): [written], ("secondary", "instagram"): [spoken]} |
| 643 | ) |
| 644 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 645 | assert cand.snippet == spoken_text, order |
| 646 | assert cand.source_items[0].snippet == spoken_text, order |
| 647 | assert cand.source_items[0].metadata.get("spoken_caption") is True, order |
| 648 | |
| 649 | def test_same_key_reddit_promotion_syncs_primary_item_and_preserves_enrichment(self): |
| 650 | comment_url = "https://www.reddit.com/r/ghostty/comments/abc123/release/c999/" |
| 651 | thread_url = "https://www.reddit.com/r/ghostty/comments/abc123/release/" |
| 652 | comment_copy = self._item( |
| 653 | "R1", |
| 654 | "reddit", |
| 655 | comment_url, |
| 656 | "Comment permalink title", |
| 657 | rel=0.3, |
| 658 | fresh=60, |
| 659 | qual=0.6, |
| 660 | snippet="Earlier comment copy snippet", |
| 661 | engagement={"score": 412, "num_comments": 25}, |
| 662 | metadata={ |
| 663 | "engagement_source": reddit_refs.LIVE, |
| 664 | "top_comments": [ |
| 665 | {"id": "c1", "score": 80, "author": "alice", "excerpt": "great release", "depth": 0} |
| 666 | ], |
| 667 | }, |
| 668 | ) |
| 669 | thread_copy = self._item( |
| 670 | "R2", |
| 671 | "reddit", |
| 672 | thread_url, |
| 673 | "Ghostty 2.0 Released", |
| 674 | rel=0.9, |
| 675 | fresh=90, |
| 676 | qual=0.6, |
| 677 | snippet="Canonical thread snippet with full context", |
| 678 | engagement={"score": None, "num_comments": 0}, |
| 679 | metadata={ |
| 680 | "engagement_source": reddit_refs.ARCTIC_PENDING, |
| 681 | "top_comments": [ |
| 682 | {"id": "c2", "score": 30, "author": "bob", "excerpt": "fast rendering", "depth": 0} |
| 683 | ], |
| 684 | }, |
| 685 | ) |
| 686 | assert fusion.source_item_key(comment_copy) == fusion.source_item_key(thread_copy) |
| 687 | |
| 688 | plan = _plan("ghostty", ["reddit"]) |
| 689 | streams = { |
| 690 | ("primary", "reddit"): [comment_copy], |
| 691 | ("secondary", "reddit"): [thread_copy], |
| 692 | } |
| 693 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 694 | |
| 695 | assert len(cand.source_items) == 1 |
| 696 | primary = schema.candidate_primary_item(cand) |
| 697 | assert primary is cand.source_items[0] |
| 698 | # Finding and citation agree on the promoted winning copy. |
| 699 | assert cand.item_id == primary.item_id == "R2" |
| 700 | assert cand.title == primary.title == "Ghostty 2.0 Released" |
| 701 | assert cand.url == primary.url == thread_url |
| 702 | # Live engagement and comments from the demoted copy were folded into primary. |
| 703 | assert primary.engagement["score"] == 412 |
| 704 | assert primary.engagement["num_comments"] == 25 |
| 705 | assert primary.metadata["engagement_source"] == reddit_refs.LIVE |
| 706 | assert [c["id"] for c in primary.metadata["top_comments"]] == ["c1", "c2"] |
| 707 | expected_score = signals.engagement_score(primary) |
| 708 | assert primary.engagement_score == expected_score |
| 709 | assert cand.engagement == expected_score |
| 710 | # Caller-owned top_comments dicts are isolated from candidate mutations. |
| 711 | primary.metadata["top_comments"][0]["author"] = "mutated" |
| 712 | assert comment_copy.metadata["top_comments"][0]["author"] == "alice" |
| 713 | assert thread_copy.metadata["top_comments"][0]["author"] == "bob" |
| 714 | |
| 715 | def test_lower_scoring_reddit_duplicate_merge_isolates_caller_comment_dicts(self): |
| 716 | url = "https://www.reddit.com/r/ghostty/comments/iso123/update/" |
| 717 | high = self._item( |
| 718 | "R1", |
| 719 | "reddit", |
| 720 | url, |
| 721 | "Ghostty update", |
| 722 | rel=0.9, |
| 723 | fresh=90, |
| 724 | qual=0.6, |
| 725 | engagement={"score": 300, "num_comments": 20}, |
| 726 | metadata={ |
| 727 | "engagement_source": reddit_refs.LIVE, |
| 728 | "top_comments": [ |
| 729 | {"id": "c1", "score": 90, "author": "alice", "excerpt": "first comment", "depth": 0} |
| 730 | ], |
| 731 | }, |
| 732 | ) |
| 733 | low = self._item( |
| 734 | "R2", |
| 735 | "reddit", |
| 736 | url, |
| 737 | "Ghostty update", |
| 738 | rel=0.3, |
| 739 | fresh=60, |
| 740 | qual=0.6, |
| 741 | engagement={"score": 100, "num_comments": 10}, |
| 742 | metadata={ |
| 743 | "engagement_source": reddit_refs.ARCTIC, |
| 744 | "top_comments": [ |
| 745 | {"id": "c2", "score": 40, "author": "bob", "excerpt": "second comment", "depth": 0} |
| 746 | ], |
| 747 | }, |
| 748 | ) |
| 749 | plan = _plan("ghostty", ["reddit"]) |
| 750 | streams = {("primary", "reddit"): [high], ("secondary", "reddit"): [low]} |
| 751 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 752 | fused_comments = cand.source_items[0].metadata["top_comments"] |
| 753 | assert [c["id"] for c in fused_comments] == ["c1", "c2"] |
| 754 | for c in fused_comments: |
| 755 | c["author"] = "corrupted" |
| 756 | assert high.metadata["top_comments"][0]["author"] == "alice" |
| 757 | assert low.metadata["top_comments"][0]["author"] == "bob" |
| 758 | |
| 759 | # Direct merge_source_items also copies comment dicts returned by union_comments. |
| 760 | merged = fusion.merge_source_items(high, low) |
| 761 | for c in merged.metadata["top_comments"]: |
| 762 | c["excerpt"] = "overwritten" |
| 763 | assert low.metadata["top_comments"][0]["excerpt"] == "second comment" |
| 764 | |
| 765 | def test_reddit_promotion_and_merge_preserve_paired_matched_comment_date_and_url(self): |
| 766 | thread_url = "https://www.reddit.com/r/python/comments/abc123/old_thread/" |
| 767 | comment_url = "https://www.reddit.com/r/python/comments/abc123/old_thread/c1/" |
| 768 | matched_copy = schema.SourceItem( |
| 769 | item_id="R-comment", |
| 770 | source="reddit", |
| 771 | title="Old thread with fresh comment", |
| 772 | body="Old thread with fresh comment", |
| 773 | url=comment_url, |
| 774 | published_at="2024-01-01", |
| 775 | date_confidence="high", |
| 776 | local_relevance=0.4, |
| 777 | freshness=50, |
| 778 | source_quality=0.6, |
| 779 | engagement={"score": 20, "num_comments": 5}, |
| 780 | metadata={ |
| 781 | "matched_comment_date": "2026-11-20", |
| 782 | "matched_comment_url": comment_url, |
| 783 | }, |
| 784 | ) |
| 785 | higher_copy = schema.SourceItem( |
| 786 | item_id="R-thread", |
| 787 | source="reddit", |
| 788 | title="Old thread with fresh comment (higher rank)", |
| 789 | body="Old thread with fresh comment", |
| 790 | url=thread_url, |
| 791 | published_at="2024-01-01", |
| 792 | date_confidence="high", |
| 793 | local_relevance=0.95, |
| 794 | freshness=50, |
| 795 | source_quality=0.6, |
| 796 | engagement={"score": 300, "num_comments": 50}, |
| 797 | metadata={}, |
| 798 | ) |
| 799 | plan = _plan("python", ["reddit"]) |
| 800 | streams = { |
| 801 | ("primary", "reddit"): [matched_copy], |
| 802 | ("secondary", "reddit"): [higher_copy], |
| 803 | } |
| 804 | [cand] = fusion.weighted_rrf( |
| 805 | streams, |
| 806 | plan, |
| 807 | pool_limit=10, |
| 808 | range_from="2026-10-25", |
| 809 | range_to="2026-11-24", |
| 810 | ) |
| 811 | primary = schema.candidate_primary_item(cand) |
| 812 | assert primary is cand.source_items[0] |
| 813 | assert primary.item_id == "R-thread" |
| 814 | assert primary.metadata["matched_comment_date"] == "2026-11-20" |
| 815 | assert primary.metadata["matched_comment_url"] == comment_url |
| 816 | assert not schema.candidate_out_of_window(cand) |
| 817 | |
| 818 | # Newer matched_comment_date wins together with its paired matched_comment_url. |
| 819 | older = schema.SourceItem( |
| 820 | item_id="R-old", |
| 821 | source="reddit", |
| 822 | title="Old thread", |
| 823 | body="Old thread", |
| 824 | url=thread_url, |
| 825 | published_at="2024-01-01", |
| 826 | metadata={ |
| 827 | "matched_comment_date": "2026-11-10", |
| 828 | "matched_comment_url": "https://www.reddit.com/r/python/comments/abc123/old_thread/c_old/", |
| 829 | }, |
| 830 | ) |
| 831 | newer = schema.SourceItem( |
| 832 | item_id="R-new", |
| 833 | source="reddit", |
| 834 | title="Old thread", |
| 835 | body="Old thread", |
| 836 | url=thread_url, |
| 837 | published_at="2024-01-01", |
| 838 | metadata={ |
| 839 | "matched_comment_date": "2026-11-22", |
| 840 | "matched_comment_url": "https://www.reddit.com/r/python/comments/abc123/old_thread/c_new/", |
| 841 | }, |
| 842 | ) |
| 843 | merged_newer = fusion.merge_source_items(older, newer) |
| 844 | assert merged_newer.metadata["matched_comment_date"] == "2026-11-22" |
| 845 | assert merged_newer.metadata["matched_comment_url"] == ( |
| 846 | "https://www.reddit.com/r/python/comments/abc123/old_thread/c_new/" |
| 847 | ) |
| 848 | |
| 849 | # When a newer date has no URL, stale URL from the older reply is cleared (never mismatched). |
| 850 | newer_no_url = schema.SourceItem( |
| 851 | item_id="R-new-nourl", |
| 852 | source="reddit", |
| 853 | title="Old thread", |
| 854 | body="Old thread", |
| 855 | url=thread_url, |
| 856 | published_at="2024-01-01", |
| 857 | metadata={"matched_comment_date": "2026-11-24"}, |
| 858 | ) |
| 859 | merged_no_url = fusion.merge_source_items(merged_newer, newer_no_url) |
| 860 | assert merged_no_url.metadata["matched_comment_date"] == "2026-11-24" |
| 861 | assert "matched_comment_url" not in merged_no_url.metadata |
| 862 | |
| 863 | # Same date backfills a missing URL; an older incoming date never overwrites a newer one. |
| 864 | same_date_with_url = schema.SourceItem( |
| 865 | item_id="R-same", |
| 866 | source="reddit", |
| 867 | title="Old thread", |
| 868 | body="Old thread", |
| 869 | url=thread_url, |
| 870 | published_at="2024-01-01", |
| 871 | metadata={ |
| 872 | "matched_comment_date": "2026-11-24", |
| 873 | "matched_comment_url": "https://www.reddit.com/r/python/comments/abc123/old_thread/c_24/", |
| 874 | }, |
| 875 | ) |
| 876 | fusion.merge_source_items(merged_no_url, same_date_with_url) |
| 877 | assert merged_no_url.metadata["matched_comment_url"] == ( |
| 878 | "https://www.reddit.com/r/python/comments/abc123/old_thread/c_24/" |
| 879 | ) |
| 880 | stale_incoming = schema.SourceItem( |
| 881 | item_id="R-stale", |
| 882 | source="reddit", |
| 883 | title="Old thread", |
| 884 | body="Old thread", |
| 885 | url=thread_url, |
| 886 | published_at="2024-01-01", |
| 887 | metadata={ |
| 888 | "matched_comment_date": "2026-11-01", |
| 889 | "matched_comment_url": "https://www.reddit.com/r/python/comments/abc123/old_thread/c_01/", |
| 890 | }, |
| 891 | ) |
| 892 | fusion.merge_source_items(merged_no_url, stale_incoming) |
| 893 | assert merged_no_url.metadata["matched_comment_date"] == "2026-11-24" |
| 894 | assert merged_no_url.metadata["matched_comment_url"] == ( |
| 895 | "https://www.reddit.com/r/python/comments/abc123/old_thread/c_24/" |
| 896 | ) |
| 897 | |
| 898 | def test_as_of_window_blocks_post_cutoff_matched_comment_on_merge_and_normalize(self): |
| 899 | thread_url = "https://www.reddit.com/r/python/comments/asof99/release/" |
| 900 | url_in_window = "https://www.reddit.com/r/python/comments/asof99/release/c_feb20/" |
| 901 | url_post_cutoff = "https://www.reddit.com/r/python/comments/asof99/release/c_mar10/" |
| 902 | plan = _plan("python", ["reddit"]) |
| 903 | |
| 904 | def _make_copy(item_id: str, rel: float, m_date: str, m_url: str) -> schema.SourceItem: |
| 905 | return schema.SourceItem( |
| 906 | item_id=item_id, |
| 907 | source="reddit", |
| 908 | title="Python release notes", |
| 909 | body="Python release notes", |
| 910 | url=thread_url, |
| 911 | published_at="2026-02-10", |
| 912 | date_confidence="high", |
| 913 | local_relevance=rel, |
| 914 | freshness=80, |
| 915 | source_quality=0.6, |
| 916 | engagement={"score": 150, "num_comments": 25}, |
| 917 | metadata={ |
| 918 | "matched_comment_date": m_date, |
| 919 | "matched_comment_url": m_url, |
| 920 | }, |
| 921 | ) |
| 922 | |
| 923 | # Case 1a: Promoted higher-scoring copy carries post-cutoff reply (2026-03-10); |
| 924 | # fused candidate MUST keep the in-window reply (2026-02-20) and its URL. |
| 925 | copy_in = _make_copy("R-in", 0.4, "2026-02-20", url_in_window) |
| 926 | copy_post_high = _make_copy("R-post-hi", 0.95, "2026-03-10", url_post_cutoff) |
| 927 | [cand_promoted] = fusion.weighted_rrf( |
| 928 | {("primary", "reddit"): [copy_in], ("secondary", "reddit"): [copy_post_high]}, |
| 929 | plan, |
| 930 | pool_limit=10, |
| 931 | range_from="2026-02-01", |
| 932 | range_to="2026-03-01", |
| 933 | ) |
| 934 | assert cand_promoted.source_items[0].item_id == "R-post-hi" |
| 935 | assert cand_promoted.source_items[0].metadata["matched_comment_date"] == "2026-02-20" |
| 936 | assert cand_promoted.source_items[0].metadata["matched_comment_url"] == url_in_window |
| 937 | |
| 938 | # Case 1b: Non-promoted lower-scoring copy carries post-cutoff reply; |
| 939 | # fused candidate MUST keep the in-window reply and its URL. |
| 940 | copy_in_high = _make_copy("R-in-hi", 0.95, "2026-02-20", url_in_window) |
| 941 | copy_post_low = _make_copy("R-post-lo", 0.4, "2026-03-10", url_post_cutoff) |
| 942 | [cand_non_promoted] = fusion.weighted_rrf( |
| 943 | {("primary", "reddit"): [copy_in_high], ("secondary", "reddit"): [copy_post_low]}, |
| 944 | plan, |
| 945 | pool_limit=10, |
| 946 | range_from="2026-02-01", |
| 947 | range_to="2026-03-01", |
| 948 | ) |
| 949 | assert cand_non_promoted.source_items[0].metadata["matched_comment_date"] == "2026-02-20" |
| 950 | assert cand_non_promoted.source_items[0].metadata["matched_comment_url"] == url_in_window |
| 951 | |
| 952 | # Case 2: Reverse order — post-cutoff arrives first, in-window arrives second -> |
| 953 | # in-window pair replaces the out-of-window pair. |
| 954 | [cand_reverse] = fusion.weighted_rrf( |
| 955 | { |
| 956 | ("primary", "reddit"): [_make_copy("R-post-first", 0.9, "2026-03-10", url_post_cutoff)], |
| 957 | ("secondary", "reddit"): [_make_copy("R-in-second", 0.5, "2026-02-20", url_in_window)], |
| 958 | }, |
| 959 | plan, |
| 960 | pool_limit=10, |
| 961 | range_from="2026-02-01", |
| 962 | range_to="2026-03-01", |
| 963 | ) |
| 964 | assert cand_reverse.source_items[0].metadata["matched_comment_date"] == "2026-02-20" |
| 965 | assert cand_reverse.source_items[0].metadata["matched_comment_url"] == url_in_window |
| 966 | |
| 967 | # Case 2b: Single copy carrying ONLY a post-cutoff reply has both fields stripped. |
| 968 | [cand_only_post] = fusion.weighted_rrf( |
| 969 | {("primary", "reddit"): [_make_copy("R-only-post", 0.8, "2026-03-10", url_post_cutoff)]}, |
| 970 | plan, |
| 971 | pool_limit=10, |
| 972 | range_from="2026-02-01", |
| 973 | range_to="2026-03-01", |
| 974 | ) |
| 975 | assert "matched_comment_date" not in cand_only_post.source_items[0].metadata |
| 976 | assert "matched_comment_url" not in cand_only_post.source_items[0].metadata |
| 977 | |
| 978 | # Case 3: _normalize_reddit drops post-cutoff and pre-window matched_comment metadata |
| 979 | # while keeping in-window matched_comment metadata. |
| 980 | raw_items = [ |
| 981 | { |
| 982 | "id": "R-norm-in", |
| 983 | "title": "In-window thread with in-window reply", |
| 984 | "url": thread_url, |
| 985 | "subreddit": "python", |
| 986 | "date": "2026-02-10", |
| 987 | "matched_comment": {"date": "2026-02-20", "url": url_in_window}, |
| 988 | }, |
| 989 | { |
| 990 | "id": "R-norm-post", |
| 991 | "title": "In-window thread with post-cutoff reply", |
| 992 | "url": "https://www.reddit.com/r/python/comments/asof98/release/", |
| 993 | "subreddit": "python", |
| 994 | "date": "2026-02-10", |
| 995 | "matched_comment": {"date": "2026-03-10", "url": url_post_cutoff}, |
| 996 | }, |
| 997 | { |
| 998 | "id": "R-norm-pre", |
| 999 | "title": "In-window thread with pre-window reply", |
| 1000 | "url": "https://www.reddit.com/r/python/comments/asof97/release/", |
| 1001 | "subreddit": "python", |
| 1002 | "date": "2026-02-10", |
| 1003 | "matched_comment": { |
| 1004 | "date": "2026-01-15", |
| 1005 | "url": "https://www.reddit.com/r/python/comments/asof97/release/c_jan15/", |
| 1006 | }, |
| 1007 | }, |
| 1008 | ] |
| 1009 | normalized = normalize.normalize_source_items( |
| 1010 | "reddit", raw_items, "2026-02-01", "2026-03-01", |
| 1011 | ) |
| 1012 | by_id = {si.item_id: si for si in normalized} |
| 1013 | assert by_id["R-norm-in"].metadata["matched_comment_date"] == "2026-02-20" |
| 1014 | assert by_id["R-norm-in"].metadata["matched_comment_url"] == url_in_window |
| 1015 | assert "matched_comment_date" not in by_id["R-norm-post"].metadata |
| 1016 | assert "matched_comment_url" not in by_id["R-norm-post"].metadata |
| 1017 | assert "matched_comment_date" not in by_id["R-norm-pre"].metadata |
| 1018 | assert "matched_comment_url" not in by_id["R-norm-pre"].metadata |
| 1019 | |
| 1020 | |
| 1021 | # --------------------------------------------------------------------------- |
| 1022 | # HIGH-106: Recompute engagement_score, longer enrichment strings, no input mutation |
| 1023 | # --------------------------------------------------------------------------- |
| 1024 | |
| 1025 | |
| 1026 | class TestHigh106MergeAndImmutability: |
| 1027 | def test_arctic_pending_to_live_merge_recomputes_engagement_score(self): |
| 1028 | url = "https://www.reddit.com/r/python/comments/abc123/test/" |
| 1029 | pending = schema.SourceItem( |
| 1030 | item_id="R1", |
| 1031 | source="reddit", |
| 1032 | title="Python 3.15 released", |
| 1033 | body="Python 3.15 released", |
| 1034 | url=url, |
| 1035 | published_at="2026-10-25", |
| 1036 | date_confidence="high", |
| 1037 | engagement={"score": None, "num_comments": 0}, |
| 1038 | metadata={"engagement_source": reddit_refs.ARCTIC_PENDING}, |
| 1039 | engagement_score=None, |
| 1040 | ) |
| 1041 | live = schema.SourceItem( |
| 1042 | item_id="R2", |
| 1043 | source="reddit", |
| 1044 | title="Python 3.15 released", |
| 1045 | body="Python 3.15 released", |
| 1046 | url=url, |
| 1047 | published_at="2026-10-25", |
| 1048 | date_confidence="high", |
| 1049 | engagement={"score": 500, "num_comments": 40}, |
| 1050 | metadata={"engagement_source": reddit_refs.LIVE}, |
| 1051 | engagement_score=None, |
| 1052 | ) |
| 1053 | merged = fusion.merge_source_items(pending, live) |
| 1054 | expected = signals.engagement_score(merged) |
| 1055 | assert expected is not None and expected > 40 |
| 1056 | assert merged.engagement["score"] == 500 |
| 1057 | assert merged.metadata["engagement_source"] == reddit_refs.LIVE |
| 1058 | assert merged.engagement_score == expected |
| 1059 | |
| 1060 | # Verify downstream rerank credits the live score instead of treating it as 0. |
| 1061 | cand = schema.Candidate( |
| 1062 | candidate_id=url, item_id="R1", source="reddit", title=merged.title, url=url, |
| 1063 | snippet="", subquery_labels=["primary"], native_ranks={"primary:reddit": 1}, |
| 1064 | local_relevance=0.8, freshness=80, engagement=merged.engagement_score, |
| 1065 | source_quality=0.6, rrf_score=0.02, sources=["reddit"], source_items=[merged], |
| 1066 | rerank_score=60.0, |
| 1067 | ) |
| 1068 | zero_cand = schema.Candidate( |
| 1069 | candidate_id=url + "z", item_id="R0", source="reddit", title=merged.title, url=url, |
| 1070 | snippet="", subquery_labels=["primary"], native_ranks={"primary:reddit": 1}, |
| 1071 | local_relevance=0.8, freshness=80, engagement=0, |
| 1072 | source_quality=0.6, rrf_score=0.02, sources=["reddit"], source_items=[merged], |
| 1073 | rerank_score=60.0, |
| 1074 | ) |
| 1075 | assert not rerank._engagement_pending(cand) |
| 1076 | assert rerank._final_score(cand) > rerank._final_score(zero_cand) + 5.0 |
| 1077 | |
| 1078 | def test_merge_replaces_shorter_string_enrichment_stubs_and_ignores_whitespace(self): |
| 1079 | a = schema.SourceItem( |
| 1080 | item_id="YT1", source="youtube", title="Demo", body="Demo", |
| 1081 | url="https://youtube.com/watch?v=1", |
| 1082 | metadata={"transcript_snippet": "short stub", "transcript": " "}, |
| 1083 | ) |
| 1084 | b = schema.SourceItem( |
| 1085 | item_id="YT2", source="youtube", title="Demo", body="Demo", |
| 1086 | url="https://youtube.com/watch?v=1", |
| 1087 | metadata={ |
| 1088 | "transcript_snippet": "full detailed transcript snippet covering Hermes Agent", |
| 1089 | "transcript": "complete transcript text", |
| 1090 | }, |
| 1091 | ) |
| 1092 | merged = fusion.merge_source_items(a, b) |
| 1093 | assert merged.metadata["transcript_snippet"] == "full detailed transcript snippet covering Hermes Agent" |
| 1094 | assert merged.metadata["transcript"] == "complete transcript text" |
| 1095 | |
| 1096 | # A shorter stub or whitespace-only copy must not overwrite the richer transcript. |
| 1097 | c = schema.SourceItem( |
| 1098 | item_id="YT3", source="youtube", title="Demo", body="Demo", |
| 1099 | url="https://youtube.com/watch?v=1", |
| 1100 | metadata={"transcript_snippet": "tiny", "transcript": " " * 200}, |
| 1101 | ) |
| 1102 | fusion.merge_source_items(merged, c) |
| 1103 | assert merged.metadata["transcript_snippet"] == "full detailed transcript snippet covering Hermes Agent" |
| 1104 | assert merged.metadata["transcript"] == "complete transcript text" |
| 1105 | |
| 1106 | def test_weighted_rrf_does_not_mutate_caller_source_items_and_syncs_live_engagement(self): |
| 1107 | url = "https://www.reddit.com/r/ghostty/comments/xyz789/release/" |
| 1108 | pending = schema.SourceItem( |
| 1109 | item_id="R1", source="reddit", title="Ghostty release", body="Ghostty release", |
| 1110 | url=url, published_at="2026-10-25", date_confidence="high", |
| 1111 | engagement={"score": None, "num_comments": 0}, |
| 1112 | metadata={"engagement_source": reddit_refs.ARCTIC_PENDING}, |
| 1113 | local_relevance=0.8, freshness=80, source_quality=0.6, engagement_score=None, |
| 1114 | ) |
| 1115 | live = schema.SourceItem( |
| 1116 | item_id="R2", source="reddit", title="Ghostty release", body="Ghostty release", |
| 1117 | url=url, published_at="2026-10-25", date_confidence="high", |
| 1118 | engagement={"score": 412, "num_comments": 25}, |
| 1119 | metadata={"engagement_source": reddit_refs.LIVE}, |
| 1120 | local_relevance=0.7, freshness=80, source_quality=0.6, engagement_score=None, |
| 1121 | ) |
| 1122 | stale_archive = schema.SourceItem( |
| 1123 | item_id="R3", source="reddit", title="Ghostty release", body="Ghostty release", |
| 1124 | url=url, published_at="2026-10-25", date_confidence="high", |
| 1125 | engagement={"score": 9000, "num_comments": 25}, |
| 1126 | metadata={"engagement_source": reddit_refs.ARCTIC}, |
| 1127 | local_relevance=0.6, freshness=80, source_quality=0.6, engagement_score=95, |
| 1128 | ) |
| 1129 | plan = schema.QueryPlan( |
| 1130 | intent="breaking_news", freshness_mode="strict_recent", cluster_mode="story", |
| 1131 | raw_topic="ghostty", |
| 1132 | subqueries=[ |
| 1133 | schema.SubQuery(label=lbl, search_query="ghostty", ranking_query="ghostty", |
| 1134 | sources=["reddit"], weight=1.0) |
| 1135 | for lbl in ("q1", "q2", "q3") |
| 1136 | ], |
| 1137 | source_weights={"reddit": 1.0}, |
| 1138 | ) |
| 1139 | streams = { |
| 1140 | ("q1", "reddit"): [pending], |
| 1141 | ("q2", "reddit"): [live], |
| 1142 | ("q3", "reddit"): [stale_archive], |
| 1143 | } |
| 1144 | [cand] = fusion.weighted_rrf(streams, plan, pool_limit=10) |
| 1145 | # Caller's input SourceItem was NOT mutated in place. |
| 1146 | assert pending.engagement == {"score": None, "num_comments": 0} |
| 1147 | assert pending.metadata["engagement_source"] == reddit_refs.ARCTIC_PENDING |
| 1148 | assert pending.engagement_score is None |
| 1149 | # Candidate's merged item upgraded pending -> live and rejected stale archive's 9000. |
| 1150 | [merged_item] = cand.source_items |
| 1151 | assert merged_item.engagement["score"] == 412 |
| 1152 | assert merged_item.metadata["engagement_source"] == reddit_refs.LIVE |
| 1153 | expected_live_score = signals.engagement_score(merged_item) |
| 1154 | assert merged_item.engagement_score == expected_live_score |
| 1155 | assert cand.engagement == expected_live_score |
| 1156 | |
| 1157 | |
| 1158 | # --------------------------------------------------------------------------- |
| 1159 | # HIGH-107: Grounding Reddit enrichment attribution, dates, safe metadata & normalize |
| 1160 | # --------------------------------------------------------------------------- |
| 1161 | |
| 1162 | |
| 1163 | class TestHigh107GroundingRedditCommentsAndDates: |
| 1164 | def test_enrich_reddit_items_preserves_attribution_dates_and_handles_missing_metadata(self): |
| 1165 | hydrated = reddit_hydrate.Hydration( |
| 1166 | items=[ |
| 1167 | # Malformed hydrated rows without metadata/post_id must not raise KeyError. |
| 1168 | {"engagement_source": reddit_refs.ARCTIC}, |
| 1169 | {"engagement_source": reddit_refs.ARCTIC, "metadata": None}, |
| 1170 | {"engagement_source": reddit_refs.ARCTIC, "metadata": {}}, |
| 1171 | { |
| 1172 | "engagement_source": reddit_refs.ARCTIC, |
| 1173 | "metadata": {"post_id": "abc123"}, |
| 1174 | "date": "2026-10-18", |
| 1175 | "selftext": "Full Reddit post body about Hermes Agent.", |
| 1176 | "top_comments": [ |
| 1177 | { |
| 1178 | "id": "c1", |
| 1179 | "score": 142, |
| 1180 | "author": "alice", |
| 1181 | "date": "2026-10-19", |
| 1182 | "url": "https://reddit.com/r/python/comments/abc123/test/c1/", |
| 1183 | "is_uploader": False, |
| 1184 | "body": "Hermes Agent works great in production!", |
| 1185 | "depth": 0, |
| 1186 | }, |
| 1187 | { |
| 1188 | "id": "c2", |
| 1189 | "score": 50, |
| 1190 | "author": "op_user", |
| 1191 | "date": "2026-10-19", |
| 1192 | "permalink": "/r/python/comments/abc123/test/c2/", |
| 1193 | "is_uploader": True, |
| 1194 | "excerpt": "Thanks everyone, OP here.", |
| 1195 | "depth": 1, |
| 1196 | }, |
| 1197 | { |
| 1198 | "id": "c3", |
| 1199 | "score": 38, |
| 1200 | "author": "bob", |
| 1201 | "date": "2026-10-19", |
| 1202 | "url": "https://reddit.com/r/python/comments/abc123/test/c3/", |
| 1203 | "is_uploader": False, |
| 1204 | "body": "Second community reaction on Hermes Agent latency.", |
| 1205 | "depth": 0, |
| 1206 | }, |
| 1207 | ], |
| 1208 | }, |
| 1209 | { |
| 1210 | "engagement_source": reddit_refs.ARCTIC, |
| 1211 | "metadata": {"post_id": "old999"}, |
| 1212 | "date": "2022-03-01", |
| 1213 | "selftext": "Ancient 2022 thread.", |
| 1214 | "top_comments": [], |
| 1215 | }, |
| 1216 | ], |
| 1217 | detail="arctic served 2", |
| 1218 | arctic_state="ok", |
| 1219 | ) |
| 1220 | raw_items = [ |
| 1221 | { |
| 1222 | "id": "W1", |
| 1223 | "title": "Undated in-window Reddit thread", |
| 1224 | "url": "https://www.reddit.com/r/python/comments/abc123/test/", |
| 1225 | "snippet": "search snippet", |
| 1226 | "date": None, |
| 1227 | "metadata": {"date_window_basis": "server_bounds"}, |
| 1228 | }, |
| 1229 | { |
| 1230 | "id": "W2", |
| 1231 | "title": "Undated ancient Reddit thread", |
| 1232 | "url": "https://www.reddit.com/r/python/comments/old999/old/", |
| 1233 | "snippet": "ancient snippet", |
| 1234 | "date": None, |
| 1235 | "metadata": {"date_window_basis": "keyless_current"}, |
| 1236 | }, |
| 1237 | ] |
| 1238 | with patch.object(reddit_hydrate, "hydrate", return_value=hydrated): |
| 1239 | enriched = grounding._enrich_reddit_items(raw_items) |
| 1240 | |
| 1241 | assert enriched[0]["date"] == "2026-10-18" |
| 1242 | assert enriched[0]["enriched_via"] == "arctic" |
| 1243 | assert len(enriched[0]["top_comments"]) == 3 |
| 1244 | c1, c2, c3 = enriched[0]["top_comments"] |
| 1245 | assert c1 == { |
| 1246 | "id": "c1", |
| 1247 | "score": 142, |
| 1248 | "author": "alice", |
| 1249 | "date": "2026-10-19", |
| 1250 | "url": "https://reddit.com/r/python/comments/abc123/test/c1/", |
| 1251 | "is_uploader": False, |
| 1252 | "excerpt": "Hermes Agent works great in production!", |
| 1253 | "depth": 0, |
| 1254 | } |
| 1255 | assert c2["id"] == "c2" |
| 1256 | assert c2["author"] == "op_user" |
| 1257 | assert c2["is_uploader"] is True |
| 1258 | assert c2["url"] == "https://reddit.com/r/python/comments/abc123/test/c2/" |
| 1259 | assert c3["author"] == "bob" |
| 1260 | assert c3["is_uploader"] is False |
| 1261 | assert enriched[1]["date"] == "2022-03-01" |
| 1262 | |
| 1263 | # Normalize through grounding: ancient backfilled thread is dropped, |
| 1264 | # in-window thread keeps top_comments, enriched_via, body text, and copies metadata. |
| 1265 | orig_meta = enriched[0]["metadata"] |
| 1266 | normalized = normalize.normalize_source_items( |
| 1267 | "grounding", enriched, "2026-10-01", "2026-10-31" |
| 1268 | ) |
| 1269 | assert len(normalized) == 1 |
| 1270 | si = normalized[0] |
| 1271 | assert si.published_at == "2026-10-18" |
| 1272 | assert si.metadata["enriched_via"] == "arctic" |
| 1273 | assert si.metadata["date_window_basis"] == "server_bounds" |
| 1274 | assert len(si.metadata["top_comments"]) == 3 |
| 1275 | assert si.metadata["top_comments"][0]["author"] == "alice" |
| 1276 | assert si.metadata["top_comments"][0]["is_uploader"] is False |
| 1277 | assert si.metadata["top_comments"][1]["is_uploader"] is True |
| 1278 | assert "Hermes Agent works great in production!" in si.body |
| 1279 | # Metadata was copied (no shared reference mutation). |
| 1280 | assert si.metadata is not orig_meta |
| 1281 | si.metadata["extra"] = "mutated" |
| 1282 | assert "extra" not in orig_meta |
| 1283 | |
| 1284 | # End-to-end render quote check: OP comment (is_uploader=True) is skipped, |
| 1285 | # while community comments by alice and bob surface with full attribution! |
| 1286 | report = schema.Report( |
| 1287 | topic="Hermes Agent", |
| 1288 | range_from="2026-10-01", |
| 1289 | range_to="2026-10-31", |
| 1290 | generated_at="2026-10-31T00:00:00Z", |
| 1291 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1292 | query_plan=_plan("Hermes Agent", ["grounding"]), |
| 1293 | clusters=[], |
| 1294 | ranked_candidates=[ |
| 1295 | schema.Candidate( |
| 1296 | candidate_id=si.url, item_id=si.item_id, source="grounding", |
| 1297 | title=si.title, url=si.url, snippet=si.snippet, |
| 1298 | subquery_labels=["primary"], native_ranks={"primary:grounding": 1}, |
| 1299 | local_relevance=0.8, freshness=80, engagement=None, |
| 1300 | source_quality=1.0, rrf_score=0.02, sources=["grounding"], |
| 1301 | source_items=[si], final_score=60.0, |
| 1302 | ) |
| 1303 | ], |
| 1304 | items_by_source={"grounding": [si]}, |
| 1305 | errors_by_source={}, |
| 1306 | ) |
| 1307 | lines = render._render_top_comments(report, limit=5) |
| 1308 | assert any("Hermes Agent works great in production!" in ln and "alice" in ln for ln in lines) |
| 1309 | assert any("Second community reaction on Hermes Agent latency." in ln and "bob" in ln for ln in lines) |
| 1310 | assert not any("op_user" in ln or "OP here" in ln for ln in lines) |
| 1311 | |
| 1312 | def test_enrich_reddit_items_preserves_existing_item_date(self): |
| 1313 | hydrated = reddit_hydrate.Hydration( |
| 1314 | items=[{ |
| 1315 | "engagement_source": reddit_refs.ARCTIC, |
| 1316 | "metadata": {"post_id": "abc123"}, |
| 1317 | "date": "2026-10-18", |
| 1318 | "selftext": "body", |
| 1319 | "top_comments": [], |
| 1320 | }], |
| 1321 | detail="arctic served 1", |
| 1322 | arctic_state="ok", |
| 1323 | ) |
| 1324 | items = [{ |
| 1325 | "url": "https://www.reddit.com/r/python/comments/abc123/test/", |
| 1326 | "date": "2026-10-19", |
| 1327 | "snippet": "orig", |
| 1328 | }] |
| 1329 | with patch.object(reddit_hydrate, "hydrate", return_value=hydrated): |
| 1330 | out = grounding._enrich_reddit_items(items) |
| 1331 | assert out[0]["date"] == "2026-10-19" |
| 1332 | |
| 1333 | def test_arctic_web_reddit_comments_enforce_reddit_topic_and_vote_floors(self): |
| 1334 | hydrated = reddit_hydrate.Hydration( |
| 1335 | items=[ |
| 1336 | { |
| 1337 | "engagement_source": reddit_refs.ARCTIC, |
| 1338 | "metadata": {"post_id": "small1"}, |
| 1339 | "date": "2026-10-20", |
| 1340 | "selftext": "Small Hermes Agent thread body", |
| 1341 | "engagement": {"score": 40, "num_comments": 10}, |
| 1342 | "top_comments": [ |
| 1343 | { |
| 1344 | "id": "offtopic_nested", |
| 1345 | "score": 50, |
| 1346 | "author": "tangent", |
| 1347 | "date": "2026-10-20", |
| 1348 | "permalink": "https://www.reddit.com/r/python/comments/small1/t/offtopic_nested/", |
| 1349 | "is_uploader": False, |
| 1350 | "body": "Totally unrelated lunch recipe with great sourdough crust.", |
| 1351 | "depth": 1, |
| 1352 | }, |
| 1353 | { |
| 1354 | "id": "good1", |
| 1355 | "score": 3, |
| 1356 | "author": "alice", |
| 1357 | "date": "2026-10-20", |
| 1358 | "permalink": "https://www.reddit.com/r/python/comments/small1/t/good1/", |
| 1359 | "is_uploader": False, |
| 1360 | "body": "Hermes Agent works reliably on small workflows.", |
| 1361 | "depth": 0, |
| 1362 | }, |
| 1363 | { |
| 1364 | "id": "zero_vote", |
| 1365 | "score": 0, |
| 1366 | "author": "zero_user", |
| 1367 | "date": "2026-10-20", |
| 1368 | "permalink": "/r/python/comments/small1/t/zero_vote/", |
| 1369 | "is_uploader": False, |
| 1370 | "body": "Hermes Agent zero-vote comment should be filtered out.", |
| 1371 | "depth": 0, |
| 1372 | }, |
| 1373 | { |
| 1374 | # Non-string body must not raise TypeError during enrichment. |
| 1375 | "id": "non_str", |
| 1376 | "score": 1, |
| 1377 | "author": "num_user", |
| 1378 | "body": 12345, |
| 1379 | "depth": 0, |
| 1380 | }, |
| 1381 | ], |
| 1382 | }, |
| 1383 | { |
| 1384 | "engagement_source": reddit_refs.ARCTIC, |
| 1385 | "metadata": {"post_id": "small3"}, |
| 1386 | "date": "2026-10-20", |
| 1387 | "selftext": "Second small Hermes Agent thread", |
| 1388 | "engagement": {"score": 20, "num_comments": 4}, |
| 1389 | "top_comments": [ |
| 1390 | { |
| 1391 | "id": "good2", |
| 1392 | "score": 2, |
| 1393 | "author": "bob", |
| 1394 | "date": "2026-10-20", |
| 1395 | "permalink": "/r/python/comments/small3/t/good2/", |
| 1396 | "is_uploader": False, |
| 1397 | "body": "Second reply on Hermes Agent memory behavior.", |
| 1398 | "depth": 0, |
| 1399 | }, |
| 1400 | ], |
| 1401 | }, |
| 1402 | { |
| 1403 | "engagement_source": reddit_refs.ARCTIC, |
| 1404 | "metadata": {"post_id": "big2"}, |
| 1405 | "date": "2026-10-20", |
| 1406 | "selftext": "Big Hermes Agent thread body", |
| 1407 | "engagement": {"score": 200, "num_comments": 50}, |
| 1408 | "top_comments": [ |
| 1409 | { |
| 1410 | "id": "under_floor", |
| 1411 | "score": 3, |
| 1412 | "author": "carol", |
| 1413 | "date": "2026-10-20", |
| 1414 | "permalink": "/r/python/comments/big2/t/under_floor/", |
| 1415 | "is_uploader": False, |
| 1416 | "body": "Hermes Agent comment below 5-vote floor for large thread.", |
| 1417 | "depth": 0, |
| 1418 | }, |
| 1419 | ], |
| 1420 | }, |
| 1421 | ], |
| 1422 | detail="arctic served 3", |
| 1423 | arctic_state="ok", |
| 1424 | ) |
| 1425 | raw_items = [ |
| 1426 | { |
| 1427 | "id": "W1", |
| 1428 | "title": "Hermes Agent small thread", |
| 1429 | "url": "https://www.reddit.com/r/python/comments/small1/t/", |
| 1430 | "snippet": "search snippet", |
| 1431 | "date": None, |
| 1432 | "metadata": {"date_window_basis": "server_bounds"}, |
| 1433 | }, |
| 1434 | { |
| 1435 | "id": "W2", |
| 1436 | "title": "Hermes Agent second small thread", |
| 1437 | "url": "https://www.reddit.com/r/python/comments/small3/t/", |
| 1438 | "snippet": "search snippet", |
| 1439 | "date": None, |
| 1440 | "metadata": {"date_window_basis": "server_bounds"}, |
| 1441 | }, |
| 1442 | { |
| 1443 | "id": "W3", |
| 1444 | "title": "Hermes Agent big thread", |
| 1445 | "url": "https://www.reddit.com/r/python/comments/big2/t/", |
| 1446 | "snippet": "search snippet", |
| 1447 | "date": None, |
| 1448 | "metadata": {"date_window_basis": "server_bounds"}, |
| 1449 | }, |
| 1450 | ] |
| 1451 | with patch.object(reddit_hydrate, "hydrate", return_value=hydrated): |
| 1452 | enriched = grounding._enrich_reddit_items(raw_items) |
| 1453 | |
| 1454 | assert enriched[0]["reddit_thread_score"] == 40 |
| 1455 | assert "engagement" not in enriched[0] |
| 1456 | assert enriched[0]["top_comments"][0]["url"] == ( |
| 1457 | "https://www.reddit.com/r/python/comments/small1/t/offtopic_nested/" |
| 1458 | ) |
| 1459 | assert enriched[0]["top_comments"][3]["excerpt"] == "12345" |
| 1460 | |
| 1461 | normalized = normalize.normalize_source_items( |
| 1462 | "grounding", enriched, "2026-10-01", "2026-10-31" |
| 1463 | ) |
| 1464 | assert len(normalized) == 3 |
| 1465 | small_si, small3_si, big_si = normalized |
| 1466 | assert small_si.source == "grounding" |
| 1467 | assert small_si.metadata["reddit_thread_score"] == 40 |
| 1468 | assert big_si.metadata["reddit_thread_score"] == 200 |
| 1469 | assert render._quote_pool_item_floor(small_si) == 2 |
| 1470 | assert render._quote_pool_item_floor(small3_si) == 2 |
| 1471 | assert render._quote_pool_item_floor(big_si) == 5 |
| 1472 | |
| 1473 | report = schema.Report( |
| 1474 | topic="Hermes Agent", |
| 1475 | range_from="2026-10-01", |
| 1476 | range_to="2026-10-31", |
| 1477 | generated_at="2026-10-31T00:00:00Z", |
| 1478 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1479 | query_plan=_plan("Hermes Agent", ["grounding"]), |
| 1480 | clusters=[], |
| 1481 | ranked_candidates=[ |
| 1482 | schema.Candidate( |
| 1483 | candidate_id=si.url, item_id=si.item_id, source="grounding", |
| 1484 | title=si.title, url=si.url, snippet=si.snippet, |
| 1485 | subquery_labels=["primary"], native_ranks={"primary:grounding": idx}, |
| 1486 | local_relevance=0.8, freshness=80, engagement=None, |
| 1487 | source_quality=1.0, rrf_score=0.02, sources=["grounding"], |
| 1488 | source_items=[si], final_score=60.0 - idx, |
| 1489 | ) |
| 1490 | for idx, si in enumerate(normalized, start=1) |
| 1491 | ], |
| 1492 | items_by_source={"grounding": normalized}, |
| 1493 | errors_by_source={}, |
| 1494 | ) |
| 1495 | lines = render._render_top_comments(report, limit=10) |
| 1496 | joined = "\n".join(lines) |
| 1497 | # Nested off-topic reply, 0-vote comment, and big-thread under-floor comment are excluded. |
| 1498 | assert "sourdough crust" not in joined |
| 1499 | assert "zero-vote comment" not in joined |
| 1500 | assert "below 5-vote floor" not in joined |
| 1501 | # Valid top-level comments on the small threads clear the scaled floor (2) and use 'upvotes'. |
| 1502 | assert any( |
| 1503 | "Hermes Agent works reliably on small workflows." in ln |
| 1504 | and "🟠 u/alice on r/python · 3 upvotes" in ln |
| 1505 | for ln in lines |
| 1506 | ) |
| 1507 | assert any( |
| 1508 | "Second reply on Hermes Agent memory behavior." in ln |
| 1509 | and "🟠 u/bob on r/python · 2 upvotes" in ln |
| 1510 | for ln in lines |
| 1511 | ) |
| 1512 | |
| 1513 | def test_fused_unenriched_and_arctic_web_copies_keep_reddit_quote_checks_and_byline(self): |
| 1514 | short_url = "https://redd.it/fus123" |
| 1515 | bare_web = schema.SourceItem( |
| 1516 | item_id="W1", |
| 1517 | source="grounding", |
| 1518 | title="Hermes Agent on redd.it", |
| 1519 | body="Hermes Agent on redd.it", |
| 1520 | url=short_url, |
| 1521 | published_at="2026-10-20", |
| 1522 | date_confidence="high", |
| 1523 | metadata={"date_window_basis": "server_bounds"}, |
| 1524 | ) |
| 1525 | arctic_web = schema.SourceItem( |
| 1526 | item_id="W2", |
| 1527 | source="grounding", |
| 1528 | title="Hermes Agent on redd.it", |
| 1529 | body="Hermes Agent on redd.it", |
| 1530 | url=short_url, |
| 1531 | published_at="2026-10-20", |
| 1532 | date_confidence="high", |
| 1533 | metadata={ |
| 1534 | "enriched_via": "arctic", |
| 1535 | "reddit_thread_score": 40, |
| 1536 | "reddit_subreddit": "LocalLLaMA", |
| 1537 | "top_comments": [ |
| 1538 | { |
| 1539 | "id": "off1", |
| 1540 | "score": 90, |
| 1541 | "author": "tangent", |
| 1542 | "excerpt": "Completely unrelated baking recipe talk.", |
| 1543 | "depth": 1, |
| 1544 | }, |
| 1545 | { |
| 1546 | "id": "ok1", |
| 1547 | "score": 3, |
| 1548 | "author": "alice", |
| 1549 | "excerpt": "Hermes Agent runs smoothly on local hardware.", |
| 1550 | "depth": 0, |
| 1551 | }, |
| 1552 | { |
| 1553 | "id": "zero1", |
| 1554 | "score": 0, |
| 1555 | "author": "nobody", |
| 1556 | "excerpt": "Hermes Agent zero-vote reply must be dropped.", |
| 1557 | "depth": 0, |
| 1558 | }, |
| 1559 | ], |
| 1560 | }, |
| 1561 | ) |
| 1562 | merged = fusion.merge_source_items(bare_web, arctic_web) |
| 1563 | assert merged.source == "grounding" |
| 1564 | assert merged.metadata["enriched_via"] == "arctic" |
| 1565 | assert merged.metadata["reddit_thread_score"] == 40 |
| 1566 | assert merged.metadata["reddit_subreddit"] == "LocalLLaMA" |
| 1567 | |
| 1568 | # A Reddit URL web item WITHOUT enriched_via still triggers Reddit quote checks + fallback byline. |
| 1569 | untagged_reddit_web = schema.SourceItem( |
| 1570 | item_id="W3", |
| 1571 | source="grounding", |
| 1572 | title="Hermes Agent short link", |
| 1573 | body="Hermes Agent short link", |
| 1574 | url="https://redd.it/untag9", |
| 1575 | published_at="2026-10-20", |
| 1576 | date_confidence="high", |
| 1577 | metadata={ |
| 1578 | "top_comments": [ |
| 1579 | { |
| 1580 | "id": "off2", |
| 1581 | "score": 70, |
| 1582 | "author": "offuser", |
| 1583 | "excerpt": "Unrelated movie review nested reply.", |
| 1584 | "depth": 1, |
| 1585 | }, |
| 1586 | { |
| 1587 | "id": "ok2", |
| 1588 | "score": 12, |
| 1589 | "author": "bob", |
| 1590 | "excerpt": "Hermes Agent handles tool calls cleanly.", |
| 1591 | "depth": 0, |
| 1592 | }, |
| 1593 | ], |
| 1594 | }, |
| 1595 | ) |
| 1596 | assert render._comment_source(untagged_reddit_web) == "reddit" |
| 1597 | |
| 1598 | report = schema.Report( |
| 1599 | topic="Hermes Agent", |
| 1600 | range_from="2026-10-01", |
| 1601 | range_to="2026-10-31", |
| 1602 | generated_at="2026-10-31T00:00:00Z", |
| 1603 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1604 | query_plan=_plan("Hermes Agent", ["grounding"]), |
| 1605 | clusters=[], |
| 1606 | ranked_candidates=[ |
| 1607 | schema.Candidate( |
| 1608 | candidate_id=si.url, item_id=si.item_id, source="grounding", |
| 1609 | title=si.title, url=si.url, snippet=si.snippet, |
| 1610 | subquery_labels=["primary"], native_ranks={"primary:grounding": idx}, |
| 1611 | local_relevance=0.8, freshness=80, engagement=None, |
| 1612 | source_quality=1.0, rrf_score=0.02, sources=["grounding"], |
| 1613 | source_items=[si], final_score=60.0 - idx, |
| 1614 | ) |
| 1615 | for idx, si in enumerate([merged, untagged_reddit_web], start=1) |
| 1616 | ], |
| 1617 | items_by_source={"grounding": [merged, untagged_reddit_web]}, |
| 1618 | errors_by_source={}, |
| 1619 | ) |
| 1620 | lines = render._render_top_comments(report, limit=10) |
| 1621 | joined = "\n".join(lines) |
| 1622 | assert "baking recipe" not in joined |
| 1623 | assert "zero-vote reply" not in joined |
| 1624 | assert "movie review" not in joined |
| 1625 | assert any( |
| 1626 | "Hermes Agent runs smoothly on local hardware." in ln |
| 1627 | and "🟠 u/alice on r/LocalLLaMA · 3 upvotes" in ln |
| 1628 | for ln in lines |
| 1629 | ) |
| 1630 | assert any( |
| 1631 | "Hermes Agent handles tool calls cleanly." in ln |
| 1632 | and "🟠 u/bob on Reddit · 12 upvotes" in ln |
| 1633 | for ln in lines |
| 1634 | ) |
| 1635 | |
| 1636 | def test_same_reddit_thread_capped_at_two_quotes_across_native_and_web_copies(self): |
| 1637 | thread_url = "https://www.reddit.com/r/python/comments/cap123/hermes_agent/" |
| 1638 | native_reddit = schema.SourceItem( |
| 1639 | item_id="R1", |
| 1640 | source="reddit", |
| 1641 | title="Hermes Agent release thread", |
| 1642 | body="Hermes Agent release thread", |
| 1643 | url=thread_url, |
| 1644 | container="python", |
| 1645 | published_at="2026-10-20", |
| 1646 | date_confidence="high", |
| 1647 | engagement={"score": 200, "num_comments": 40}, |
| 1648 | metadata={ |
| 1649 | "top_comments": [ |
| 1650 | {"id": "n1", "score": 80, "author": "native_one", "excerpt": "Native top comment about Hermes Agent speed.", "depth": 0}, |
| 1651 | {"id": "n2", "score": 45, "author": "native_two", "excerpt": "Native second comment about Hermes Agent setup.", "depth": 0}, |
| 1652 | ] |
| 1653 | }, |
| 1654 | ) |
| 1655 | web_reddit = schema.SourceItem( |
| 1656 | item_id="W1", |
| 1657 | source="grounding", |
| 1658 | title="Hermes Agent release thread", |
| 1659 | body="Hermes Agent release thread", |
| 1660 | url=thread_url, |
| 1661 | published_at="2026-10-20", |
| 1662 | date_confidence="high", |
| 1663 | metadata={ |
| 1664 | "enriched_via": "arctic", |
| 1665 | "reddit_thread_score": 200, |
| 1666 | "reddit_subreddit": "python", |
| 1667 | "top_comments": [ |
| 1668 | {"id": "w1", "score": 70, "author": "web_one", "excerpt": "Web Arctic comment one on Hermes Agent.", "depth": 0}, |
| 1669 | {"id": "w2", "score": 35, "author": "web_two", "excerpt": "Web Arctic comment two on Hermes Agent.", "depth": 0}, |
| 1670 | ], |
| 1671 | }, |
| 1672 | ) |
| 1673 | |
| 1674 | # Case 1: Both items fused into the same candidate -> merged comments sort by votes |
| 1675 | # (80, 70, 45, 35), so the top 2 highest-voted win and total is capped at 2. |
| 1676 | fused_cand = schema.Candidate( |
| 1677 | candidate_id=thread_url, |
| 1678 | item_id="R1", |
| 1679 | source="reddit", |
| 1680 | title="Hermes Agent release thread", |
| 1681 | url=thread_url, |
| 1682 | snippet="", |
| 1683 | subquery_labels=["primary"], |
| 1684 | native_ranks={"primary:reddit": 1}, |
| 1685 | local_relevance=0.9, |
| 1686 | freshness=80, |
| 1687 | engagement=60, |
| 1688 | source_quality=0.6, |
| 1689 | rrf_score=0.03, |
| 1690 | sources=["reddit", "grounding"], |
| 1691 | source_items=[native_reddit, web_reddit], |
| 1692 | final_score=70.0, |
| 1693 | ) |
| 1694 | report_fused = schema.Report( |
| 1695 | topic="Hermes Agent", |
| 1696 | range_from="2026-10-01", |
| 1697 | range_to="2026-10-31", |
| 1698 | generated_at="2026-10-31T00:00:00Z", |
| 1699 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1700 | query_plan=_plan("Hermes Agent", ["reddit", "grounding"]), |
| 1701 | clusters=[], |
| 1702 | ranked_candidates=[fused_cand], |
| 1703 | items_by_source={"reddit": [native_reddit], "grounding": [web_reddit]}, |
| 1704 | errors_by_source={}, |
| 1705 | ) |
| 1706 | fused_lines = render._render_top_comments(report_fused, limit=10) |
| 1707 | quote_lines_fused = [ln for ln in fused_lines if ln.startswith("- ")] |
| 1708 | assert len(quote_lines_fused) == 2 |
| 1709 | assert "native_one" in quote_lines_fused[0] |
| 1710 | assert "web_one" in quote_lines_fused[1] |
| 1711 | assert not any("native_two" in ln or "web_two" in ln for ln in quote_lines_fused) |
| 1712 | |
| 1713 | # Case 2: Two separate candidates referencing the same Reddit thread -> still capped at 2 quotes total. |
| 1714 | cand_a = schema.Candidate( |
| 1715 | candidate_id="cand-native", |
| 1716 | item_id="R1", |
| 1717 | source="reddit", |
| 1718 | title="Hermes Agent release thread", |
| 1719 | url=thread_url, |
| 1720 | snippet="", |
| 1721 | subquery_labels=["primary"], |
| 1722 | native_ranks={"primary:reddit": 1}, |
| 1723 | local_relevance=0.9, |
| 1724 | freshness=80, |
| 1725 | engagement=60, |
| 1726 | source_quality=0.6, |
| 1727 | rrf_score=0.03, |
| 1728 | sources=["reddit"], |
| 1729 | source_items=[native_reddit], |
| 1730 | final_score=70.0, |
| 1731 | ) |
| 1732 | cand_b = schema.Candidate( |
| 1733 | candidate_id="cand-web", |
| 1734 | item_id="W1", |
| 1735 | source="grounding", |
| 1736 | title="Hermes Agent release thread", |
| 1737 | url=thread_url, |
| 1738 | snippet="", |
| 1739 | subquery_labels=["primary"], |
| 1740 | native_ranks={"primary:grounding": 1}, |
| 1741 | local_relevance=0.8, |
| 1742 | freshness=80, |
| 1743 | engagement=None, |
| 1744 | source_quality=1.0, |
| 1745 | rrf_score=0.02, |
| 1746 | sources=["grounding"], |
| 1747 | source_items=[web_reddit], |
| 1748 | final_score=65.0, |
| 1749 | ) |
| 1750 | report_split = schema.Report( |
| 1751 | topic="Hermes Agent", |
| 1752 | range_from="2026-10-01", |
| 1753 | range_to="2026-10-31", |
| 1754 | generated_at="2026-10-31T00:00:00Z", |
| 1755 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1756 | query_plan=_plan("Hermes Agent", ["reddit", "grounding"]), |
| 1757 | clusters=[], |
| 1758 | ranked_candidates=[cand_a, cand_b], |
| 1759 | items_by_source={"reddit": [native_reddit], "grounding": [web_reddit]}, |
| 1760 | errors_by_source={}, |
| 1761 | ) |
| 1762 | split_lines = render._render_top_comments(report_split, limit=10) |
| 1763 | quote_lines_split = [ln for ln in split_lines if ln.startswith("- ")] |
| 1764 | assert len(quote_lines_split) == 2 |
| 1765 | |
| 1766 | def test_merged_reddit_group_sorts_by_votes_and_places_pending_last(self): |
| 1767 | # Case 1: Native Reddit copy has a 2-upvote reply (below the 5-upvote item floor for a |
| 1768 | # 200-score thread), while the web copy has a 20-upvote reply. Merged comments must sort |
| 1769 | # by descending score so the 20-upvote reply sits at index 0 and clears the item floor! |
| 1770 | thread_url = "https://www.reddit.com/r/python/comments/sort123/hermes_agent/" |
| 1771 | native_low = schema.SourceItem( |
| 1772 | item_id="R-low", |
| 1773 | source="reddit", |
| 1774 | title="Hermes Agent benchmark thread", |
| 1775 | body="Hermes Agent benchmark thread", |
| 1776 | url=thread_url, |
| 1777 | container="python", |
| 1778 | published_at="2026-10-20", |
| 1779 | date_confidence="high", |
| 1780 | engagement={"score": 200, "num_comments": 50}, |
| 1781 | metadata={ |
| 1782 | "top_comments": [ |
| 1783 | { |
| 1784 | "id": "low1", |
| 1785 | "score": 2, |
| 1786 | "author": "low_voter", |
| 1787 | "excerpt": "Low-vote native reply on Hermes Agent benchmarks.", |
| 1788 | "depth": 0, |
| 1789 | }, |
| 1790 | ] |
| 1791 | }, |
| 1792 | ) |
| 1793 | web_high = schema.SourceItem( |
| 1794 | item_id="W-high", |
| 1795 | source="grounding", |
| 1796 | title="Hermes Agent benchmark thread", |
| 1797 | body="Hermes Agent benchmark thread", |
| 1798 | url=thread_url, |
| 1799 | published_at="2026-10-20", |
| 1800 | date_confidence="high", |
| 1801 | metadata={ |
| 1802 | "enriched_via": "arctic", |
| 1803 | "reddit_thread_score": 200, |
| 1804 | "reddit_subreddit": "python", |
| 1805 | "top_comments": [ |
| 1806 | { |
| 1807 | "id": "high1", |
| 1808 | "score": 20, |
| 1809 | "author": "high_voter", |
| 1810 | "excerpt": "High-vote web reply proving Hermes Agent speed.", |
| 1811 | "depth": 0, |
| 1812 | }, |
| 1813 | ], |
| 1814 | }, |
| 1815 | ) |
| 1816 | cand_votes = schema.Candidate( |
| 1817 | candidate_id=thread_url, |
| 1818 | item_id="R-low", |
| 1819 | source="reddit", |
| 1820 | title="Hermes Agent benchmark thread", |
| 1821 | url=thread_url, |
| 1822 | snippet="", |
| 1823 | subquery_labels=["primary"], |
| 1824 | native_ranks={"primary:reddit": 1}, |
| 1825 | local_relevance=0.9, |
| 1826 | freshness=80, |
| 1827 | engagement=60, |
| 1828 | source_quality=0.6, |
| 1829 | rrf_score=0.03, |
| 1830 | sources=["reddit", "grounding"], |
| 1831 | source_items=[native_low, web_high], |
| 1832 | final_score=70.0, |
| 1833 | ) |
| 1834 | report_votes = schema.Report( |
| 1835 | topic="Hermes Agent", |
| 1836 | range_from="2026-10-01", |
| 1837 | range_to="2026-10-31", |
| 1838 | generated_at="2026-10-31T00:00:00Z", |
| 1839 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1840 | query_plan=_plan("Hermes Agent", ["reddit", "grounding"]), |
| 1841 | clusters=[], |
| 1842 | ranked_candidates=[cand_votes], |
| 1843 | items_by_source={"reddit": [native_low], "grounding": [web_high]}, |
| 1844 | errors_by_source={}, |
| 1845 | ) |
| 1846 | lines_votes = render._render_top_comments(report_votes, limit=10) |
| 1847 | quote_lines_votes = [ln for ln in lines_votes if ln.startswith("- ")] |
| 1848 | assert len(quote_lines_votes) == 2 |
| 1849 | assert "high_voter" in quote_lines_votes[0] |
| 1850 | assert "20 upvotes" in quote_lines_votes[0] |
| 1851 | assert "low_voter" in quote_lines_votes[1] |
| 1852 | assert "2 upvotes" in quote_lines_votes[1] |
| 1853 | |
| 1854 | # Case 2: Native Reddit copy has two score_pending replies while web copy has a scored |
| 1855 | # 15-upvote reply -> scored reply must lead ahead of pending replies (never crowded out). |
| 1856 | pending_url = "https://www.reddit.com/r/python/comments/pend456/hermes_agent/" |
| 1857 | native_pending = schema.SourceItem( |
| 1858 | item_id="R-pend", |
| 1859 | source="reddit", |
| 1860 | title="Hermes Agent launch discussion", |
| 1861 | body="Hermes Agent launch discussion", |
| 1862 | url=pending_url, |
| 1863 | container="python", |
| 1864 | published_at="2026-10-20", |
| 1865 | date_confidence="high", |
| 1866 | engagement={"score": None, "num_comments": 10}, |
| 1867 | metadata={ |
| 1868 | "engagement_source": reddit_refs.ARCTIC_PENDING, |
| 1869 | "top_comments": [ |
| 1870 | { |
| 1871 | "id": "p1", |
| 1872 | "score": None, |
| 1873 | "score_pending": True, |
| 1874 | "author": "pending_one", |
| 1875 | "excerpt": "First pending comment about Hermes Agent launch.", |
| 1876 | "depth": 0, |
| 1877 | }, |
| 1878 | { |
| 1879 | "id": "p2", |
| 1880 | "score": None, |
| 1881 | "score_pending": True, |
| 1882 | "author": "pending_two", |
| 1883 | "excerpt": "Second pending comment about Hermes Agent launch.", |
| 1884 | "depth": 0, |
| 1885 | }, |
| 1886 | ], |
| 1887 | }, |
| 1888 | ) |
| 1889 | web_scored = schema.SourceItem( |
| 1890 | item_id="W-scored", |
| 1891 | source="grounding", |
| 1892 | title="Hermes Agent launch discussion", |
| 1893 | body="Hermes Agent launch discussion", |
| 1894 | url=pending_url, |
| 1895 | published_at="2026-10-20", |
| 1896 | date_confidence="high", |
| 1897 | metadata={ |
| 1898 | "enriched_via": "arctic", |
| 1899 | "reddit_thread_score": 150, |
| 1900 | "reddit_subreddit": "python", |
| 1901 | "top_comments": [ |
| 1902 | { |
| 1903 | "id": "s1", |
| 1904 | "score": 15, |
| 1905 | "author": "scored_user", |
| 1906 | "excerpt": "Scored 15-upvote comment on Hermes Agent launch.", |
| 1907 | "depth": 0, |
| 1908 | }, |
| 1909 | ], |
| 1910 | }, |
| 1911 | ) |
| 1912 | cand_pending = schema.Candidate( |
| 1913 | candidate_id=pending_url, |
| 1914 | item_id="R-pend", |
| 1915 | source="reddit", |
| 1916 | title="Hermes Agent launch discussion", |
| 1917 | url=pending_url, |
| 1918 | snippet="", |
| 1919 | subquery_labels=["primary"], |
| 1920 | native_ranks={"primary:reddit": 1}, |
| 1921 | local_relevance=0.9, |
| 1922 | freshness=80, |
| 1923 | engagement=50, |
| 1924 | source_quality=0.6, |
| 1925 | rrf_score=0.03, |
| 1926 | sources=["reddit", "grounding"], |
| 1927 | source_items=[native_pending, web_scored], |
| 1928 | final_score=70.0, |
| 1929 | ) |
| 1930 | report_pending = schema.Report( |
| 1931 | topic="Hermes Agent", |
| 1932 | range_from="2026-10-01", |
| 1933 | range_to="2026-10-31", |
| 1934 | generated_at="2026-10-31T00:00:00Z", |
| 1935 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 1936 | query_plan=_plan("Hermes Agent", ["reddit", "grounding"]), |
| 1937 | clusters=[], |
| 1938 | ranked_candidates=[cand_pending], |
| 1939 | items_by_source={"reddit": [native_pending], "grounding": [web_scored]}, |
| 1940 | errors_by_source={}, |
| 1941 | ) |
| 1942 | lines_pending = render._render_top_comments(report_pending, limit=10) |
| 1943 | quote_lines_pending = [ln for ln in lines_pending if ln.startswith("- ")] |
| 1944 | assert len(quote_lines_pending) == 2 |
| 1945 | assert "scored_user" in quote_lines_pending[0] |
| 1946 | assert "15 upvotes" in quote_lines_pending[0] |
| 1947 | assert "pending_one" in quote_lines_pending[1] |
| 1948 | assert not any("pending_two" in ln for ln in quote_lines_pending) |
| 1949 | |
| 1950 | def test_arctic_web_reddit_comments_apply_reddit_rules_in_cards_and_render_full(self): |
| 1951 | thread_url = "https://www.reddit.com/r/python/comments/card99/hermes_agent/" |
| 1952 | web_reddit = schema.SourceItem( |
| 1953 | item_id="W-card", |
| 1954 | source="grounding", |
| 1955 | title="Hermes Agent Reddit discussion found via web", |
| 1956 | body="Hermes Agent Reddit discussion found via web", |
| 1957 | snippet="Web snippet for Hermes Agent thread", |
| 1958 | url=thread_url, |
| 1959 | published_at="2026-10-20", |
| 1960 | date_confidence="high", |
| 1961 | metadata={ |
| 1962 | "enriched_via": "arctic", |
| 1963 | "reddit_thread_score": 120, |
| 1964 | "reddit_subreddit": "python", |
| 1965 | "top_comments": [ |
| 1966 | { |
| 1967 | "id": "c0", |
| 1968 | "score": 0, |
| 1969 | "author": "zero_user", |
| 1970 | "excerpt": "Zero-vote reply should never appear on ranked cards.", |
| 1971 | "depth": 0, |
| 1972 | }, |
| 1973 | { |
| 1974 | "id": "c5", |
| 1975 | "score": 5, |
| 1976 | "author": "five_user", |
| 1977 | "excerpt": "Five-vote reply is below Reddit card floor.", |
| 1978 | "depth": 0, |
| 1979 | }, |
| 1980 | { |
| 1981 | "id": "c14", |
| 1982 | "score": 14, |
| 1983 | "author": "alice", |
| 1984 | "excerpt": "Fourteen-vote reply clears Reddit card floor cleanly.", |
| 1985 | "depth": 0, |
| 1986 | }, |
| 1987 | ], |
| 1988 | }, |
| 1989 | ) |
| 1990 | # _top_comments_list enforces Reddit's 10-upvote floor for web-found Reddit threads. |
| 1991 | filtered = render._top_comments_list(web_reddit) |
| 1992 | assert [c["id"] for c in filtered] == ["c14"] |
| 1993 | |
| 1994 | cand = schema.Candidate( |
| 1995 | candidate_id=thread_url, |
| 1996 | item_id="W-card", |
| 1997 | source="grounding", |
| 1998 | title=web_reddit.title, |
| 1999 | url=thread_url, |
| 2000 | snippet=web_reddit.snippet, |
| 2001 | subquery_labels=["primary"], |
| 2002 | native_ranks={"primary:grounding": 1}, |
| 2003 | local_relevance=0.9, |
| 2004 | freshness=85, |
| 2005 | engagement=None, |
| 2006 | source_quality=1.0, |
| 2007 | rrf_score=0.03, |
| 2008 | sources=["grounding"], |
| 2009 | source_items=[web_reddit], |
| 2010 | final_score=72.0, |
| 2011 | ) |
| 2012 | cluster = schema.Cluster( |
| 2013 | cluster_id="cl1", |
| 2014 | title=web_reddit.title, |
| 2015 | candidate_ids=[cand.candidate_id], |
| 2016 | representative_ids=[cand.candidate_id], |
| 2017 | sources=["grounding"], |
| 2018 | score=cand.final_score, |
| 2019 | ) |
| 2020 | report = schema.Report( |
| 2021 | topic="Hermes Agent", |
| 2022 | range_from="2026-10-01", |
| 2023 | range_to="2026-10-31", |
| 2024 | generated_at="2026-10-31T00:00:00Z", |
| 2025 | provider_runtime=schema.ProviderRuntime("local", "m", "m"), |
| 2026 | query_plan=_plan("Hermes Agent", ["grounding"]), |
| 2027 | clusters=[cluster], |
| 2028 | ranked_candidates=[cand], |
| 2029 | items_by_source={"grounding": [web_reddit]}, |
| 2030 | errors_by_source={}, |
| 2031 | ) |
| 2032 | |
| 2033 | # Ranked card keeps [grounding] badge (item.source stays "grounding", never rewritten to reddit), |
| 2034 | # rejects <10-vote replies, and formats qualifying replies with Reddit's u/ byline and "upvotes" label. |
| 2035 | card_text = "\n".join(render._render_candidate(cand, "1.", report)) |
| 2036 | assert "1. [grounding]" in card_text |
| 2037 | assert "1. [reddit]" not in card_text |
| 2038 | assert "zero_user" not in card_text |
| 2039 | assert "five_user" not in card_text |
| 2040 | assert "u/alice (14 upvotes):" in card_text |
| 2041 | assert "14 votes" not in card_text |
| 2042 | |
| 2043 | compact_text = render.render_compact(report) |
| 2044 | clusters_section = compact_text.split("## Top Community Comments")[0] |
| 2045 | assert "[grounding]" in clusters_section |
| 2046 | assert "[reddit]" not in clusters_section |
| 2047 | assert "u/alice (14 upvotes):" in clusters_section |
| 2048 | assert "zero_user" not in compact_text |
| 2049 | assert "five_user" not in clusters_section |
| 2050 | |
| 2051 | # render_full also uses Reddit's u/ byline and "upvotes" label while keeping source="grounding". |
| 2052 | full_text = render.render_full(report) |
| 2053 | assert "Top comment u/alice (14 upvotes):" in full_text |
| 2054 | assert "Top comment u/zero_user (0 upvotes):" in full_text |
| 2055 | assert "14 votes" not in full_text |
| 2056 | assert web_reddit.source == "grounding" |
| 2057 | |
| 2058 | |
| 2059 | # --------------------------------------------------------------------------- |
| 2060 | # HIGH-108: UTC clock in grounding._now() for east-of-UTC Serper relative dates |
| 2061 | # --------------------------------------------------------------------------- |
| 2062 | |
| 2063 | |
| 2064 | class TestHigh108GroundingUtcClock: |
| 2065 | def test_now_returns_timezone_aware_utc(self): |
| 2066 | now = grounding._now() |
| 2067 | assert now.tzinfo is timezone.utc |
| 2068 | |
| 2069 | def test_serper_relative_dates_stay_in_utc_window_for_east_of_utc_users(self): |
| 2070 | # 2026-03-27T20:00:00Z is already 2026-03-28 05:00 in UTC+9 (Tokyo). |
| 2071 | # With UTC _now(), fresh Serper relative results resolve to 2026-03-27 |
| 2072 | # and stay inside the UTC date_range ("2026-02-25", "2026-03-27"). |
| 2073 | utc_now = datetime(2026, 3, 27, 20, 0, tzinfo=timezone.utc) |
| 2074 | mock_response = { |
| 2075 | "organic": [ |
| 2076 | {"title": "Breaking Now", "link": "https://example.com/1", "snippet": "s", "date": "just now"}, |
| 2077 | {"title": "Breaking Today", "link": "https://example.com/2", "snippet": "s", "date": "today"}, |
| 2078 | {"title": "Breaking Mins", "link": "https://example.com/3", "snippet": "s", "date": "15 minutes ago"}, |
| 2079 | {"title": "Breaking Hours", "link": "https://example.com/4", "snippet": "s", "date": "2 hours ago"}, |
| 2080 | ] |
| 2081 | } |
| 2082 | with patch("lib.grounding.http.request", return_value=mock_response), \ |
| 2083 | patch("lib.grounding._now", return_value=utc_now): |
| 2084 | items, _artifact = grounding.serper_search( |
| 2085 | "breaking", ("2026-02-25", "2026-03-27"), "fake-key" |
| 2086 | ) |
| 2087 | assert len(items) == 4 |
| 2088 | assert all(item["date"] == "2026-03-27" for item in items) |
| 2089 |