返回 last30days-skill
test_fun_vote_weighting.py
根目录 / tests / test_fun_vote_weighting.py
1 """Tests for crowd-vote weighting in the fun judge (Best Takes).
2
3 Covers:
4 - U2: signals.top_comment_vote_signal (per-platform normalized [0,1] vote signal)
5 - U1: rerank._extract_comment_text_scored / _build_fun_prompt (votes in the LLM prompt)
6 - U4: rerank._apply_single_fun_fallback (fallback uses the vote signal)
7 - U3: render._render_best_takes (relevance-gated, confidence-scaled, bounded nudge)
8 """
9
10 import pytest
11
12 from lib import fusion, normalize, schema, signals
13 from lib.rerank import (
14 _apply_single_fun_fallback,
15 _build_fun_prompt,
16 _extract_comment_text,
17 _extract_comment_text_scored,
18 )
19 from lib import render
20
21
22 def _candidate(
23 *,
24 source: str = "reddit",
25 title: str = "Some Title",
26 snippet: str = "",
27 top_comments=None,
28 fun_score=None,
29 local_relevance: float = 0.8,
30 explanation: str | None = None,
31 final_score: float = 50.0,
32 engagement=0.0,
33 ) -> schema.Candidate:
34 source_items = []
35 if top_comments is not None:
36 source_items.append(
37 schema.SourceItem(
38 item_id="si-1",
39 source=source,
40 title=title,
41 body="",
42 url=f"https://example.com/{source}/1",
43 metadata={"top_comments": top_comments},
44 )
45 )
46 c = schema.Candidate(
47 candidate_id="c-1",
48 item_id="i-1",
49 source=source,
50 title=title,
51 url=f"https://example.com/{source}/1",
52 snippet=snippet,
53 subquery_labels=["q1"],
54 native_ranks={source: 1},
55 local_relevance=local_relevance,
56 freshness=50,
57 engagement=engagement,
58 source_quality=0.5,
59 rrf_score=0.01,
60 source_items=source_items,
61 )
62 c.fun_score = fun_score
63 c.explanation = explanation
64 c.final_score = final_score
65 return c
66
67
68 # --------------------------------------------------------------------------- U2
69
70 class TestTopCommentVoteSignal:
71 def test_cross_platform_comparable(self):
72 """A 66-upvote Reddit comment and a 22,821-like TikTok comment land on a
73 comparable scale -- neither platform dominates by raw count."""
74 reddit = _candidate(source="reddit", top_comments=[{"body": "x", "score": 66}])
75 tiktok = _candidate(source="tiktok", top_comments=[{"body": "x", "score": 22821}])
76 rs = signals.top_comment_vote_signal(reddit)
77 ts = signals.top_comment_vote_signal(tiktok)
78 # Both substantial, and TikTok's 22k does not swamp Reddit's 66 by 100x.
79 assert 0.3 < rs < 1.0
80 assert 0.3 < ts <= 1.0
81 assert ts / max(rs, 1e-9) < 2.5
82
83 def test_zero_or_missing_votes(self):
84 assert signals.top_comment_vote_signal(_candidate(top_comments=[{"body": "x"}])) == 0.0
85 assert signals.top_comment_vote_signal(_candidate(top_comments=[{"body": "x", "score": 0}])) == 0.0
86 assert signals.top_comment_vote_signal(_candidate(top_comments=None)) == 0.0
87
88 def test_monotonic_within_platform(self):
89 low = _candidate(source="reddit", top_comments=[{"body": "x", "score": 10}])
90 high = _candidate(source="reddit", top_comments=[{"body": "x", "score": 5000}])
91 assert signals.top_comment_vote_signal(high) > signals.top_comment_vote_signal(low)
92
93 def test_bounded_zero_to_one(self):
94 for score in (1, 100, 6100, 39000, 10_000_000):
95 sig = signals.top_comment_vote_signal(
96 _candidate(source="tiktok", top_comments=[{"body": "x", "score": score}])
97 )
98 assert 0.0 <= sig <= 1.0
99
100
101 # --------------------------------------------------------------------------- U1
102
103 class TestVotesInFunPrompt:
104 @pytest.mark.parametrize(
105 ("source", "vote_field"),
106 [
107 ("youtube", "likes"),
108 ("tiktok", "digg_count"),
109 ("instagram", "comment_like_count"),
110 ],
111 )
112 def test_normalized_video_comments_reach_fun_prompt(self, source, vote_field):
113 comment = f"lmao the {source} comment section did the research"
114 items = normalize.normalize_source_items(
115 source,
116 [{
117 "id": "video-1",
118 "title": "Research update",
119 "text": "Research update",
120 "url": f"https://example.com/{source}/video-1",
121 "date": "2026-09-20",
122 "top_comments": [{"text": comment, vote_field: 1200}],
123 }],
124 "2026-09-01",
125 "2026-09-30",
126 )
127 plan = schema.QueryPlan(
128 intent="concept",
129 freshness_mode="balanced_recent",
130 cluster_mode="concept",
131 raw_topic="Research update",
132 subqueries=[schema.SubQuery(
133 label="primary",
134 search_query="Research update",
135 ranking_query="Research update",
136 sources=[source],
137 )],
138 source_weights={source: 1.0},
139 )
140 candidates = fusion.weighted_rrf(
141 {("primary", source): items}, plan, pool_limit=10,
142 )
143
144 assert len(candidates) == 1
145 assert f"comments: [+1200] {comment}" in _build_fun_prompt(
146 "Research update", candidates,
147 )
148 assert _extract_comment_text(candidates[0]) == comment
149
150 def test_extractors_preserve_legacy_comments_limits_and_insights(self):
151 excerpt = "canonical comment " * 20
152 c = _candidate(top_comments=[
153 {"excerpt": excerpt, "body": "superseded body", "score": 14200},
154 {"body": "legacy Reddit comment", "score": 3},
155 "plain string comment",
156 {"excerpt": "fourth comment"},
157 ])
158 c.source_items[0].metadata["comment_insights"] = [
159 "first insight", "second insight", "third insight",
160 ]
161 tail = "plain string comment | first insight | second insight"
162
163 assert _extract_comment_text(c) == (
164 f"{excerpt[:150]} | legacy Reddit comment | {tail}"
165 )
166 assert _extract_comment_text_scored(c) == (
167 f"[+14200] {excerpt[:150]} | [+3] legacy Reddit comment | {tail}"
168 )
169
170 @pytest.mark.parametrize("excerpt", [None, ""])
171 def test_empty_excerpt_falls_back_to_legacy_body(self, excerpt):
172 c = _candidate(top_comments=[{
173 "excerpt": excerpt, "body": "legacy comment", "score": 5,
174 }])
175 assert _extract_comment_text(c) == "legacy comment"
176 assert _extract_comment_text_scored(c) == "[+5] legacy comment"
177
178 def test_scored_extract_prefixes_vote_count(self):
179 c = _candidate(top_comments=[{"body": "the crowd loved this", "score": 14200}])
180 text = _extract_comment_text_scored(c)
181 assert "[+14200]" in text
182 assert "the crowd loved this" in text
183
184 def test_scored_extract_no_score_no_prefix(self):
185 c = _candidate(top_comments=[{"body": "no score here"}])
186 text = _extract_comment_text_scored(c)
187 assert "no score here" in text
188 assert "[+" not in text
189
190 def test_scored_extract_negative_score_no_malformed_prefix(self):
191 """A negative score must not emit a misleading [+-N] prefix (Greptile #592)."""
192 c = _candidate(top_comments=[{"body": "downvoted line", "score": -3}])
193 text = _extract_comment_text_scored(c)
194 assert "downvoted line" in text
195 assert "[+-3]" not in text
196 assert "[+" not in text
197
198 def test_prompt_contains_traction_guidance(self):
199 c = _candidate(top_comments=[{"body": "lol", "score": 99}])
200 prompt = _build_fun_prompt("test topic", [c])
201 assert "[+99]" in prompt
202 # The judge is told votes = traction, not funniness.
203 assert "TRACTION" in prompt
204
205
206 # --------------------------------------------------------------------------- U4
207
208 class TestFallbackUsesVoteSignal:
209 def test_high_vote_top_comment_scores_higher(self):
210 low = _candidate(source="reddit", title="t", snippet="s", top_comments=[{"body": "ok", "score": 5}])
211 high = _candidate(source="reddit", title="t", snippet="s", top_comments=[{"body": "ok", "score": 4000}])
212 _apply_single_fun_fallback(low)
213 _apply_single_fun_fallback(high)
214 assert high.fun_score > low.fun_score
215
216 def test_fallback_bounded(self):
217 c = _candidate(source="tiktok", top_comments=[{"body": "lol bruh", "score": 10_000_000}])
218 _apply_single_fun_fallback(c)
219 assert 0.0 <= c.fun_score <= 100.0
220
221 def test_fallback_without_votes_still_scores(self):
222 c = _candidate(title="hilarious bit", snippet="", top_comments=[{"body": "bruh"}])
223 _apply_single_fun_fallback(c)
224 assert c.fun_score is not None and c.fun_score > 0
225
226
227 # --------------------------------------------------------------------------- U3
228
229 def _render(cands, level="medium"):
230 p = render._FUN_LEVELS[level]
231 return "\n".join(
232 render._render_best_takes(cands, limit=p["limit"], threshold=p["threshold"], vote_weight=p["vote_weight"])
233 )
234
235
236 class TestBestTakesVoteWeighting:
237 # Best Takes displays the candidate TITLE when the top comment body is longer
238 # than it, so these tests use distinctive long titles + longer comment bodies
239 # and assert on the titles.
240 def test_relevance_gate_excludes_entity_miss(self):
241 """An off-topic-but-viral comment (entity-miss) never reaches Best Takes,
242 even with a huge vote count and a high fun_score."""
243 offtopic = _candidate(
244 source="youtube", title="JamesMayReactsClip", fun_score=85,
245 top_comments=[{"body": "James May is a great man and a true friend", "score": 39000}],
246 explanation="fallback-local-score (entity-miss demotion)", final_score=0.0,
247 )
248 ontopic_a = _candidate(source="reddit", title="VelcroShirtReturn", fun_score=88,
249 top_comments=[{"body": "the velcro on my camp chair bag ate it", "score": 66}])
250 ontopic_b = _candidate(source="reddit", title="BuriedInBaggies", fun_score=82,
251 top_comments=[{"body": "when i die bury me in my baggies", "score": 73}])
252 out = _render([offtopic, ontopic_a, ontopic_b])
253 assert "JamesMayReactsClip" not in out
254 assert "VelcroShirtReturn" in out
255
256 def test_zero_final_score_excluded(self):
257 dead = _candidate(title="DeadZeroScore", fun_score=90, final_score=0.0,
258 top_comments=[{"body": "high voted but score zero item", "score": 100}])
259 a = _candidate(title="FunnyAlpha", fun_score=88, top_comments=[{"body": "funny alpha line here", "score": 50}])
260 b = _candidate(title="FunnyBeta", fun_score=85, top_comments=[{"body": "funny beta line here", "score": 50}])
261 out = _render([dead, a, b])
262 assert "DeadZeroScore" not in out
263
264 def test_funny_floor_blocks_high_vote_unfunny(self):
265 """A high-voted but unfunny comment (fun below the floor) is excluded."""
266 rant = _candidate(title="LawyerRant", fun_score=15,
267 top_comments=[{"body": "pay a lawyer to send a letter to their legal dept", "score": 1720}])
268 a = _candidate(title="FunnyAlpha", fun_score=80, top_comments=[{"body": "funny alpha line here", "score": 40}])
269 b = _candidate(title="FunnyBeta", fun_score=78, top_comments=[{"body": "funny beta line here", "score": 40}])
270 out = _render([rant, a, b])
271 assert "LawyerRant" not in out
272
273 def test_votes_promote_funnyish_over_threshold(self):
274 """A funny-ish on-topic comment (fun 55) with strong on-topic votes clears
275 the medium threshold (70) via the effective score -- the empty-Best-Takes fix."""
276 promoted = _candidate(source="reddit", title="PromotedGem", fun_score=55, local_relevance=1.0,
277 top_comments=[{"body": "a promoted gem the crowd loved", "score": 6000}])
278 other = _candidate(source="reddit", title="AlreadyFunny", fun_score=72,
279 top_comments=[{"body": "already funny on its own merit", "score": 10}])
280 # Without votes, PromotedGem (fun 55) would not clear medium's 70 threshold.
281 baseline = _render([
282 _candidate(source="reddit", title="PromotedGem", fun_score=55,
283 top_comments=[{"body": "a promoted gem the crowd loved"}]),
284 other,
285 ])
286 assert "PromotedGem" not in baseline
287 out = _render([promoted, other])
288 assert "PromotedGem" in out
289
290 def test_bounded_amplification_does_not_overturn_humor_gap(self):
291 """fun 90 / tiny votes still ranks above fun 55 / max votes at medium."""
292 gem = _candidate(source="reddit", title="GhostOfYvonGem", fun_score=90, local_relevance=1.0,
293 top_comments=[{"body": "the ghost of yvon weeps for this funko pop civilization", "score": 26}])
294 viral = _candidate(source="tiktok", title="MidButViral", fun_score=55, local_relevance=1.0,
295 top_comments=[{"body": "mid but extremely viral comment here", "score": 50000}])
296 out = _render([gem, viral])
297 assert out.index("GhostOfYvonGem") < out.index("MidButViral")
298
299 def test_meaningful_at_medium_orders_by_votes(self):
300 """Equal fun_score, different votes -> ordered by votes, and the effect is
301 more than a hairline tiebreaker at medium."""
302 hi = _candidate(source="reddit", title="HighVotedItem", fun_score=72, local_relevance=1.0,
303 top_comments=[{"body": "high voted comment body here", "score": 5000}])
304 lo = _candidate(source="reddit", title="LowVotedItem", fun_score=72, local_relevance=1.0,
305 top_comments=[{"body": "low voted comment body here", "score": 5}])
306 eff_hi = render._effective_fun_score(hi, render._FUN_LEVELS["medium"]["vote_weight"])
307 eff_lo = render._effective_fun_score(lo, render._FUN_LEVELS["medium"]["vote_weight"])
308 assert eff_hi - eff_lo > 5.0 # meaningful, not a tiebreaker
309 out = _render([hi, lo])
310 assert out.index("HighVotedItem") < out.index("LowVotedItem")
311
312 def test_level_scaling_high_more_than_low(self):
313 c = _candidate(source="reddit", fun_score=72, local_relevance=1.0,
314 top_comments=[{"body": "x", "score": 5000}])
315 eff_low = render._effective_fun_score(c, render._FUN_LEVELS["low"]["vote_weight"])
316 eff_high = render._effective_fun_score(c, render._FUN_LEVELS["high"]["vote_weight"])
317 base = c.fun_score
318 assert (eff_high - base) > (eff_low - base)
319
320 def test_confidence_scaling(self):
321 weight = render._FUN_LEVELS["medium"]["vote_weight"]
322 high_conf = _candidate(source="reddit", fun_score=72, local_relevance=1.0,
323 top_comments=[{"body": "x", "score": 5000}])
324 low_conf = _candidate(source="reddit", fun_score=72, local_relevance=0.2,
325 top_comments=[{"body": "x", "score": 5000}])
326 assert render._effective_fun_score(high_conf, weight) > render._effective_fun_score(low_conf, weight)
327
328 def test_crowd_boost_tag_when_votes_lift_ranking(self):
329 """A vote-boosted item is flagged '+crowd' so a lower-fun item ranking
330 above a higher-fun one reads correctly (Greptile #592)."""
331 boosted = _candidate(source="reddit", title="BoostedItem", fun_score=72, local_relevance=1.0,
332 top_comments=[{"body": "crowd loved this line a lot", "score": 6000}])
333 plain = _candidate(source="reddit", title="PlainItem", fun_score=90,
334 top_comments=[{"body": "very funny on its own merit here"}])
335 out = _render([boosted, plain])
336 assert "+crowd" in out
337 # The plain (no-votes) item carries no crowd tag.
338 plain_line = [ln for ln in out.splitlines() if "PlainItem" in ln][0]
339 assert "+crowd" not in plain_line
340
341 def test_no_votes_preserves_pure_fun_ordering(self):
342 """With no comment votes, Best Takes ordering matches pure fun_score (no regression)."""
343 a = _candidate(source="reddit", title="FunnyAlpha", fun_score=90, top_comments=[{"body": "funny alpha line here"}])
344 b = _candidate(source="reddit", title="FunnyBeta", fun_score=80, top_comments=[{"body": "funny beta line here"}])
345 out = _render([a, b])
346 assert out.index("FunnyAlpha") < out.index("FunnyBeta")
347
347 lines PYTHON