| 1 | from dataclasses import asdict, replace |
| 2 | import threading |
| 3 | from unittest.mock import Mock, patch |
| 4 | import pytest |
| 5 | from lib import dates, entity_extract, fusion, pipeline, planner, render, rerank, schema |
| 6 | |
| 7 | |
| 8 | def plan(): |
| 9 | return schema.QueryPlan('factual', 'strict_recent', 'story', 'Alex Rowan', |
| 10 | [schema.SubQuery('primary', 'Alex Rowan Northstar Labs', 'Alex Rowan at Northstar Labs', ['x'])], |
| 11 | {'x': 1.0}, person_identity_anchors=['Northstar Labs', 'Cedar Ventures']) |
| 12 | |
| 13 | |
| 14 | def item(text, author='disclosurebot', source='x'): |
| 15 | return schema.SourceItem('i', source, text, text, 'https://example.invalid/post', |
| 16 | author=author, relevance_hint=1.0) |
| 17 | |
| 18 | |
| 19 | def candidate(evidence): |
| 20 | return schema.Candidate('c', 'i', evidence.source, evidence.title, evidence.url, |
| 21 | evidence.body, ['primary'], {'primary:x': 1}, 1.0, 100, 100000, 1.0, 1.0, |
| 22 | source_items=[evidence]) |
| 23 | |
| 24 | |
| 25 | @pytest.mark.parametrize('text,author,source,expected', [ |
| 26 | ('Alex Rowan resigns as Alloy Works secretary', 'disclosurebot', 'x', False), |
| 27 | ('Alex Rowan joins NORTHSTAR LABS', 'reporter', 'x', True), |
| 28 | ('Alex Rowan joins Cedar Ventures', 'reporter', 'x', True), |
| 29 | ('Northstar Labsmith sponsors Alex Rowan', 'reporter', 'x', False), |
| 30 | ('Shipping today', 'alex_founder', 'x', True), |
| 31 | ('Shipping today', 'alex_founder', 'reddit', False), |
| 32 | ('Alex Rowan resigns', 'partner', 'x', False), |
| 33 | ]) |
| 34 | def test_identity_gate(text, author, source, expected): |
| 35 | assert entity_extract.matches_person_identity(item(text, author, source), |
| 36 | plan().person_identity_anchors, 'alex_founder') is expected |
| 37 | |
| 38 | |
| 39 | @pytest.mark.parametrize('hosted', [False, True]) |
| 40 | def test_wrong_person_cannot_rank_even_with_high_scores_or_related_author(hosted): |
| 41 | provider = Mock() if hosted else None |
| 42 | wrong = candidate(item('Alex Rowan resigns as Alloy Works secretary', 'partner')) |
| 43 | ranked = rerank.rerank_candidates(topic='Alex Rowan', plan=plan(), candidates=[wrong], |
| 44 | provider=provider, model='fake' if hosted else None, shortlist_size=10, |
| 45 | resolved_handles={'alex_founder', 'partner'}, primary_handle='alex_founder') |
| 46 | assert ranked == [] |
| 47 | if hosted: |
| 48 | provider.generate_json.assert_not_called() |
| 49 | |
| 50 | |
| 51 | def test_qualified_and_first_party_evidence_survives_fallback(): |
| 52 | for evidence in [item('Alex Rowan at Northstar Labs'), item('Shipping today', 'alex_founder')]: |
| 53 | assert rerank.rerank_candidates(topic='Alex Rowan', plan=plan(), |
| 54 | candidates=[candidate(evidence)], provider=None, model=None, shortlist_size=10, |
| 55 | resolved_handles={'alex_founder'}, primary_handle='alex_founder') |
| 56 | |
| 57 | |
| 58 | def test_plan_roundtrip_and_validation(): |
| 59 | original = plan() |
| 60 | assert schema.query_plan_from_dict(asdict(original)) == original |
| 61 | raw = asdict(original) |
| 62 | planner.validate_external_plan(raw) |
| 63 | sanitized = planner._sanitize_plan(raw, topic='Alex Rowan', depth='default', |
| 64 | available_sources=['x'], requested_sources=['x']) |
| 65 | assert sanitized.person_identity_anchors == original.person_identity_anchors |
| 66 | for invalid in ['Northstar Labs', None, [123], [''], ['!!!']]: |
| 67 | raw['person_identity_anchors'] = invalid |
| 68 | with pytest.raises(ValueError, match='person_identity_anchors'): |
| 69 | planner.validate_external_plan(raw) |
| 70 | |
| 71 | |
| 72 | @pytest.mark.parametrize('malformed,expected', [ |
| 73 | (None, []), ('Northstar Labs', []), (['Northstar Labs', '', 123], ['Northstar Labs']), |
| 74 | ]) |
| 75 | def test_internal_planner_keeps_plan_when_anchors_are_malformed(malformed, expected): |
| 76 | raw = asdict(plan()) |
| 77 | raw['person_identity_anchors'] = malformed |
| 78 | sanitized = planner._sanitize_plan(raw, topic='Alex Rowan', depth='default', |
| 79 | available_sources=['x'], requested_sources=['x']) |
| 80 | assert sanitized.subqueries |
| 81 | assert sanitized.person_identity_anchors == expected |
| 82 | |
| 83 | |
| 84 | def test_namesake_does_not_expand_x_targets(): |
| 85 | bundle = schema.RetrievalBundle() |
| 86 | bundle.items_by_source['x'] = [ |
| 87 | item('Alex Rowan resigns as Alloy Works secretary @alloynews'), |
| 88 | item('Alex Rowan at Northstar Labs', 'qualified'), |
| 89 | ] |
| 90 | with patch.object(entity_extract, 'extract_entities', wraps=entity_extract.extract_entities) as extract: |
| 91 | # Stop immediately after extraction; no network calls or real accounts. |
| 92 | extract.side_effect = lambda reddit, posts, **kw: (_ for _ in ()).throw(StopIteration(posts)) |
| 93 | with pytest.raises(StopIteration) as exc: |
| 94 | pipeline._run_supplemental_searches(topic='Alex Rowan', bundle=bundle, plan=plan(), |
| 95 | config={}, depth='default', date_range=('2026-10-01', '2026-10-22'), |
| 96 | runtime=schema.ProviderRuntime('local', '', '', x_search_backend='bird'), |
| 97 | mock=False, rate_limited_sources=set(), rate_limit_lock=threading.Lock(), |
| 98 | x_handle='alex_founder') |
| 99 | assert [post['author_handle'] for post in exc.value.args[0]] == ['qualified'] |
| 100 | |
| 101 | |
| 102 | def test_unscoped_plan_is_compatible(): |
| 103 | legacy_payload = asdict(plan()) |
| 104 | del legacy_payload['person_identity_anchors'] |
| 105 | planner.validate_external_plan(legacy_payload) |
| 106 | legacy_plan = schema.query_plan_from_dict(legacy_payload) |
| 107 | assert legacy_plan.person_identity_anchors == [] |
| 108 | evidence = item('Alex Rowan resigns as Alloy Works secretary') |
| 109 | assert entity_extract.matches_person_identity(evidence, []) |
| 110 | assert rerank.rerank_candidates(topic='Alex Rowan', plan=legacy_plan, |
| 111 | candidates=[candidate(evidence)], provider=None, model=None, shortlist_size=10) |
| 112 | |
| 113 | |
| 114 | @pytest.mark.parametrize('thin_first', [False, True]) |
| 115 | def test_fusion_keeps_qualified_article_without_unqualified_submission(thin_first): |
| 116 | qualified = item('Alex Rowan at Northstar Labs', source='grounding') |
| 117 | thin = item('Alex Rowan update', source='hackernews') |
| 118 | thin.engagement_score = 100000 |
| 119 | qualified.engagement_score = 10 |
| 120 | streams = [(('primary', 'grounding'), [qualified]), (('primary', 'hackernews'), [thin])] |
| 121 | if thin_first: |
| 122 | streams.reverse() |
| 123 | scoped_plan = plan() |
| 124 | scoped_plan.subqueries[0] = replace(scoped_plan.subqueries[0], sources=['grounding', 'hackernews']) |
| 125 | candidates = fusion.weighted_rrf(dict(streams), scoped_plan, pool_limit=10) |
| 126 | assert len(candidates) == 1 |
| 127 | assert candidates[0].source_items == [qualified] |
| 128 | assert candidates[0].source == 'grounding' |
| 129 | assert candidates[0].engagement == 10 |
| 130 | assert rerank.rerank_candidates(topic='Alex Rowan', plan=scoped_plan, |
| 131 | candidates=candidates, provider=None, model=None, shortlist_size=10) |
| 132 | |
| 133 | |
| 134 | @pytest.mark.parametrize('metadata', [ |
| 135 | {'transcript_snippet': 'Alex Rowan at Northstar Labs'}, |
| 136 | {'transcript_highlights': ['Alex Rowan at Northstar Labs']}, |
| 137 | {'top_comments': [{'excerpt': 'Alex Rowan at Northstar Labs'}]}, |
| 138 | {'top_comments': [{'text': 'Alex Rowan at Northstar Labs'}]}, |
| 139 | {'top_comments': ['Alex Rowan at Northstar Labs']}, |
| 140 | {'comment_insights': ['Alex Rowan at Northstar Labs']}, |
| 141 | ]) |
| 142 | def test_readable_metadata_identity_anchors_are_retained(metadata): |
| 143 | evidence = item('Alex Rowan interview', source='youtube') |
| 144 | evidence.metadata = metadata |
| 145 | assert entity_extract.matches_person_identity(evidence, plan().person_identity_anchors) |
| 146 | assert rerank.rerank_candidates(topic='Alex Rowan', plan=plan(), |
| 147 | candidates=[candidate(evidence)], provider=None, model=None, shortlist_size=10) |
| 148 | |
| 149 | |
| 150 | def test_nonreadable_metadata_cannot_supply_identity(): |
| 151 | evidence = item('Alex Rowan interview', source='youtube') |
| 152 | evidence.metadata = {'thumbnail_url': 'Northstar Labs', 'transcript_highlights': [123]} |
| 153 | assert not entity_extract.matches_person_identity(evidence, plan().person_identity_anchors) |
| 154 | |
| 155 | |
| 156 | @pytest.mark.parametrize('primary_handle,expected', [(None, False), ('alex_founder', True), ('partner', False)]) |
| 157 | def test_fusion_only_exempts_explicit_x_subject(primary_handle, expected): |
| 158 | evidence = item('Shipping today', author='alex_founder') |
| 159 | candidates = fusion.weighted_rrf({('primary', 'x'): [evidence]}, plan(), pool_limit=10, |
| 160 | primary_handle=primary_handle, first_party_handles={'alex_founder', 'partner'}) |
| 161 | assert bool(candidates) is expected |
| 162 | |
| 163 | |
| 164 | def test_anchored_run_drops_namesakes_from_footer_counts_and_top_voices(): |
| 165 | def reddit_thread(item_id, title, subreddit): |
| 166 | return {'id': item_id, 'title': title, 'subreddit': subreddit, |
| 167 | 'url': f'https://reddit.com/r/{subreddit}/comments/{item_id}', |
| 168 | 'date': dates.get_date_range(5)[0], 'selftext': title, |
| 169 | 'engagement': {'score': 300, 'num_comments': 40, 'upvote_ratio': 0.9}, |
| 170 | 'relevance': 0.9, 'why_relevant': 'fixture'} |
| 171 | |
| 172 | threads = [reddit_thread('R1', 'Pace Capital leads the Infisical seed round', 'venturecapital'), |
| 173 | reddit_thread('R2', 'Pace Morby creative finance playbook', 'realestateinvesting')] |
| 174 | with patch.object(pipeline, 'available_sources', return_value=['reddit']), \ |
| 175 | patch.object(pipeline, '_retrieve_stream', return_value=(threads, {})), \ |
| 176 | patch.object(pipeline, '_retry_thin_sources'): |
| 177 | report = pipeline.run(topic='Pace Capital', config={}, depth='quick', |
| 178 | requested_sources=['reddit'], web_backend='none', external_plan={ |
| 179 | 'intent': 'research', 'freshness_mode': 'balanced_recent', 'cluster_mode': 'topic', |
| 180 | 'subqueries': [{'label': 'primary', 'search_query': 'Pace Capital', |
| 181 | 'ranking_query': 'What is Pace Capital, the VC firm, doing?', |
| 182 | 'sources': ['reddit']}], |
| 183 | 'person_identity_anchors': ['Pace Capital']}) |
| 184 | assert [i.container for i in report.items_by_source['reddit']] == ['venturecapital'] |
| 185 | assert report.source_status['reddit'].items_returned == 1 |
| 186 | assert 'realestateinvesting' not in render._top_voices_footer_line(report) |
| 187 | |
| 188 | |
| 189 | # -- person runs --------------------------------------------------------------- |
| 190 | |
| 191 | PERSON = 'Dana Okafor' |
| 192 | PERSON_PLAN = { |
| 193 | 'intent': 'research', 'freshness_mode': 'balanced_recent', 'cluster_mode': 'topic', |
| 194 | 'subqueries': [{'label': 'primary', 'search_query': PERSON, |
| 195 | 'ranking_query': f'What has {PERSON} done lately?', |
| 196 | 'sources': ['grounding']}], |
| 197 | } |
| 198 | NAMESAKE_URL = 'https://food.example/lisbon/dana-okafor-bistro' |
| 199 | NEWS_URL = 'https://news.example/freight/dana-okafor-coo' |
| 200 | |
| 201 | |
| 202 | def _person_ctx(**overrides): |
| 203 | from lib import person |
| 204 | ctx = person.PersonContext(full_name=PERSON, employer_name='Northwind Freight', |
| 205 | employer_domain='northwind.example', |
| 206 | anchors=['Northwind Freight', 'northwind.example'], linkedin_status='no key') |
| 207 | for key, value in overrides.items(): |
| 208 | setattr(ctx, key, value) |
| 209 | return ctx |
| 210 | |
| 211 | |
| 212 | def _web(url, title, snippet): |
| 213 | return {'title': title, 'snippet': snippet, 'url': url, |
| 214 | 'date': dates.get_date_range(5)[0], 'relevance': 0.9} |
| 215 | |
| 216 | |
| 217 | NAMESAKE = _web(NAMESAKE_URL, 'Dana Okafor opens a new bistro in Lisbon', |
| 218 | 'Chef Dana Okafor brings her tasting menu to the old town.') |
| 219 | NEWS = _web(NEWS_URL, 'Dana Okafor named COO at Northwind Freight', |
| 220 | 'Northwind Freight promoted Dana Okafor to chief operating officer.') |
| 221 | |
| 222 | |
| 223 | def _person_run(config, web_items, *, github_user=None, github_items=()): |
| 224 | def retrieve(*_args, source=None, **_kwargs): |
| 225 | return (list(web_items), {}) if source == 'grounding' else ([], {}) |
| 226 | |
| 227 | plan = PERSON_PLAN |
| 228 | run_config = dict(config) |
| 229 | if github_user: |
| 230 | run_config.setdefault('GITHUB_TOKEN', 'dummy-token') |
| 231 | plan = { |
| 232 | **PERSON_PLAN, |
| 233 | 'subqueries': [ |
| 234 | {**sq, 'sources': [*sq['sources'], 'github']} |
| 235 | for sq in PERSON_PLAN['subqueries'] |
| 236 | ], |
| 237 | } |
| 238 | with patch.object(pipeline, '_retrieve_stream', side_effect=retrieve), \ |
| 239 | patch.object(pipeline, '_retry_thin_sources'), \ |
| 240 | patch.object(pipeline.github, 'enrich_candidates_with_stars'), \ |
| 241 | patch.object(pipeline.github, 'search_github_person', return_value=list(github_items)): |
| 242 | return pipeline.run(topic=PERSON, config=run_config, depth='quick', |
| 243 | requested_sources=['grounding', 'github'], web_backend='brave', |
| 244 | external_plan=plan, github_user=github_user) |
| 245 | |
| 246 | |
| 247 | def _urls(report, source): |
| 248 | return [i.url for i in report.items_by_source.get(source, [])] |
| 249 | |
| 250 | |
| 251 | def test_person_run_drops_and_counts_a_namesake_and_keeps_the_anchored_article(): |
| 252 | ctx = _person_ctx() |
| 253 | report = _person_run({'_person': ctx}, [NAMESAKE, NEWS]) |
| 254 | assert _urls(report, 'grounding') == [NEWS_URL] |
| 255 | assert NAMESAKE_URL not in {c.url for c in report.ranked_candidates} |
| 256 | assert NEWS_URL in {c.url for c in report.ranked_candidates} |
| 257 | assert report.artifacts['person_profile']['dropped_counts'] == {'grounding': 1} |
| 258 | assert report.query_plan.person_run is True |
| 259 | assert report.query_plan.person_identity_anchors == ['Northwind Freight', 'northwind.example'] |
| 260 | |
| 261 | |
| 262 | def test_person_anchors_join_host_plan_anchors_once_ignoring_case(): |
| 263 | ctx = _person_ctx() |
| 264 | plan_with_anchors = {**PERSON_PLAN, 'person_identity_anchors': ['NORTHWIND FREIGHT', 'Cedar Ventures']} |
| 265 | with patch.object(pipeline, '_retrieve_stream', return_value=([], {})), \ |
| 266 | patch.object(pipeline, '_retry_thin_sources'): |
| 267 | report = pipeline.run(topic=PERSON, config={'_person': ctx}, depth='quick', |
| 268 | requested_sources=['grounding'], web_backend='brave', external_plan=plan_with_anchors) |
| 269 | assert report.query_plan.person_identity_anchors == [ |
| 270 | 'NORTHWIND FREIGHT', 'Cedar Ventures', 'northwind.example'] |
| 271 | |
| 272 | |
| 273 | def test_freemail_only_person_run_drops_the_namesake_and_keeps_first_party_activity(): |
| 274 | ctx = _person_ctx(employer_name='', employer_domain='', anchors=[], identity_weak=True) |
| 275 | commit = {'id': 'GH1', 'title': 'dokafor/route-planner: add dock scheduling', 'snippet': '', |
| 276 | 'url': 'https://github.com/dokafor/route-planner/pull/7', 'author': 'dokafor', |
| 277 | 'container': 'dokafor/route-planner', 'date': dates.get_date_range(3)[0], |
| 278 | 'relevance': 0.9} |
| 279 | report = _person_run({'_person': ctx}, [NAMESAKE], github_user='dokafor', github_items=[commit]) |
| 280 | assert _urls(report, 'grounding') == [] |
| 281 | assert _urls(report, 'github') == [commit['url']] |
| 282 | assert report.artifacts['person_profile']['dropped_counts'] == {'grounding': 1} |
| 283 | assert report.artifacts['person_profile']['first_party_in_window'] == 1 |
| 284 | |
| 285 | |
| 286 | def test_non_person_run_without_anchors_keeps_the_namesake(): |
| 287 | report = _person_run({}, [NAMESAKE]) |
| 288 | assert _urls(report, 'grounding') == [NAMESAKE_URL] |
| 289 | assert 'person_profile' not in report.artifacts |
| 290 | assert report.query_plan.person_run is False |
| 291 | |
| 292 | |
| 293 | def test_marked_first_party_post_passes_without_employer_text(): |
| 294 | post = item('Kicking off the winter peak plan with the dispatch team.', PERSON, 'linkedin_profile') |
| 295 | post.metadata = {'identity_anchor': True, 'is_reshare': False} |
| 296 | assert entity_extract.matches_person_identity(post, ['Northwind Freight'], person_run=True) |
| 297 | assert entity_extract.matches_person_identity(post, [], person_run=True) |
| 298 | |
| 299 | |
| 300 | @pytest.mark.parametrize('anchors', [[], ['Northwind Freight']]) |
| 301 | def test_person_run_gate_drops_unmarked_name_only_items(anchors): |
| 302 | namesake = item('Chef Dana Okafor opens a bistro in Lisbon', 'foodnews', 'grounding') |
| 303 | assert not entity_extract.matches_person_identity(namesake, anchors, person_run=True) |
| 304 | assert entity_extract.matches_person_identity(namesake, []) |
| 305 | |
| 306 | |
| 307 | def test_person_run_gate_keeps_the_resolved_x_subject_with_no_anchors(): |
| 308 | post = item('Shipping the new dock schedule today', 'dokafor', 'x') |
| 309 | assert entity_extract.matches_person_identity(post, [], 'dokafor', person_run=True) |
| 310 | assert not entity_extract.matches_person_identity(post, [], 'someone_else', person_run=True) |
| 311 | |
| 312 | |
| 313 | def test_backfilled_transcript_anchor_passes_the_person_run_gate(): |
| 314 | video = item('Dana Okafor on last-mile logistics', 'logisticspod', 'youtube') |
| 315 | video.metadata = {'transcript_snippet': 'I run operations at Northwind Freight these days.'} |
| 316 | assert entity_extract.matches_person_identity(video, ['Northwind Freight'], person_run=True) |
| 317 | video.metadata = {} |
| 318 | assert not entity_extract.matches_person_identity(video, ['Northwind Freight'], person_run=True) |
| 319 | |
| 320 | |
| 321 | def test_rerank_and_fusion_apply_the_person_run_gate_with_no_anchors(): |
| 322 | scoped = replace(plan(), person_identity_anchors=[], person_run=True) |
| 323 | namesake = item('Chef Dana Okafor opens a bistro in Lisbon', 'foodnews') |
| 324 | assert rerank.rerank_candidates(topic=PERSON, plan=scoped, candidates=[candidate(namesake)], |
| 325 | provider=None, model=None, shortlist_size=10) == [] |
| 326 | assert fusion.weighted_rrf({('primary', 'x'): [namesake]}, scoped, pool_limit=10) == [] |
| 327 | |
| 328 | |
| 329 | def test_person_run_flag_round_trips_and_old_reports_load(): |
| 330 | scoped = replace(plan(), person_run=True) |
| 331 | assert schema.query_plan_from_dict(asdict(scoped)).person_run is True |
| 332 | legacy = asdict(plan()) |
| 333 | del legacy['person_run'] |
| 334 | assert schema.query_plan_from_dict(legacy).person_run is False |
| 335 |