返回 last30days-skill
test_first_party_floor.py
根目录 / tests / test_first_party_floor.py
1 """Retrieval-floor exemption for posts authored by a handle the run is searching.
2
3 The production failure this pins: a mixed batch where the mention lane clears
4 the relevance floor and the from lane does not. Because
5 `prune_low_relevance` ends with `return filtered or items`, the all-fail rescue
6 only fires when *everything* fails. A mixed batch is therefore the exact shape
7 that silently loses the subject's own posts, and no prior test exercised it --
8 existing supplement-lane tests use single-item batches that trip the rescue.
9 """
10
11 from unittest.mock import patch
12
13 import pytest
14
15 from lib import pipeline, schema, signals
16
17
18 def _x_item(item_id: str, author: str, relevance: float, engagement: dict | None = None):
19 item = schema.SourceItem(
20 item_id=item_id,
21 source="x",
22 title="",
23 body="post body",
24 url=f"https://x.com/{author}/status/{item_id}",
25 author=author,
26 engagement=engagement or {},
27 )
28 item.local_relevance = relevance
29 return item
30
31
32 def _mixed_batch():
33 """From-lane items score 0.0 (a post rarely names its own author);
34 mention-lane items clear the floor because they contain the handle."""
35 return [
36 _x_item("1", "steipete", 0.0, {"likes": 7773, "reposts": 391}),
37 _x_item("2", "steipete", 0.0, {"likes": 3466, "reposts": 128}),
38 _x_item("3", "someone_else", 0.32, {"likes": 78, "reposts": 8}),
39 _x_item("4", "another_acct", 0.23, {"likes": 8, "reposts": 1}),
40 ]
41
42
43 def _annotate(items):
44 """Populate engagement_score the way the real pipeline does."""
45 scores = signals.normalize([signals.engagement_raw(i) for i in items])
46 for item, score in zip(items, scores, strict=True):
47 item.engagement_score = score
48 return items
49
50
51 def test_mixed_batch_keeps_first_party_and_drops_off_topic():
52 items = _annotate(_mixed_batch())
53 kept = signals.prune_low_relevance(items, first_party_handles={"steipete"})
54 authors = sorted(i.author for i in kept)
55 assert "steipete" in authors, (
56 "first-party posts were pruned from a mixed batch; this is the measured "
57 "defect where 8 subject-authored posts never reached the report"
58 )
59 assert len([a for a in authors if a == "steipete"]) == 2
60
61
62 def test_mixed_batch_without_exemption_still_loses_first_party():
63 """Characterizes the defect: without the exemption the batch drops them."""
64 items = _annotate(_mixed_batch())
65 kept = signals.prune_low_relevance(items)
66 assert all(i.author != "steipete" for i in kept), (
67 "expected the unexempted path to still drop zero-relevance first-party "
68 "posts; if this now passes, the floor changed and the exemption's "
69 "justification needs rechecking"
70 )
71
72
73 def test_non_first_party_below_floor_is_still_pruned():
74 """The exemption must be scoped, not a blanket floor removal."""
75 items = _annotate(_mixed_batch() + [_x_item("5", "spam_acct", 0.02, {"likes": 0})])
76 kept = signals.prune_low_relevance(items, first_party_handles={"steipete"})
77 assert all(i.author != "spam_acct" for i in kept)
78
79
80 def test_batch_minimum_is_not_treated_as_zero_engagement():
81 """`normalize` maps the batch minimum to exactly 0, so an item with real
82 engagement was being given the stricter 1.5x social threshold purely for
83 being the least-engaged item present."""
84 items = _annotate([
85 _x_item("1", "acct_a", 0.20, {"likes": 500, "reposts": 40}),
86 _x_item("2", "acct_b", 0.20, {"likes": 5000, "reposts": 400}),
87 ])
88 least = next(i for i in items if i.author == "acct_a")
89 assert least.engagement_score == 0, "precondition: min-max maps batch min to 0"
90 kept = signals.prune_low_relevance(items)
91 assert any(i.author == "acct_a" for i in kept), (
92 "an item with 500 likes was pruned by the zero-engagement gate purely "
93 "because it was the batch minimum"
94 )
95
96
97 def test_genuinely_zero_engagement_still_gets_stricter_threshold():
98 """The stricter gate must survive for real zero-engagement social noise."""
99 items = _annotate([
100 _x_item("1", "acct_a", 0.20, {"likes": 0, "reposts": 0}),
101 _x_item("2", "acct_b", 0.90, {"likes": 5000, "reposts": 400}),
102 ])
103 kept = signals.prune_low_relevance(items)
104 assert all(i.author != "acct_a" for i in kept), (
105 "a genuinely zero-engagement item at 0.20 should fail the 0.225 gate"
106 )
107
108
109 def test_all_fail_rescue_is_unchanged():
110 items = _annotate([_x_item("1", "acct_a", 0.01), _x_item("2", "acct_b", 0.02)])
111 kept = signals.prune_low_relevance(items)
112 assert len(kept) == 2, "the all-fail rescue must still return the batch"
113
114
115 def test_batch_with_no_first_party_behaves_as_before():
116 items = _annotate(_mixed_batch())
117 assert signals.prune_low_relevance(items, first_party_handles=frozenset()) == \
118 signals.prune_low_relevance(items)
119
120
121 def test_handles_are_matched_case_insensitively():
122 items = _annotate(_mixed_batch())
123 kept = signals.prune_low_relevance(items, first_party_handles={"SteiPete"})
124 assert any(i.author == "steipete" for i in kept)
125
126
127 # --- KTD8: one owner for the entity-miss predicate -------------------------
128
129 def _candidate(explanation: str, final_score: float, author: str = "someone"):
130 url = f"https://x.com/{author}/status/1"
131 cand = schema.Candidate(
132 candidate_id="c1",
133 item_id="i1",
134 source="x",
135 title="t",
136 url=url,
137 snippet="s",
138 subquery_labels=["primary"],
139 native_ranks={"primary:x": 1},
140 local_relevance=0.0,
141 freshness=80,
142 engagement=50,
143 source_quality=0.68,
144 rrf_score=0.02,
145 )
146 cand.source_items = [
147 schema.SourceItem(
148 item_id="i1", source="x", title="t", body="b", url=url, author=author,
149 )
150 ]
151 cand.explanation = explanation
152 cand.final_score = final_score
153 return cand
154
155
156 def test_render_delegates_to_shared_predicate():
157 """render must not carry its own copy of the entity-miss test."""
158 from lib import render, rerank
159 cand = _candidate("fallback-local-score (entity-miss demotion)", 40.0)
160 assert render._best_take_relevance_ok(cand) is rerank.candidate_relevance_ok(cand)
161 ok = _candidate("llm-scored", 40.0)
162 assert render._best_take_relevance_ok(ok) is rerank.candidate_relevance_ok(ok)
163
164
165 def test_shared_predicate_rejects_entity_miss_and_zero_score():
166 from lib import rerank
167 assert not rerank.candidate_relevance_ok(
168 _candidate("fallback-local-score (entity-miss demotion)", 40.0)
169 )
170 assert not rerank.candidate_relevance_ok(_candidate("llm-scored", 0.0))
171 assert rerank.candidate_relevance_ok(_candidate("llm-scored", 40.0))
172
173
174 def test_first_party_carveout_reaches_render_side_gate():
175 """The measured KTD8 failure: a first-party post demoted on the LLM path
176 was floored by rerank but still discarded at render because the render-side
177 copy re-tested the explanation string."""
178 from lib import render, rerank
179 cand = _candidate("fallback-local-score (entity-miss demotion)", 0.0, author="steipete")
180 assert not render._best_take_relevance_ok(cand), "precondition: demoted before the floor runs"
181 rerank._apply_first_party_floor([cand], resolved_handles={"steipete"})
182 assert cand.final_score >= rerank.FIRST_PARTY_FLOOR
183 assert render._best_take_relevance_ok(cand), (
184 "first-party carve-out applied in rerank did not propagate to the "
185 "render-side relevance gate"
186 )
187
188
189 def test_non_first_party_demotion_survives_the_floor_pass():
190 from lib import render, rerank
191 cand = _candidate("fallback-local-score (entity-miss demotion)", 0.0, author="rando")
192 rerank._apply_first_party_floor([cand], resolved_handles={"steipete"})
193 assert not render._best_take_relevance_ok(cand), (
194 "an off-topic collision post must stay buried"
195 )
196
197
198 # --- Phase 1 / quick-depth wiring (Greptile) --------------------------------
199
200 @pytest.mark.parametrize("handle_in_topic", [False, True])
201 def test_pipeline_deferred_floor_keeps_subject_and_prunes_unrelated_account(handle_in_topic):
202 topic = "@steipete research" if handle_in_topic else "Peter Steinberger research"
203 raw = [
204 {"id": "subject", "author_handle": "steipete", "text": "Shipped another update",
205 "url": "https://x.com/steipete/status/1", "date": "2026-03-15",
206 "engagement": {"likes": 50}},
207 {"id": "noise", "author_handle": "rando_acct", "text": "Banana bread recipe",
208 "url": "https://x.com/rando_acct/status/2", "date": "2026-03-15",
209 "engagement": {"likes": 50}},
210 {"id": "relevant", "author_handle": "observer", "text": f"{topic} evaluation results",
211 "url": "https://x.com/observer/status/3", "date": "2026-03-15",
212 "engagement": {"likes": 50}},
213 ]
214 with patch.object(pipeline, "_retrieve_stream", return_value=(raw, {})), \
215 patch.object(pipeline, "weighted_rrf", wraps=pipeline.weighted_rrf) as fuse:
216 report = pipeline.run(
217 topic=topic, x_handle=None if handle_in_topic else "steipete",
218 config={}, depth="quick", mock=True, requested_sources=["x"],
219 web_backend="none", as_of_date="2026-03-31",
220 )
221 streams = fuse.call_args.args[0]
222 assert {item.item_id for stream in streams.values() for item in stream} == {"subject", "relevant"}
223 assert {item.item_id for candidate in report.ranked_candidates
224 for item in candidate.source_items} == {"subject", "relevant"}
225
226
227 def test_related_handles_lane_gets_the_exemption():
228 import inspect
229 from lib import pipeline
230 src = inspect.getsource(pipeline._run_supplemental_searches)
231 assert "first_party_handles=related_handles," in src
232
233
234 def test_quick_run_without_an_explicit_handle_still_protects_the_subject():
235 """The gap in the first fix: covering only user-typed handles does nothing
236 for a quick run, where nobody typed one and Phase 2's automatic resolution
237 never executes."""
238 from lib import pipeline
239 candidates = pipeline._topic_first_party_candidates("Peter Steinberger steipete")
240 assert "steipete" in candidates
241
242 items = _annotate(_mixed_batch())
243 kept = signals.prune_low_relevance(items, first_party_handles=candidates)
244 assert any(i.author == "steipete" for i in kept), (
245 "a quick search naming the subject must not discard what they wrote"
246 )
247
248
249 def test_topic_candidates_include_explicit_mentions():
250 from lib import pipeline
251 assert "getenergy_" in pipeline._topic_first_party_candidates("@GetEnergy_ launch")
252
253
254 def test_topic_candidates_exclude_stopwords():
255 from lib import pipeline
256 got = pipeline._topic_first_party_candidates("the best of the year")
257 assert "the" not in got and "of" not in got
258
259
260 def test_topic_candidates_exclude_query_scaffolding_words():
261 """Words like "review" or "news" describe the search, not the subject, so an
262 account that happens to be named after one must not get first-party status
263 (rerank._handle_is_topic already excludes the same words)."""
264 from lib import pipeline
265 got = pipeline._topic_first_party_candidates("Cursor review latest news")
266 assert "cursor" in got
267 assert not {"review", "latest", "news"} & got
268
269
270 def test_topic_candidates_do_not_exempt_unrelated_authors():
271 """Candidates only matter when a post's author matches one, so ordinary
272 words cost nothing -- no account is named 'lunch'."""
273 from lib import pipeline
274 candidates = pipeline._topic_first_party_candidates("bentgo lunch boxes")
275 items = _annotate(_mixed_batch() + [_x_item("9", "spam_acct", 0.01, {"likes": 0})])
276 kept = signals.prune_low_relevance(items, first_party_handles=candidates)
277 assert all(i.author != "spam_acct" for i in kept)
278
279
280 def test_topic_candidates_are_unioned_into_the_explicit_set():
281 import inspect
282 from lib import pipeline
283 src = inspect.getsource(pipeline.run)
284 assert "_topic_first_party_candidates(topic)" in src
285 build = src.index("explicit_first_party")
286 use = src.index("first_party_handles=explicit_first_party,")
287 assert build < use
288
289
290 def test_name_only_topic_resolves_the_subject_from_mentions():
291 """The hard case: search "Peter Steinberger" with no handle anywhere. His
292 handle is @steipete, which matches no topic token, and Phase 2's resolution
293 has not run. Posts *about* him mention him, which is the signal the engine
294 already uses -- just later than the prune."""
295 from lib import pipeline
296 raw = [
297 {"text": "Great thread from @steipete on agent loops"},
298 {"text": "@steipete nailed this one"},
299 {"text": "watching @steipete build in public is wild"},
300 {"text": "unrelated chatter with no mention"},
301 ]
302 assert "steipete" in pipeline._batch_subject_handles(raw)
303
304
305 def test_batch_subject_keys_on_mentions_not_authors():
306 """A prolific commentator inflates author counts; being mentioned by other
307 accounts is what identifies the subject."""
308 from lib import pipeline
309 raw = [
310 {"author_handle": "spam_acct", "text": "buy now"},
311 {"author_handle": "spam_acct", "text": "buy now again"},
312 {"author_handle": "spam_acct", "text": "and again"},
313 {"author_handle": "someone", "text": "actually useful thread by @realsubject"},
314 ]
315 got = pipeline._batch_subject_handles(raw)
316 assert "spam_acct" not in got
317 assert "realsubject" in got
318
319
320 def test_batch_subject_is_capped():
321 from lib import pipeline
322 raw = [{"text": f"@acct{i} said something"} for i in range(10)]
323 assert len(pipeline._batch_subject_handles(raw)) <= 2
324
325
326 def test_batch_subject_is_empty_without_mentions():
327 from lib import pipeline
328 assert pipeline._batch_subject_handles([{"text": "no mentions here"}]) == set()
329 assert pipeline._batch_subject_handles([]) == set()
330
331
332 def test_batch_inference_is_unioned_not_gated():
333 """Regression: gating this on "no handles supplied" made it dead code.
334
335 The caller's set is derived partly from topic tokens, so it is non-empty
336 for essentially every real topic -- a fallback would never fire and the
337 name-only case would stay broken while looking fixed.
338 """
339 import inspect
340 from lib import pipeline
341 src = inspect.getsource(pipeline._normalize_score_dedupe)
342 assert "floor_handles |= _batch_subject_handles(raw_items)" in src
343 assert "not floor_handles" not in src, (
344 "batch inference must union, never gate on an empty supplied set"
345 )
346
347
348 def test_name_only_topic_keeps_subject_posts_end_to_end():
349 """The full path: topic names a person, handle appears nowhere in it, and
350 the subject's own zero-relevance posts still survive the floor."""
351 from lib import pipeline
352 supplied = pipeline._topic_first_party_candidates("Peter Steinberger")
353 assert "steipete" not in supplied, "precondition: the handle is not in the topic"
354 raw = [
355 {"text": "Great thread from @steipete on agent loops"},
356 {"text": "@steipete nailed this"},
357 {"text": "more praise for @steipete"},
358 ]
359 inferred = pipeline._batch_subject_handles(raw)
360 items = _annotate(_mixed_batch())
361 kept = signals.prune_low_relevance(
362 items, first_party_handles=supplied | inferred
363 )
364 assert any(i.author == "steipete" for i in kept)
365
366
367 # --- ordering fix: prune X after resolution, not before ---------------------
368
369 def test_x_defers_its_relevance_floor_past_resolution():
370 """The root ordering bug: X was pruned before the run knew who the subject
371 was, so the floor could not exempt an author nobody had identified yet. No
372 amount of guessing at prune time substitutes for knowing."""
373 import inspect
374 from lib import pipeline
375 src = inspect.getsource(pipeline.run)
376 assert 'defer_relevance_prune=(source == "x")' in src
377
378
379 def test_deferred_prune_runs_after_resolution_and_before_fusion():
380 import inspect
381 from lib import pipeline
382 src = inspect.getsource(pipeline.run)
383 resolve_at = src.index("resolved_handles = explicit_first_party")
384 prune_at = src.index("Deferred X relevance floor")
385 fuse_at = src.index("candidates = weighted_rrf(")
386 assert resolve_at < prune_at < fuse_at, (
387 "the deferred floor must see resolved handles and still run before fusion"
388 )
389
390
391 def test_deferred_prune_reaches_the_report_not_just_fusion():
392 """The floor must run before the per-source view is finalized. Pruning only
393 the fusion streams left report.items_by_source and the X source_status
394 count describing the pre-floor pool."""
395 from unittest.mock import patch
396
397 from lib import dates, pipeline
398
399 day = dates.get_date_range(2)[0]
400
401 def _raw(item_id, author, text, likes):
402 return {
403 "id": item_id,
404 "text": text,
405 "url": f"https://x.com/{author}/status/{item_id}",
406 "author_handle": author,
407 "date": day,
408 "engagement": {"likes": likes, "reposts": 0, "replies": 0, "quotes": 0},
409 "relevance": 0.5,
410 "why_relevant": "test",
411 }
412
413 raw_items = [
414 _raw("1", "steipete", "unrelated lunch photo", 500),
415 _raw("2", "dev_a", "agent loops are great, agent loops everywhere", 300),
416 _raw("3", "dev_b", "agent loops need better evals", 200),
417 _raw("4", "spam_acct", "buy cheap watches now", 0),
418 ]
419 plan = {
420 "intent": "general",
421 "freshness_mode": "balanced_recent",
422 "cluster_mode": "story",
423 "subqueries": [
424 {
425 "label": "primary",
426 "search_query": "agent loops",
427 "ranking_query": "agent loops",
428 "sources": ["x"],
429 }
430 ],
431 "source_weights": {"x": 1.0},
432 }
433 with patch("lib.pipeline._retrieve_stream_impl", return_value=(raw_items, {})):
434 report = pipeline.run(
435 topic="agent loops",
436 config={},
437 depth="quick",
438 requested_sources=["x"],
439 mock=True,
440 x_handle="steipete",
441 external_plan=plan,
442 )
443
444 authors = {item.author for item in report.items_by_source["x"]}
445 assert "steipete" in authors, "first-party post must survive the floor"
446 assert "spam_acct" not in authors, "the floor must reach the report's per-source view"
447 assert report.source_status["x"].items_returned == len(report.items_by_source["x"])
448
449
450 def test_non_x_sources_still_prune_in_place():
451 """Only X defers; everything else keeps its existing behavior."""
452 import inspect
453 from lib import pipeline
454 src = inspect.getsource(pipeline._normalize_score_dedupe)
455 assert 'if source != "jobs" and not defer_relevance_prune:' in src
456
457
458 def test_deferred_prune_still_drops_off_topic_posts():
459 """Deferring must not mean skipping."""
460 items = _annotate(_mixed_batch() + [_x_item("9", "spam_acct", 0.01, {"likes": 0})])
461 kept = signals.prune_low_relevance(items, first_party_handles={"steipete"})
462 assert any(i.author == "steipete" for i in kept)
463 assert all(i.author != "spam_acct" for i in kept)
464
465
466 # --- unresolved subject policy: skip X floor when no real handle identified ---
467
468 def test_topic_handle_mentions_extracts_only_at_mentions():
469 """@mentions in the topic are real handles; regular words are not."""
470 from lib import pipeline
471 assert pipeline._topic_handle_mentions("Peter Steinberger @steipete") == {"steipete"}
472 assert pipeline._topic_handle_mentions("Peter Steinberger") == set()
473 assert pipeline._topic_handle_mentions("@GetEnergy_ launch") == {"getenergy_"}
474
475
476 def test_topic_handle_mentions_is_case_insensitive():
477 from lib import pipeline
478 assert pipeline._topic_handle_mentions("@SteiPete") == {"steipete"}
479
480
481 def test_entity_topic_no_handle_no_discovery_skips_x_floor():
482 """Policy: when the subject cannot be identified, skip the X floor entirely.
483
484 Entity-shaped topic, no --x-handle, auto-resolve/Phase 2 return nothing.
485 Retrieved X items include a zero-relevance post whose author is not a
486 topic token. That post survives prune because the floor is not applied.
487 A companion on-topic post is in the batch so the all-fail rescue cannot
488 hide an incorrectly applied floor.
489 """
490 from unittest.mock import patch
491 from lib import pipeline
492
493 topic = "Peter Steinberger"
494 assert pipeline._topic_handle_mentions(topic) == set()
495 topic_tokens = pipeline._topic_first_party_candidates(topic)
496 assert "peter" in topic_tokens and "steinberger" in topic_tokens
497 assert "rando_acct" not in topic_tokens
498
499 raw_items = [
500 {
501 "id": "1",
502 "text": "shipping a new agent loop tonight",
503 "url": "https://x.com/rando_acct/status/1",
504 "author_handle": "rando_acct",
505 "date": "2026-08-01",
506 "engagement": {"likes": 0, "reposts": 0, "replies": 0},
507 },
508 {
509 "id": "2",
510 "text": "Peter Steinberger just shipped another agent demo",
511 "url": "https://x.com/third_acct/status/2",
512 "author_handle": "third_acct",
513 "date": "2026-08-01",
514 "engagement": {"likes": 50, "reposts": 5, "replies": 2},
515 },
516 ]
517 plan = {
518 "intent": "person",
519 "freshness_mode": "balanced_recent",
520 "cluster_mode": "topic",
521 "subqueries": [{
522 "label": "primary",
523 "search_query": topic,
524 "ranking_query": topic,
525 "sources": ["x"],
526 }],
527 "source_weights": {"x": 1.0},
528 }
529
530 def fake_retrieve(**kwargs):
531 if kwargs.get("source") == "x":
532 return raw_items, {}
533 return [], {}
534
535 with patch("lib.pipeline._retrieve_stream", side_effect=lambda **kw: fake_retrieve(**kw)):
536 report = pipeline.run(
537 topic=topic,
538 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
539 depth="quick",
540 requested_sources=["x"],
541 mock=True,
542 external_plan=plan,
543 as_of_date="2026-08-14",
544 )
545
546 x_items = report.items_by_source.get("x") or []
547 authors = {item.author for item in x_items}
548 assert "rando_acct" in authors, (
549 "unresolved subject policy: skip X floor when no real handle identified; "
550 "the zero-relevance post whose author is not a topic token must survive"
551 )
552
553
554 def test_entity_topic_with_at_mention_applies_x_floor():
555 """When the topic DOES include @mentions, the X floor applies normally."""
556 from lib import pipeline
557
558 topic = "Peter Steinberger @steipete"
559 explicit_x_handles = pipeline._topic_handle_mentions(topic)
560 supplemental_handles = []
561
562 assert "steipete" in explicit_x_handles, (
563 "precondition: @mention is a real handle"
564 )
565
566 real_x_handles = explicit_x_handles | {
567 h.lstrip("@").strip().lower() for h in supplemental_handles if h and h.strip()
568 }
569 assert real_x_handles, "real handles were resolved"
570
571 topic_candidates = pipeline._topic_first_party_candidates(topic)
572 items = _annotate([
573 _x_item("1", "steipete", 0.0, {"likes": 100, "reposts": 10}),
574 _x_item("2", "rando_acct", 0.0, {"likes": 0, "reposts": 0}),
575 _x_item("3", "third_acct", 0.18, {"likes": 20, "reposts": 2}),
576 ])
577
578 kept = signals.prune_low_relevance(items, first_party_handles=topic_candidates | real_x_handles)
579
580 assert "steipete" in {i.author for i in kept}, (
581 "first-party posts survive the floor"
582 )
583 assert "rando_acct" not in {i.author for i in kept}, (
584 "when real handles exist, off-topic zero-relevance posts are pruned"
585 )
586
587
588 def test_explicit_x_handle_applies_x_floor():
589 """--x-handle triggers the floor even with entity-only topic."""
590 from lib import pipeline
591
592 topic = "Peter Steinberger"
593 x_handle = "steipete"
594 explicit_x_handles = {x_handle.lstrip("@").strip().lower()}
595
596 assert pipeline._topic_handle_mentions(topic) == set(), (
597 "precondition: topic has no @mentions"
598 )
599 assert explicit_x_handles == {"steipete"}, (
600 "but we have an explicit --x-handle"
601 )
602
603 topic_candidates = pipeline._topic_first_party_candidates(topic)
604 resolved_handles = topic_candidates | explicit_x_handles
605
606 items = _annotate([
607 _x_item("1", "steipete", 0.0, {"likes": 100, "reposts": 10}),
608 _x_item("2", "rando_acct", 0.0, {"likes": 0, "reposts": 0}),
609 ])
610
611 kept = signals.prune_low_relevance(items, first_party_handles=resolved_handles)
612
613 assert "steipete" in {i.author for i in kept}
614 assert "rando_acct" not in {i.author for i in kept}, (
615 "--x-handle triggers the floor, pruning off-topic posts"
616 )
617
618
619 # --- thin-source retry must not prune X before handle resolution ------------
620
621 def test_thin_retry_keeps_zero_relevance_subject_authored_x_post():
622 """Phase 1 defers the X floor; the simplified-query retry must too.
623
624 A default/deep run with fewer than three X items retries with a simpler
625 query. If that retry returns a subject-authored post that does not repeat
626 the subject's name, applying the relevance floor here (with no resolved
627 handles) discards it before it enters the bundle. The later
628 resolved-handle floor cannot recover a post that never arrived.
629 """
630 import threading
631 from unittest.mock import patch
632 from lib import pipeline
633
634 topic = "Peter Steinberger"
635 raw_items = [
636 {
637 "id": "1",
638 "text": "shipping a new agent loop tonight",
639 "url": "https://x.com/steipete/status/1",
640 "author_handle": "steipete",
641 "date": "2026-08-01",
642 "engagement": {"likes": 3466, "reposts": 128, "replies": 40},
643 },
644 {
645 "id": "2",
646 "text": "Peter Steinberger just shipped another agent demo",
647 "url": "https://x.com/third_acct/status/2",
648 "author_handle": "third_acct",
649 "date": "2026-08-01",
650 "engagement": {"likes": 50, "reposts": 5, "replies": 2},
651 },
652 ]
653 plan = schema.QueryPlan(
654 intent="person",
655 freshness_mode="balanced_recent",
656 cluster_mode="topic",
657 raw_topic=topic,
658 subqueries=[
659 schema.SubQuery(
660 label="primary",
661 search_query=topic,
662 ranking_query=topic,
663 sources=["x"],
664 )
665 ],
666 source_weights={"x": 1.0},
667 )
668 bundle = schema.RetrievalBundle()
669
670 with patch("lib.pipeline._retrieve_stream", return_value=(raw_items, {})):
671 pipeline._retry_thin_sources(
672 topic=topic,
673 bundle=bundle,
674 plan=plan,
675 config={},
676 depth="default",
677 date_range=("2026-07-15", "2026-08-14"),
678 runtime=schema.ProviderRuntime(
679 reasoning_provider="mock",
680 planner_model="mock",
681 rerank_model="mock",
682 ),
683 mock=False,
684 rate_limited_sources=set(),
685 rate_limit_lock=threading.Lock(),
686 settings=pipeline.DEPTH_SETTINGS["default"],
687 )
688
689 x_items = bundle.items_by_source.get("x") or []
690 authors = {item.author for item in x_items}
691 assert "steipete" in authors, (
692 "thin-retry X path must defer the relevance floor the way Phase 1 does; "
693 "a zero-relevance subject-authored post must survive into the bundle"
694 )
695 assert "third_acct" in authors, (
696 "precondition: the companion on-topic post cleared the floor, so the "
697 "all-fail rescue cannot hide an incorrectly applied prune"
698 )
699
699 lines PYTHON