返回 last30days-skill
test_pr19_bird_search_xquik.py
根目录 / tests / test_pr19_bird_search_xquik.py
1 """Regression tests for PR 19: vendored bird-search, bird_x & xquik security and lifecycle.
2
3 Covers:
4 - HIGH-150: xquik handle validation, topic query sanitization, date-window filtering, schema guards, and None/ID coercion.
5 - HIGH-156: runtime-query-ids timeouts, byte/bundle caps, allowlisted manual redirects, and SearchTimeline-only refresh.
6 - HIGH-157: fetch body timeout, byte cap, signal composition, 404 body cancel, immediate abort on network/timeout errors, and --timeout-ms.
7 - HIGH-158: atomic private (0o700/0o600) cache writes, symlink refusal, concurrent write integrity, and read-only home refresh.
8 - HIGH-159: cursor cycle detection, empty-page stop, maxPages: 0/non-finite guards, default page cap, and partial-page preservation.
9 - HIGH-160: cookies.js FROM_BROWSER=off/BROWSER_CONSENT refusal and bird_x.set_credentials clearing stale failover/keys.
10 - HIGH-161: cancel, deadline_monotonic, and capture_limit_bytes forwarding to subproc.run_with_timeout in bird_x.
11 """
12
13 from __future__ import annotations
14
15 import json
16 import os
17 import re
18 import shutil
19 import stat
20 import subprocess
21 import textwrap
22 import threading
23 import time
24 from concurrent.futures import ThreadPoolExecutor
25 from pathlib import Path
26 from unittest import mock
27 from urllib.parse import parse_qs, urlsplit
28
29 import pytest
30
31 from lib import bird_x, env, xquik
32 from lib.subproc import SubprocResult, SubprocTimeout
33
34 REPO_ROOT = Path(__file__).resolve().parents[1]
35 BIRD_DIR = REPO_ROOT / "skills" / "last30days" / "scripts" / "lib" / "vendor" / "bird-search"
36 BIRD_MJS = BIRD_DIR / "bird-search.mjs"
37 HAS_NODE = shutil.which("node") is not None
38
39
40 def _node_eval(script: str, *, env_overrides: dict[str, str | None] | None = None, timeout: float = 20) -> subprocess.CompletedProcess:
41 run_env = os.environ.copy()
42 if env_overrides:
43 for key, value in env_overrides.items():
44 if value is None:
45 run_env.pop(key, None)
46 else:
47 run_env[key] = value
48 return subprocess.run(
49 ["node", "--input-type=module", "-e", script],
50 cwd=REPO_ROOT,
51 env=run_env,
52 capture_output=True,
53 text=True,
54 timeout=timeout,
55 check=False,
56 )
57
58
59 def _register_sweet_cookie_stub(tmp_path: Path) -> Path:
60 loader = tmp_path / "sweet-cookie-loader.mjs"
61 loader.write_text(
62 textwrap.dedent(
63 """
64 export async function resolve(specifier, context, nextResolve) {
65 if (specifier === '@steipete/sweet-cookie') {
66 return { url: 'sweet-cookie-stub://mock', shortCircuit: true };
67 }
68 return nextResolve(specifier, context);
69 }
70 export async function load(url, context, nextLoad) {
71 if (url === 'sweet-cookie-stub://mock') {
72 return {
73 format: 'module',
74 shortCircuit: true,
75 source: `
76 export async function getCookies(options) {
77 process.stderr.write('SWEET_COOKIE_CALLED=' + (options.browsers?.[0] ?? 'none') + '\\n');
78 return {
79 cookies: [
80 { name: 'auth_token', value: 'stub-browser-auth-1111', domain: 'x.com' },
81 { name: 'ct0', value: 'stub-browser-ct0-2222', domain: 'x.com' },
82 ],
83 warnings: [],
84 };
85 }
86 `,
87 };
88 }
89 return nextLoad(url, context);
90 }
91 """
92 ),
93 encoding="utf-8",
94 )
95 register = tmp_path / "register-sweet-cookie.mjs"
96 register.write_text(
97 "import { register } from 'node:module';\n"
98 f"register({json.dumps(loader.as_uri())});\n",
99 encoding="utf-8",
100 )
101 return register
102
103
104 # ---------------------------------------------------------------------------
105 # HIGH-150: xquik.py handle validation, query sanitization, window & parsing
106 # ---------------------------------------------------------------------------
107
108
109 class TestHigh150XquikSecurityAndParsing:
110 def test_handle_lanes_validate_handles_strip_whitespace_before_at_and_exclude_self_mentions(self):
111 seen_queries: list[str] = []
112
113 def fake_get(url, **kwargs):
114 seen_queries.append(parse_qs(urlsplit(url).query)["q"][0])
115 return {"tweets": []}
116
117 bad_and_good = [
118 None, "", " ", " @alice ", "ALICE", "@Alice",
119 "alice OR from:bob", "bad;handle", "a" * 16, 12345,
120 ]
121 with mock.patch("lib.xquik.http.get", side_effect=fake_get):
122 xquik.search_handles(bad_and_good, "topic", "2026-05-01", "2026-05-31", token="dummy-key")
123 xquik.search_mentions(bad_and_good, "2026-05-01", "2026-05-31", token="dummy-key")
124
125 assert seen_queries == [
126 "from:alice since:2026-05-01 until:2026-06-01",
127 "@alice -from:alice since:2026-05-01 until:2026-06-01",
128 ]
129
130 @pytest.mark.parametrize(
131 "raw_query,expected_prefix",
132 [
133 ("alpha OR beta", "(alpha OR beta)"),
134 ("(alpha) OR (beta)", "((alpha) OR (beta))"),
135 ('("alpha" OR "beta")', '("alpha" OR "beta")'),
136 ('"unbalanced quote OR beta', "(unbalanced quote OR beta)"),
137 ('"good phrase" and "dangling', '"good phrase" and dangling'),
138 ('foo "a OR b"', 'foo "a OR b"'),
139 ("foo) OR (bar", "(foo OR bar)"),
140 ("foo since:2020-01-01 until:2020-12-31", "foo"),
141 ('"since:2020" foo', '"since:2020" foo'),
142 ("OR foo OR", "foo"),
143 ("from:evil to:victim filter:links lang:en -spam ai agents", "ai agents"),
144 ("from:evil OR alice", "alice"),
145 ('Python: "Mission: Impossible" -is:retweet', 'Python "Mission: Impossible"'),
146 ('"hello\\" OR from:evil', '"hello"'),
147 ('foo \\"bar baz', "foo bar baz"),
148 ],
149 )
150 def test_topic_query_sanitization_and_or_parenthesization(self, raw_query, expected_prefix):
151 seen_queries: list[str] = []
152
153 def fake_get(url, **kwargs):
154 seen_queries.append(parse_qs(urlsplit(url).query)["q"][0])
155 return {"tweets": []}
156
157 with mock.patch("lib.xquik.expand_xquik_queries", return_value=[raw_query]), \
158 mock.patch("lib.xquik.http.get", side_effect=fake_get):
159 xquik.search_xquik(raw_query, "2026-05-01", "2026-05-31", depth="quick", token="dummy-key")
160
161 assert seen_queries == [f"{expected_prefix} since:2026-05-01 until:2026-06-01"]
162
163 def test_empty_sanitized_topic_query_is_skipped(self):
164 with mock.patch("lib.xquik.expand_xquik_queries", return_value=['""', "()", "OR", "since:2020"]), \
165 mock.patch("lib.xquik.http.get") as mock_get:
166 res = xquik.search_xquik("()", "2026-05-01", "2026-05-31", depth="quick", token="dummy-key")
167 assert res == {"items": []}
168 mock_get.assert_not_called()
169
170 def test_date_window_filtering_applies_to_topic_handle_and_mention_lanes(self):
171 tweets = [
172 {"id": "1001", "text": "too old", "createdAt": "2026-04-30T23:59:59Z", "author": {"username": "fan"}},
173 {"id": "1002", "text": "start edge", "createdAt": "2026-05-01T00:00:00Z", "author": {"username": "fan"}},
174 {"id": "1003", "text": "end edge", "createdAt": "2026-05-31T23:59:59Z", "author": {"username": "fan"}},
175 {"id": "1004", "text": "too new", "createdAt": "2026-06-01T00:00:00Z", "author": {"username": "fan"}},
176 # +05:00 converts to 2026-04-30T22:00:00Z -> outside window!
177 {"id": "1005", "text": "tz before", "createdAt": "2026-05-01T03:00:00+05:00", "author": {"username": "fan"}},
178 {"id": "1006", "text": "undated kept", "author": {"username": "fan"}},
179 ]
180 with mock.patch("lib.xquik.http.get", return_value={"tweets": tweets}):
181 topic_items = xquik.search_xquik("agents", "2026-05-01", "2026-05-31", depth="quick", token="k")["items"]
182 handle_items = xquik.search_handles(["fan"], "agents", "2026-05-01", "2026-05-31", token="k")
183 mention_items = xquik.search_mentions(["other"], "2026-05-01", "2026-05-31", token="k")
184
185 expected_urls = [
186 "https://x.com/fan/status/1002",
187 "https://x.com/fan/status/1003",
188 "https://x.com/fan/status/1006",
189 ]
190 assert [it["url"] for it in topic_items] == expected_urls
191 assert [it["url"] for it in handle_items] == expected_urls
192 assert [it["url"] for it in mention_items] == expected_urls
193
194 def test_schema_drift_and_none_fields_never_crash_or_fabricate_urls(self):
195 failures: list[str] = []
196 with mock.patch("lib.xquik.http.get", side_effect=[["not", "a", "dict"], "plain-string", None]):
197 assert xquik.search_handles(["alice"], "t", "2026-05-01", "2026-05-31", token="k", failure_out=failures) == []
198 assert xquik.search_handles(["alice"], "t", "2026-05-01", "2026-05-31", token="k", failure_out=failures) == []
199 assert xquik.search_handles(["alice"], "t", "2026-05-01", "2026-05-31", token="k", failure_out=failures) == []
200 assert len(failures) == 3
201
202 malformed_tweets = [
203 {"id": None, "text": "null id", "author": {"username": "alice"}},
204 {"id": "0", "text": "zero str id", "author": {"username": "alice"}},
205 {"id": 0, "text": "zero int id", "author": {"username": "alice"}},
206 {"id": "000", "text": "zeros id", "author": {"username": "alice"}},
207 {"id": "9" * 5000, "text": "oversized str id", "author": {"username": "alice"}},
208 {"id": 10 ** 5000, "text": "oversized int id", "author": {"username": "alice"}},
209 {"id": "1" * 21, "text": "21-digit id", "author": {"username": "alice"}},
210 {"id": "None", "text": "str none id", "author": {"username": "alice"}},
211 {"id": "123abc", "text": "alpha id", "author": {"username": "alice"}},
212 {"id": "١٢٣٤٥", "text": "non-ascii digits", "author": {"username": "alice"}},
213 {"id": True, "text": "bool id", "author": {"username": "alice"}},
214 {"id": "1001", "text": "null username", "author": {"username": None}},
215 {"id": "1002", "text": "bad username", "author": {"username": "alice/../../evil"}},
216 {"id": "1003", "text": "string author", "author": "alice"},
217 {"id": "1004", "text": "list author", "author": ["alice"]},
218 {
219 "id": "1005",
220 "text": None,
221 "createdAt": 12345,
222 "likeCount": True,
223 "retweetCount": False,
224 "author": {"username": " @valid_user "},
225 },
226 ]
227 with mock.patch("lib.xquik.http.get", return_value={"tweets": malformed_tweets}):
228 res = xquik.search_xquik("test", "2026-05-01", "2026-05-31", depth="quick", token="k")
229
230 assert len(res["items"]) == 1
231 item = res["items"][0]
232 assert item["url"] == "https://x.com/valid_user/status/1005"
233 assert item["author_handle"] == "valid_user"
234 assert item["text"] == ""
235 assert item["date"] is None
236 assert item["engagement"]["likes"] is None
237 assert item["engagement"]["reposts"] is None
238 assert xquik._clean_tweet_id("9" * 5000) == ""
239 assert xquik._clean_tweet_id(10 ** 5000) == ""
240 assert xquik._safe_int(True) is None
241 assert xquik._safe_int(False) is None
242 assert xquik.parse_xquik_response("not-a-dict") == [] # type: ignore[arg-type]
243
244
245 # ---------------------------------------------------------------------------
246 # HIGH-156: runtime-query-ids redirect validation, timeouts, caps & SearchTimeline-only
247 # ---------------------------------------------------------------------------
248
249
250 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
251 class TestHigh156QueryIdDiscoverySecurity:
252 def test_discovery_blocks_cross_origin_downgrade_userinfo_port_and_redirect_loops(self, tmp_path):
253 cache_file = tmp_path / "ids.json"
254 script = textwrap.dedent(
255 f"""
256 import {{ createRuntimeQueryIdStore, validateDiscoveryUrl }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
257
258 const rejected = [];
259 for (const bad of [
260 'http://x.com/?lang=en',
261 'https://evil.example/bundle.js',
262 'https://evil.x.com/bundle.js',
263 'https://x.com.evil.example/bundle.js',
264 'https://x.com:8443/?lang=en',
265 'https://user:pass@x.com/?lang=en',
266 'http://169.254.169.254/latest/meta-data/',
267 ]) {{
268 try {{
269 validateDiscoveryUrl(bad);
270 rejected.push({{ bad, ok: true }});
271 }} catch (err) {{
272 rejected.push({{ bad, ok: false }});
273 }}
274 }}
275
276 const fetchedUrls = [];
277 const fetchImpl = async (url, init) => {{
278 fetchedUrls.push({{ url: String(url), redirect: init?.redirect }});
279 const u = String(url);
280 if (u === 'https://x.com/?lang=en') {{
281 return new Response('', {{ status: 302, headers: {{ location: 'http://169.254.169.254/latest/meta-data/' }} }});
282 }}
283 if (u === 'https://x.com/explore') {{
284 return new Response('', {{ status: 302, headers: {{ location: 'https://evil.example/steal' }} }});
285 }}
286 if (u === 'https://x.com/notifications') {{
287 // Safe same-host relative redirect -> succeeds
288 return new Response('', {{ status: 302, headers: {{ location: '/home' }} }});
289 }}
290 if (u === 'https://x.com/home') {{
291 return new Response(
292 '<script src="https://abs.twimg.com/responsive-web/client-web/main.abc123.js"></script>' +
293 '<script src="https://abs.twimg.com/responsive-web/client-web/bad.redirect.js"></script>',
294 {{ status: 200 }},
295 );
296 }}
297 if (u.endsWith('bad.redirect.js')) {{
298 return new Response('', {{ status: 301, headers: {{ location: 'http://abs.twimg.com/downgrade.js' }} }});
299 }}
300 if (u.endsWith('main.abc123.js')) {{
301 return new Response('e.exports={{queryId:"FreshSearchId_1",operationName:"SearchTimeline"}}', {{ status: 200 }});
302 }}
303 return new Response('', {{ status: 404 }});
304 }};
305
306 const store = createRuntimeQueryIdStore({{
307 fetchImpl,
308 cachePath: {json.dumps(str(cache_file))},
309 }});
310 const info = await store.refresh(['SearchTimeline'], {{ force: true }});
311
312 // Redirect loop exceeding maxRedirects must stop cleanly
313 let loopCount = 0;
314 const loopStore = createRuntimeQueryIdStore({{
315 cachePath: {json.dumps(str(tmp_path / "loop.json"))},
316 maxRedirects: 2,
317 fetchImpl: async (url) => {{
318 loopCount += 1;
319 return new Response('', {{ status: 302, headers: {{ location: `${{url}}&hop=${{loopCount}}` }} }});
320 }},
321 }});
322 let loopErr = null;
323 try {{
324 await loopStore.refresh(['SearchTimeline'], {{ force: true }});
325 }} catch (e) {{
326 loopErr = e.message;
327 }}
328
329 process.stdout.write(JSON.stringify({{
330 rejected,
331 fetchedUrls,
332 searchId: info?.snapshot?.ids?.SearchTimeline ?? null,
333 loopCount,
334 loopErr,
335 }}));
336 """
337 )
338 res = _node_eval(script)
339 assert res.returncode == 0, res.stderr
340 data = json.loads(res.stdout)
341 assert all(item["ok"] is False for item in data["rejected"]), data["rejected"]
342 urls = [entry["url"] for entry in data["fetchedUrls"]]
343 assert all(entry["redirect"] == "manual" for entry in data["fetchedUrls"])
344 assert not any("169.254.169.254" in u or "evil.example" in u or u.startswith("http://") for u in urls), urls
345 assert "https://x.com/home" in urls
346 assert data["searchId"] == "FreshSearchId_1"
347 assert data["loopErr"] is not None
348 # 4 discovery pages * (1 initial + 2 allowed redirects = 3 fetches each) = 12 max
349 assert data["loopCount"] == 12
350
351 def test_discovery_enforces_body_timeout_byte_cap_bundle_cap_and_search_only_refresh(self, tmp_path):
352 cache_file = tmp_path / "ids-caps.json"
353 script = textwrap.dedent(
354 f"""
355 import {{ createRuntimeQueryIdStore }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
356 import {{ TwitterClientBase }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js';
357 import {{ SEARCH_QUERY_ID_OPERATIONS }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-constants.js';
358
359 // 1) Stalled body stream must abort within fetchTimeoutMs
360 let stalledCancelled = false;
361 const stalledStore = createRuntimeQueryIdStore({{
362 cachePath: {json.dumps(str(tmp_path / "stalled.json"))},
363 fetchTimeoutMs: 80,
364 refreshTimeoutMs: 250,
365 fetchImpl: async () => new Response(new ReadableStream({{
366 start(controller) {{
367 controller.enqueue(new TextEncoder().encode('<html>partial'));
368 }},
369 cancel() {{
370 stalledCancelled = true;
371 }},
372 }}), {{ status: 200 }}),
373 }});
374 const t0 = Date.now();
375 let stalledErr = null;
376 try {{
377 await stalledStore.refresh(['SearchTimeline'], {{ force: true }});
378 }} catch (e) {{
379 stalledErr = e.message;
380 }}
381 const stalledElapsed = Date.now() - t0;
382
383 // 2) Oversized bundle stream must abort & cancel without buffering unbounded data;
384 // and bundle count must be capped at maxBundles.
385 let oversizedCancelled = false;
386 const bundleFetches = [];
387 const htmlBundles = Array.from({{ length: 50 }}, (_, i) =>
388 `https://abs.twimg.com/responsive-web/client-web/chunk.${{i}}.js`
389 ).join(' ');
390 const cappedStore = createRuntimeQueryIdStore({{
391 cachePath: {json.dumps(str(cache_file))},
392 maxBundles: 5,
393 maxBytes: 4096,
394 fetchImpl: async (url) => {{
395 const u = String(url);
396 if (u.startsWith('https://x.com/')) {{
397 return new Response(htmlBundles, {{ status: 200 }});
398 }}
399 bundleFetches.push(u);
400 if (u.endsWith('chunk.0.js')) {{
401 return new Response(new ReadableStream({{
402 pull(controller) {{
403 controller.enqueue(new Uint8Array(3000));
404 }},
405 cancel() {{
406 oversizedCancelled = true;
407 }},
408 }}), {{ status: 200 }});
409 }}
410 return new Response('noop', {{ status: 200 }});
411 }},
412 }});
413 await cappedStore.refresh(['SearchTimeline'], {{ force: true }});
414
415 // 3) Page-by-page discovery scans page 1's bundles immediately without touching slow page 2
416 const pageByPageUrls = [];
417 const fastPageStore = createRuntimeQueryIdStore({{
418 cachePath: {json.dumps(str(tmp_path / "fast-page.json"))},
419 fetchTimeoutMs: 500,
420 refreshTimeoutMs: 1000,
421 fetchImpl: async (url) => {{
422 const u = String(url);
423 pageByPageUrls.push(u);
424 if (u === 'https://x.com/?lang=en') {{
425 return new Response(
426 'https://abs.twimg.com/responsive-web/client-web/fast.1.js',
427 {{ status: 200 }},
428 );
429 }}
430 if (u.endsWith('fast.1.js')) {{
431 return new Response(
432 'e.exports={{queryId:"FastPageId_7",operationName:"SearchTimeline"}}',
433 {{ status: 200 }},
434 );
435 }}
436 // Fallback pages hang — must never be requested once page 1 yields SearchTimeline
437 return new Promise(() => {{}});
438 }},
439 }});
440 const tFast = Date.now();
441 const fastInfo = await fastPageStore.refresh(['SearchTimeline'], {{ force: true }});
442 const fastElapsed = Date.now() - tFast;
443
444 process.stdout.write(JSON.stringify({{
445 searchOps: SEARCH_QUERY_ID_OPERATIONS,
446 stalledErr,
447 stalledElapsed,
448 stalledCancelled,
449 oversizedCancelled,
450 bundleFetchCount: bundleFetches.length,
451 fastPageId: fastInfo?.snapshot?.ids?.SearchTimeline ?? null,
452 fastPageUrls: pageByPageUrls,
453 fastElapsed,
454 }}));
455 """
456 )
457 res = _node_eval(script)
458 assert res.returncode == 0, res.stderr
459 data = json.loads(res.stdout)
460 assert data["searchOps"] == ["SearchTimeline"]
461 assert data["stalledErr"] is not None
462 assert data["stalledElapsed"] < 2000
463 assert data["stalledCancelled"] is True
464 assert data["oversizedCancelled"] is True
465 assert data["bundleFetchCount"] == 5
466 assert data["fastPageId"] == "FastPageId_7"
467 assert data["fastElapsed"] < 500
468 assert data["fastPageUrls"] == [
469 "https://x.com/?lang=en",
470 "https://abs.twimg.com/responsive-web/client-web/fast.1.js",
471 ]
472
473 # 4) TwitterClientBase.refreshQueryIds: install fetch stub & cache path BEFORE dynamic
474 # import so the module-level runtimeQueryIds store captures our stub and temp cache.
475 client_cache = tmp_path / "client-cache.json"
476 client_script = textwrap.dedent(
477 f"""
478 delete process.env.NODE_ENV;
479 process.env.BIRD_QUERY_IDS_CACHE = {json.dumps(str(client_cache))};
480 const clientBundlesFetched = [];
481 globalThis.fetch = async (url) => {{
482 const u = String(url);
483 if (u.startsWith('https://x.com/')) {{
484 const body = Array.from({{ length: 18 }}, (_, i) =>
485 `https://abs.twimg.com/responsive-web/client-web/b${{i}}.js`
486 ).join(' ');
487 return new Response(body, {{ status: 200 }});
488 }}
489 clientBundlesFetched.push(u);
490 if (u.endsWith('b0.js')) {{
491 return new Response('e.exports={{queryId:"SearchOnlyId99",operationName:"SearchTimeline"}}', {{ status: 200 }});
492 }}
493 return new Response('noop', {{ status: 200 }});
494 }};
495
496 const {{ TwitterClientBase }} = await import('./skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js');
497 const client = new TwitterClientBase({{ cookies: {{ authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }}, timeoutMs: 5000 }});
498 await client.refreshQueryIds();
499 const refreshedId = await client.getQueryId('SearchTimeline');
500 process.stdout.write(JSON.stringify({{
501 clientBundlesFetchedCount: clientBundlesFetched.length,
502 refreshedId,
503 }}));
504 """
505 )
506 client_res = _node_eval(client_script)
507 assert client_res.returncode == 0, client_res.stderr
508 client_data = json.loads(client_res.stdout)
509 # First chunk of concurrency 6 finds SearchTimeline in b0.js and stops before chunks 2-3 (18 total).
510 assert 1 <= client_data["clientBundlesFetchedCount"] <= 6
511 assert client_data["refreshedId"] == "SearchOnlyId99"
512 assert client_cache.is_file()
513 assert json.loads(client_cache.read_text(encoding="utf-8"))["ids"] == {"SearchTimeline": "SearchOnlyId99"}
514
515 def test_slow_sibling_bundle_is_aborted_once_target_found_leaving_time_for_retry(self, tmp_path):
516 retry_cache = tmp_path / "retry-cache.json"
517 script = textwrap.dedent(
518 f"""
519 delete process.env.NODE_ENV;
520 process.env.BIRD_QUERY_IDS_CACHE = {json.dumps(str(retry_cache))};
521 let slowAborted = false;
522 let searchAttempts = 0;
523 globalThis.fetch = async (url, init) => {{
524 const u = String(url);
525 if (u.includes('/SearchTimeline?')) {{
526 searchAttempts += 1;
527 if (u.includes('/RotatedFreshId_9/SearchTimeline?')) {{
528 const body = {{
529 data: {{
530 search_by_raw_query: {{
531 search_timeline: {{
532 timeline: {{
533 instructions: [{{
534 type: 'TimelineAddEntries',
535 entries: [{{
536 entryId: 'tweet-888',
537 content: {{
538 itemContent: {{
539 tweet_results: {{
540 result: {{
541 __typename: 'Tweet',
542 rest_id: '888',
543 legacy: {{ id_str: '888', full_text: 'after fast refresh', created_at: 'Wed May 15 12:00:00 +0000 2026' }},
544 core: {{ user_results: {{ result: {{ rest_id: '8', legacy: {{ screen_name: 'carol', name: 'Carol' }} }} }} }},
545 }},
546 }},
547 }},
548 }},
549 }}],
550 }}],
551 }},
552 }},
553 }},
554 }},
555 }};
556 return new Response(JSON.stringify(body), {{ status: 200, headers: {{ 'content-type': 'application/json' }} }});
557 }}
558 return new Response('not found', {{ status: 404 }});
559 }}
560 if (u === 'https://x.com/?lang=en') {{
561 return new Response(
562 'https://abs.twimg.com/responsive-web/client-web/fast.js ' +
563 'https://abs.twimg.com/responsive-web/client-web/stalled.js',
564 {{ status: 200 }},
565 );
566 }}
567 if (u.endsWith('fast.js')) {{
568 return new Response('e.exports={{queryId:"RotatedFreshId_9",operationName:"SearchTimeline"}}', {{ status: 200 }});
569 }}
570 if (u.endsWith('stalled.js')) {{
571 return new Promise((_resolve, reject) => {{
572 init?.signal?.addEventListener('abort', () => {{
573 slowAborted = true;
574 reject(init.signal.reason);
575 }}, {{ once: true }});
576 }});
577 }}
578 return new Response('', {{ status: 404 }});
579 }};
580
581 const {{ TwitterClientBase }} = await import('./skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js');
582 const {{ withSearch }} = await import('./skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-search.js');
583 const Client = withSearch(TwitterClientBase);
584 const client = new Client({{ cookies: {{ authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }}, timeoutMs: 3000 }});
585 const t0 = Date.now();
586 const res = await client.search('hello', 5);
587 const elapsed = Date.now() - t0;
588 process.stdout.write(JSON.stringify({{
589 success: res.success,
590 ids: (res.tweets || []).map((t) => t.id),
591 slowAborted,
592 elapsed,
593 searchAttempts,
594 }}));
595 """
596 )
597 res = _node_eval(script)
598 assert res.returncode == 0, res.stderr
599 data = json.loads(res.stdout)
600 assert data["success"] is True
601 assert data["ids"] == ["888"]
602 assert data["slowAborted"] is True
603 assert data["elapsed"] < 1500
604 assert data["searchAttempts"] >= 2
605
606 def test_read_response_text_json_fallback_utf8_truncation_and_non_ok_abort_rethrow(self, tmp_path):
607 script = textwrap.dedent(
608 f"""
609 import {{ createRuntimeQueryIdStore, readResponseTextBounded }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
610
611 // 1) .json()-only response fallback bounded by UTF-8 bytes
612 const jsonOnly = await readResponseTextBounded({{ json: async () => ({{ ok: true }}) }}, 64, null);
613 let jsonOverErr = null;
614 try {{
615 await readResponseTextBounded({{ json: async () => ({{ big: 'a'.repeat(100) }}) }}, 32, null);
616 }} catch (e) {{
617 jsonOverErr = e.message;
618 }}
619
620 // 2) .text()-only UTF-8 byte truncation never splits multi-byte chars or exceeds maxBytes
621 const truncEmoji = await readResponseTextBounded(
622 {{ text: async () => '🔥a' }},
623 2,
624 null,
625 {{ truncateOnLimit: true }},
626 );
627 const truncAccent = await readResponseTextBounded(
628 {{ text: async () => 'éé' }},
629 3,
630 null,
631 {{ truncateOnLimit: true }},
632 );
633
634 // 3) Stalled non-OK (500) body in discovery fetchText aborts promptly (rethrows AbortError, doesn't hang)
635 let nonOkCancelled = false;
636 const nonOkStore = createRuntimeQueryIdStore({{
637 cachePath: {json.dumps(str(tmp_path / "non-ok.json"))},
638 fetchTimeoutMs: 80,
639 refreshTimeoutMs: 250,
640 fetchImpl: async () => new Response(new ReadableStream({{
641 start(controller) {{
642 controller.enqueue(new TextEncoder().encode('err'));
643 }},
644 cancel() {{
645 nonOkCancelled = true;
646 }},
647 }}), {{ status: 500 }}),
648 }});
649 const t0 = Date.now();
650 let nonOkErr = null;
651 try {{
652 await nonOkStore.refresh(['SearchTimeline'], {{ force: true }});
653 }} catch (e) {{
654 nonOkErr = e.message;
655 }}
656 const nonOkElapsed = Date.now() - t0;
657
658 process.stdout.write(JSON.stringify({{
659 jsonOnly,
660 jsonOverErr,
661 truncEmoji,
662 truncEmojiBytes: Buffer.byteLength(truncEmoji, 'utf8'),
663 truncAccent,
664 truncAccentBytes: Buffer.byteLength(truncAccent, 'utf8'),
665 nonOkCancelled,
666 nonOkErr,
667 nonOkElapsed,
668 }}));
669 """
670 )
671 res = _node_eval(script)
672 assert res.returncode == 0, res.stderr
673 data = json.loads(res.stdout)
674 assert data["jsonOnly"] == '{"ok":true}'
675 assert data["jsonOverErr"] and "byte limit" in data["jsonOverErr"].lower()
676 assert data["truncEmoji"] == ""
677 assert data["truncEmojiBytes"] <= 2
678 assert data["truncAccent"] == "é"
679 assert data["truncAccentBytes"] == 2
680 assert data["nonOkCancelled"] is True
681 assert data["nonOkErr"] is not None
682 assert data["nonOkElapsed"] < 2000
683
684
685 # ---------------------------------------------------------------------------
686 # HIGH-157: fetch body timeout, byte cap, signal composition, 404 cancel, abort loop, --timeout-ms
687 # ---------------------------------------------------------------------------
688
689
690 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
691 class TestHigh157FetchLifecycleAndTimeoutCli:
692 def test_body_timeout_signal_composition_404_cancel_byte_cap_and_no_4x_retry(self):
693 script = textwrap.dedent(
694 """
695 import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js';
696 import { withSearch } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-search.js';
697
698 const Client = withSearch(TwitterClientBase);
699
700 // 1) Stalled body after 200 headers must time out AND not multiply 4x across fallback queryIds
701 let stallFetches = 0;
702 let stallCancelled = false;
703 let refreshCalls = 0;
704 globalThis.fetch = async () => {
705 stallFetches += 1;
706 return new Response(new ReadableStream({
707 start(controller) {
708 controller.enqueue(new TextEncoder().encode('{"partial":'));
709 },
710 cancel() {
711 stallCancelled = true;
712 },
713 }), { status: 200, headers: { 'content-type': 'application/json' } });
714 };
715 const client1 = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 120 });
716 client1.refreshQueryIds = async () => { refreshCalls += 1; };
717 const t0 = Date.now();
718 const r1 = await client1.search('hello', 5);
719 const elapsed1 = Date.now() - t0;
720
721 // 2) 404 cancels response.body before continuing to next queryId
722 let cancelled404Count = 0;
723 let fetchCount404 = 0;
724 globalThis.fetch = async () => {
725 fetchCount404 += 1;
726 if (fetchCount404 === 1) {
727 return new Response(new ReadableStream({
728 start(controller) {
729 controller.enqueue(new TextEncoder().encode('not found'));
730 },
731 cancel() {
732 cancelled404Count += 1;
733 },
734 }), { status: 404 });
735 }
736 return new Response(JSON.stringify({
737 data: { search_by_raw_query: { search_timeline: { timeline: { instructions: [] } } } },
738 }), { status: 200, headers: { 'content-type': 'application/json' } });
739 };
740 const client2 = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 2000 });
741 const r2 = await client2.search('hello', 5);
742
743 // 3) Network error stops immediately on queryId #1 without retrying remaining 3 IDs
744 let netFetches = 0;
745 globalThis.fetch = async () => {
746 netFetches += 1;
747 throw new TypeError('fetch failed');
748 };
749 const client3 = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 2000 });
750 const r3 = await client3.search('hello', 5);
751
752 // 4) Caller init.signal is composed in both fetchWithTimeout and fetchTextWithTimeout
753 const caller = new AbortController();
754 globalThis.fetch = async (_url, init) => {
755 setTimeout(() => caller.abort(new Error('caller cancelled')), 30);
756 return new Promise((_, reject) => {
757 init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });
758 });
759 };
760 const client4 = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 10000 });
761 let callerAbortMsg = null;
762 try {
763 await client4.fetchTextWithTimeout('https://x.com/test', { signal: caller.signal });
764 } catch (e) {
765 callerAbortMsg = e.message;
766 }
767 const caller2 = new AbortController();
768 globalThis.fetch = async (_url, init) => {
769 setTimeout(() => caller2.abort(new Error('caller2 cancelled')), 30);
770 return new Promise((_, reject) => {
771 init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });
772 });
773 };
774 let caller2AbortMsg = null;
775 try {
776 await client4.fetchWithTimeout('https://x.com/test', { signal: caller2.signal });
777 } catch (e) {
778 caller2AbortMsg = e.message;
779 }
780
781 // 5) Oversized 200 response hits maxResponseBytes cap and cancels stream
782 let bigCancelled = false;
783 globalThis.fetch = async () => new Response(new ReadableStream({
784 pull(controller) {
785 controller.enqueue(new Uint8Array(400));
786 },
787 cancel() {
788 bigCancelled = true;
789 },
790 }), { status: 200 });
791 const client5 = new Client({
792 cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' },
793 timeoutMs: 2000,
794 maxResponseBytes: 512,
795 });
796 const r5 = await client5.search('hello', 5);
797
798 process.stdout.write(JSON.stringify({
799 r1, elapsed1, stallFetches, stallCancelled, refreshCalls,
800 r2Ok: r2.success, fetchCount404, cancelled404Count,
801 r3, netFetches,
802 callerAbortMsg, caller2AbortMsg,
803 r5, bigCancelled,
804 }));
805 """
806 )
807 res = _node_eval(script)
808 assert res.returncode == 0, res.stderr
809 data = json.loads(res.stdout)
810
811 assert data["r1"]["success"] is False
812 assert "timed out" in data["r1"]["error"].lower()
813 assert data["elapsed1"] < 1500
814 assert data["stallFetches"] == 1
815 assert data["stallCancelled"] is True
816 assert data["refreshCalls"] == 0
817
818 assert data["r2Ok"] is True
819 assert data["fetchCount404"] == 2
820 assert data["cancelled404Count"] == 1
821
822 assert data["r3"]["success"] is False
823 assert data["netFetches"] == 1
824
825 assert data["callerAbortMsg"] == "caller cancelled"
826 assert data["caller2AbortMsg"] == "caller2 cancelled"
827
828 assert data["r5"]["success"] is False
829 assert "byte limit" in data["r5"]["error"].lower()
830 assert data["bigCancelled"] is True
831
832 def test_bird_search_mjs_timeout_ms_cli_flag_and_python_forwarding(self, tmp_path):
833 stub = tmp_path / "stub-stall.mjs"
834 stub.write_text(
835 textwrap.dedent(
836 """
837 globalThis.fetch = async (_url, init) => new Promise((_resolve, reject) => {
838 init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });
839 });
840 """
841 ),
842 encoding="utf-8",
843 )
844 run_env = os.environ.copy()
845 run_env.update(
846 AUTH_TOKEN="dummy-auth-token-1234",
847 CT0="dummy-ct0-token-5678",
848 BIRD_DISABLE_BROWSER_COOKIES="1",
849 )
850 started = time.monotonic()
851 res = subprocess.run(
852 [
853 "node", "--import", stub.as_uri(), str(BIRD_MJS),
854 "--count", "1", "--timeout-ms", "150", "--json", "--", "hello",
855 ],
856 cwd=REPO_ROOT,
857 env=run_env,
858 capture_output=True,
859 text=True,
860 check=False,
861 )
862 elapsed = time.monotonic() - started
863 assert res.returncode == 1
864 assert elapsed < 3.0
865 payload = json.loads(res.stdout)
866 match = re.search(r"timed out after (\d+)ms", payload["error"])
867 assert match is not None, payload["error"]
868 assert 1 <= int(match.group(1)) <= 150
869
870 for bad in (
871 ["--timeout-ms", "0"],
872 ["--timeout-ms", "-5"],
873 ["--timeout-ms", "abc"],
874 ["--timeout-ms", "2147483648"],
875 ["--timeout-ms", "999999999999"],
876 ["--timeout-ms"],
877 ):
878 bad_res = subprocess.run(
879 ["node", str(BIRD_MJS), *bad, "--json", "--", "hello"],
880 cwd=REPO_ROOT,
881 env=run_env,
882 capture_output=True,
883 text=True,
884 check=False,
885 )
886 assert bad_res.returncode == 1
887 assert bad_res.stdout == ""
888
889 # Verify bird_x.py passes --timeout-ms matching clamped subprocess budget on all 3 lanes,
890 # including sub-second remaining deadlines (< 1000ms).
891 captured_cmds: list[list[str]] = []
892
893 def fake_run(cmd, **_kwargs):
894 captured_cmds.append(cmd)
895 return SubprocResult(returncode=0, stdout="[]", stderr="")
896
897 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run):
898 bird_x._invoke_bird_subprocess("hello", count=5, timeout=8)
899 bird_x._invoke_bird_subprocess("hello", count=5, timeout=8, deadline=time.monotonic() + 0.35)
900 bird_x.search_handles(["alice"], "topic", "2026-05-01", count_per=2)
901 bird_x.search_mentions(["alice"], "2026-05-01", count_per=2)
902
903 assert len(captured_cmds) == 4
904 for cmd in captured_cmds:
905 sep = cmd.index("--")
906 idx = cmd.index("--timeout-ms")
907 assert idx < sep
908 # Python reserves flush headroom so Node writes partial JSON before Python kills it
909 assert captured_cmds[0][captured_cmds[0].index("--timeout-ms") + 1] == "6500"
910 sub_second_ms = int(captured_cmds[1][captured_cmds[1].index("--timeout-ms") + 1])
911 assert 1 <= sub_second_ms < 350
912 assert captured_cmds[2][captured_cmds[2].index("--timeout-ms") + 1] == "13500"
913 assert captured_cmds[3][captured_cmds[3].index("--timeout-ms") + 1] == "13500"
914
915 def test_single_search_deadline_and_headroom_preserve_page1_on_page2_stall(self, tmp_path):
916 # 1) Node searchPaged enforces a single total deadline across pages (page 1 slow + page 2 stall)
917 node_script = textwrap.dedent(
918 """
919 import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js';
920 import { withSearch } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-search.js';
921
922 const Client = withSearch(TwitterClientBase);
923 let pageNum = 0;
924 globalThis.fetch = async (_url, init) => {
925 pageNum += 1;
926 if (pageNum === 1) {
927 await new Promise((r) => setTimeout(r, 120));
928 const body = {
929 data: {
930 search_by_raw_query: {
931 search_timeline: {
932 timeline: {
933 instructions: [{
934 type: 'TimelineAddEntries',
935 entries: [
936 {
937 entryId: 'tweet-601',
938 content: {
939 itemContent: {
940 tweet_results: {
941 result: {
942 __typename: 'Tweet',
943 rest_id: '601',
944 legacy: { id_str: '601', full_text: 'page1 kept', created_at: 'Wed May 15 12:00:00 +0000 2026' },
945 core: { user_results: { result: { rest_id: '1', legacy: { screen_name: 'alice', name: 'Alice' } } } },
946 },
947 },
948 },
949 },
950 },
951 { entryId: 'cursor-bottom-0', content: { cursorType: 'Bottom', value: 'c2' } },
952 ],
953 }],
954 },
955 },
956 },
957 },
958 };
959 return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
960 }
961 return new Promise((_res, reject) => {
962 init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });
963 });
964 };
965 const client = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 260 });
966 const t0 = Date.now();
967 const result = await client.search('hello', 30);
968 const elapsed = Date.now() - t0;
969 process.stdout.write(JSON.stringify({
970 elapsed,
971 success: result.success,
972 ids: (result.tweets || []).map((t) => t.id),
973 error: result.error,
974 }));
975 """
976 )
977 res = _node_eval(node_script)
978 assert res.returncode == 0, res.stderr
979 data = json.loads(res.stdout)
980 assert data["success"] is False
981 assert data["ids"] == ["601"]
982 assert "timed out" in data["error"].lower()
983 # Total time is bounded by the single 260ms search deadline (not 120 + 260 = 380ms+)
984 assert data["elapsed"] < 360
985
986 # 2) End-to-end Python -> Node: page 2 stalls forever, Node self-aborts using headroom
987 # before Python's 2s subprocess timeout kills it, flushing page 1's tweet to stdout.
988 stub = tmp_path / "stub-page2-stall.mjs"
989 stub.write_text(
990 textwrap.dedent(
991 """
992 let calls = 0;
993 globalThis.fetch = async (_url, init) => {
994 calls += 1;
995 if (calls === 1) {
996 const body = {
997 data: {
998 search_by_raw_query: {
999 search_timeline: {
1000 timeline: {
1001 instructions: [{
1002 type: 'TimelineAddEntries',
1003 entries: [
1004 {
1005 entryId: 'tweet-602',
1006 content: {
1007 itemContent: {
1008 tweet_results: {
1009 result: {
1010 __typename: 'Tweet',
1011 rest_id: '602',
1012 legacy: { id_str: '602', full_text: 'flushed before kill', created_at: 'Wed May 15 12:00:00 +0000 2026' },
1013 core: { user_results: { result: { rest_id: '2', legacy: { screen_name: 'bob', name: 'Bob' } } } },
1014 },
1015 },
1016 },
1017 },
1018 },
1019 { entryId: 'cursor-bottom-0', content: { cursorType: 'Bottom', value: 'c-stall' } },
1020 ],
1021 }],
1022 },
1023 },
1024 },
1025 },
1026 };
1027 return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
1028 }
1029 return new Promise((_res, reject) => {
1030 init?.signal?.addEventListener('abort', () => reject(init.signal.reason), { once: true });
1031 });
1032 };
1033 """
1034 ),
1035 encoding="utf-8",
1036 )
1037 real_run = bird_x.subproc.run_with_timeout
1038
1039 def wrapped_run(cmd, **kwargs):
1040 env_copy = dict(kwargs.get("env") or {})
1041 env_copy["NODE_OPTIONS"] = f"--import={stub.as_uri()}"
1042 env_copy["AUTH_TOKEN"] = "dummy-auth-token-1234"
1043 env_copy["CT0"] = "dummy-ct0-token-5678"
1044 kwargs["env"] = env_copy
1045 return real_run(cmd, **kwargs)
1046
1047 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=wrapped_run):
1048 resp = bird_x._run_bird_search("hello", count=30, timeout=2)
1049 assert "timed out" in resp.get("error", "").lower()
1050 parsed = bird_x.parse_bird_response(resp)
1051 assert [it["url"] for it in parsed] == ["https://x.com/bob/status/602"]
1052
1053
1054 # ---------------------------------------------------------------------------
1055 # HIGH-158: atomic private cache writes, symlink refusal & read-only HOME
1056 # ---------------------------------------------------------------------------
1057
1058
1059 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
1060 class TestHigh158AtomicPrivateCacheWrites:
1061 def test_private_permissions_and_atomic_writes_for_query_ids_and_features(self, tmp_path):
1062 nested_dir = tmp_path / "private_cache_dir"
1063 qid_cache = nested_dir / "query-ids-cache.json"
1064 feat_cache = nested_dir / "features.json"
1065
1066 script = textwrap.dedent(
1067 f"""
1068 import {{ createRuntimeQueryIdStore }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
1069 import {{ refreshFeatureOverridesCache }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-features.js';
1070
1071 const fetchImpl = async (url) => {{
1072 if (String(url).startsWith('https://x.com/')) {{
1073 return new Response('https://abs.twimg.com/responsive-web/client-web/main.1.js', {{ status: 200 }});
1074 }}
1075 return new Response('e.exports={{queryId:"AtomicId_1",operationName:"SearchTimeline"}}', {{ status: 200 }});
1076 }};
1077
1078 const store = createRuntimeQueryIdStore({{
1079 fetchImpl,
1080 cachePath: {json.dumps(str(qid_cache))},
1081 }});
1082 await store.refresh(['SearchTimeline'], {{ force: true }});
1083
1084 process.env.BIRD_FEATURES_CACHE = {json.dumps(str(feat_cache))};
1085 await refreshFeatureOverridesCache();
1086 """
1087 )
1088 res = _node_eval(script)
1089 assert res.returncode == 0, res.stderr
1090 assert json.loads(qid_cache.read_text(encoding="utf-8"))["ids"]["SearchTimeline"] == "AtomicId_1"
1091 assert feat_cache.is_file()
1092
1093 if os.name != "nt":
1094 assert stat.S_IMODE(nested_dir.stat().st_mode) == 0o700
1095 assert stat.S_IMODE(qid_cache.stat().st_mode) == 0o600
1096 assert stat.S_IMODE(feat_cache.stat().st_mode) == 0o600
1097 # No leftover .tmp sibling files
1098 assert not [p for p in nested_dir.iterdir() if p.name.endswith(".tmp")]
1099
1100 @pytest.mark.skipif(os.name == "nt", reason="POSIX symlinks require elevated privileges on Windows")
1101 def test_symlink_target_and_dir_refusal_for_query_ids_and_features(self, tmp_path):
1102 victim = tmp_path / "victim.txt"
1103 victim.write_text("DO_NOT_OVERWRITE", encoding="utf-8")
1104 symlink_target = tmp_path / "symlink-cache.json"
1105 symlink_target.symlink_to(victim)
1106
1107 real_dir = tmp_path / "real_dir"
1108 real_dir.mkdir()
1109 symlink_dir = tmp_path / "symlink_dir"
1110 symlink_dir.symlink_to(real_dir)
1111
1112 outside_dir = tmp_path / "outside_dir"
1113 outside_dir.mkdir()
1114 ancestor_symlink = tmp_path / "ancestor_symlink"
1115 ancestor_symlink.symlink_to(outside_dir)
1116
1117 script = textwrap.dedent(
1118 f"""
1119 import {{ writeFileAtomicPrivate }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
1120
1121 let symlinkTargetErr = null;
1122 try {{
1123 await writeFileAtomicPrivate({json.dumps(str(symlink_target))}, '{{}}\\n');
1124 }} catch (e) {{
1125 symlinkTargetErr = e.message;
1126 }}
1127
1128 let symlinkDirErr = null;
1129 try {{
1130 await writeFileAtomicPrivate({json.dumps(str(symlink_dir / "out.json"))}, '{{}}\\n');
1131 }} catch (e) {{
1132 symlinkDirErr = e.message;
1133 }}
1134
1135 let ancestorSymlinkErr = null;
1136 try {{
1137 await writeFileAtomicPrivate({json.dumps(str(ancestor_symlink / "nested" / "deep" / "cache.json"))}, '{{}}\\n');
1138 }} catch (e) {{
1139 ancestorSymlinkErr = e.message;
1140 }}
1141
1142 process.stdout.write(JSON.stringify({{ symlinkTargetErr, symlinkDirErr, ancestorSymlinkErr }}));
1143 """
1144 )
1145 res = _node_eval(script)
1146 assert res.returncode == 0, res.stderr
1147 data = json.loads(res.stdout)
1148 assert data["symlinkTargetErr"] and "symlink" in data["symlinkTargetErr"].lower()
1149 assert data["symlinkDirErr"] and "symlink" in data["symlinkDirErr"].lower()
1150 assert data["ancestorSymlinkErr"] and "symlink" in data["ancestorSymlinkErr"].lower()
1151 assert victim.read_text(encoding="utf-8") == "DO_NOT_OVERWRITE"
1152 assert not (real_dir / "out.json").exists()
1153 assert not (outside_dir / "nested").exists()
1154
1155 def test_concurrent_node_processes_never_corrupt_query_ids_cache(self, tmp_path):
1156 cache_file = tmp_path / "concurrent" / "query-ids-cache.json"
1157
1158 def worker(idx: int) -> subprocess.CompletedProcess:
1159 script = textwrap.dedent(
1160 f"""
1161 import {{ createRuntimeQueryIdStore }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
1162 const fetchImpl = async (url) => {{
1163 if (String(url).startsWith('https://x.com/')) {{
1164 return new Response('https://abs.twimg.com/responsive-web/client-web/main.{idx}.js', {{ status: 200 }});
1165 }}
1166 return new Response('e.exports={{queryId:"ConcurrentId_{idx}",operationName:"SearchTimeline"}}', {{ status: 200 }});
1167 }};
1168 const store = createRuntimeQueryIdStore({{ fetchImpl, cachePath: {json.dumps(str(cache_file))} }});
1169 for (let round = 0; round < 3; round++) {{
1170 await store.refresh(['SearchTimeline'], {{ force: true }});
1171 }}
1172 """
1173 )
1174 return _node_eval(script)
1175
1176 with ThreadPoolExecutor(max_workers=6) as pool:
1177 results = list(pool.map(worker, range(6)))
1178
1179 for res in results:
1180 assert res.returncode == 0, res.stderr
1181 parsed = json.loads(cache_file.read_text(encoding="utf-8"))
1182 assert parsed["ids"]["SearchTimeline"].startswith("ConcurrentId_")
1183 assert not [p for p in cache_file.parent.iterdir() if p.name.endswith(".tmp")]
1184
1185 @pytest.mark.skipif(
1186 os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0),
1187 reason="POSIX non-root chmod test",
1188 )
1189 def test_readonly_cache_dir_still_refreshes_memory_snapshot(self, tmp_path):
1190 ro_dir = tmp_path / "readonly_home"
1191 ro_dir.mkdir(mode=0o700)
1192 ro_dir.chmod(0o500)
1193 cache_file = ro_dir / "query-ids-cache.json"
1194 try:
1195 script = textwrap.dedent(
1196 f"""
1197 import {{ createRuntimeQueryIdStore }} from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js';
1198 const fetchImpl = async (url) => {{
1199 if (String(url).startsWith('https://x.com/')) {{
1200 return new Response('https://abs.twimg.com/responsive-web/client-web/main.ro.js', {{ status: 200 }});
1201 }}
1202 return new Response('e.exports={{queryId:"ReadOnlyMemId_42",operationName:"SearchTimeline"}}', {{ status: 200 }});
1203 }};
1204 const store = createRuntimeQueryIdStore({{ fetchImpl, cachePath: {json.dumps(str(cache_file))} }});
1205 const info = await store.refresh(['SearchTimeline'], {{ force: true }});
1206 const id = await store.getQueryId('SearchTimeline');
1207 process.stdout.write(JSON.stringify({{ id, infoId: info?.snapshot?.ids?.SearchTimeline ?? null }}));
1208 """
1209 )
1210 res = _node_eval(script)
1211 assert res.returncode == 0, res.stderr
1212 data = json.loads(res.stdout)
1213 assert data["id"] == "ReadOnlyMemId_42"
1214 assert data["infoId"] == "ReadOnlyMemId_42"
1215 assert not cache_file.exists()
1216 finally:
1217 ro_dir.chmod(0o700)
1218
1219
1220 # ---------------------------------------------------------------------------
1221 # HIGH-159: pagination cycle detection, empty-page stop, maxPages:0, caps & partials
1222 # ---------------------------------------------------------------------------
1223
1224
1225 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
1226 class TestHigh159PaginationGuards:
1227 def test_paginate_cursor_stops_on_cycles_empty_pages_and_invalid_max_pages(self):
1228 script = textwrap.dedent(
1229 """
1230 import { paginateCursor } from './skills/last30days/scripts/lib/vendor/bird-search/lib/paginate-cursor.js';
1231
1232 // 1) 2-step cursor cycle A -> B -> A
1233 let cycleCalls = 0;
1234 const cycleRes = await paginateCursor({
1235 pageDelayMs: 0,
1236 getKey: (x) => x.id,
1237 fetchPage: async (cursor) => {
1238 cycleCalls += 1;
1239 if (!cursor) return { success: true, items: [{ id: '1' }], cursor: 'A' };
1240 if (cursor === 'A') return { success: true, items: [{ id: '2' }], cursor: 'B' };
1241 if (cursor === 'B') return { success: true, items: [{ id: '3' }], cursor: 'A' };
1242 throw new Error('should never loop');
1243 },
1244 });
1245
1246 // 2) Rotating unique cursors with empty items stops immediately
1247 let emptyCalls = 0;
1248 const emptyRes = await paginateCursor({
1249 pageDelayMs: 0,
1250 getKey: (x) => x.id,
1251 fetchPage: async () => {
1252 emptyCalls += 1;
1253 return { success: true, items: [], cursor: `empty-${emptyCalls}` };
1254 },
1255 });
1256
1257 // 3) Rotating unique cursors with only duplicate items (added === 0) stops
1258 let dupCalls = 0;
1259 const dupRes = await paginateCursor({
1260 pageDelayMs: 0,
1261 getKey: (x) => x.id,
1262 fetchPage: async () => {
1263 dupCalls += 1;
1264 return { success: true, items: [{ id: 'same' }], cursor: `dup-${dupCalls}` };
1265 },
1266 });
1267
1268 // 4) maxPages: 0, -1, NaN, Infinity never call fetchPage
1269 let guardCalls = 0;
1270 const guardFetch = async () => { guardCalls += 1; return { success: true, items: [{ id: 'x' }], cursor: 'C' }; };
1271 const zeroRes = await paginateCursor({ maxPages: 0, cursor: 'init', getKey: (x) => x.id, fetchPage: guardFetch });
1272 const negRes = await paginateCursor({ maxPages: -3, cursor: 'init', getKey: (x) => x.id, fetchPage: guardFetch });
1273 const nanRes = await paginateCursor({ maxPages: Number.NaN, getKey: (x) => x.id, fetchPage: guardFetch });
1274 const infRes = await paginateCursor({ maxPages: Number.POSITIVE_INFINITY, getKey: (x) => x.id, fetchPage: guardFetch });
1275
1276 process.stdout.write(JSON.stringify({
1277 cycleCalls, cycleLen: cycleRes.items.length, cycleNext: cycleRes.nextCursor ?? null,
1278 emptyCalls, emptyLen: emptyRes.items.length,
1279 dupCalls, dupLen: dupRes.items.length,
1280 guardCalls, zeroRes, negRes, nanRes, infRes,
1281 }));
1282 """
1283 )
1284 res = _node_eval(script)
1285 assert res.returncode == 0, res.stderr
1286 data = json.loads(res.stdout)
1287 assert data["cycleCalls"] == 3
1288 assert data["cycleLen"] == 3
1289 assert data["cycleNext"] is None
1290 assert data["emptyCalls"] == 1
1291 assert data["emptyLen"] == 0
1292 assert data["dupCalls"] == 2
1293 assert data["dupLen"] == 1
1294 assert data["guardCalls"] == 0
1295 assert data["zeroRes"] == {"success": True, "items": [], "nextCursor": "init"}
1296 assert data["negRes"] == {"success": True, "items": [], "nextCursor": "init"}
1297 assert data["nanRes"]["success"] is False
1298 assert data["infRes"]["success"] is False
1299
1300 def test_search_paged_handles_cycles_max_pages_zero_default_cap_and_partial_page_failure(self):
1301 script = textwrap.dedent(
1302 """
1303 import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js';
1304 import { withSearch } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-search.js';
1305
1306 const Client = withSearch(TwitterClientBase);
1307
1308 function makePageBody(tweets, nextCursor) {
1309 const entries = tweets.map((t) => ({
1310 entryId: `tweet-${t.id}`,
1311 content: {
1312 itemContent: {
1313 tweet_results: {
1314 result: {
1315 __typename: 'Tweet',
1316 rest_id: t.id,
1317 legacy: {
1318 id_str: t.id,
1319 full_text: t.text,
1320 created_at: 'Wed May 15 12:00:00 +0000 2026',
1321 },
1322 core: {
1323 user_results: {
1324 result: {
1325 rest_id: '42',
1326 legacy: { screen_name: 'tester', name: 'Tester' },
1327 },
1328 },
1329 },
1330 },
1331 },
1332 },
1333 },
1334 }));
1335 if (nextCursor) {
1336 entries.push({
1337 entryId: 'cursor-bottom-0',
1338 content: { cursorType: 'Bottom', value: nextCursor },
1339 });
1340 }
1341 return JSON.stringify({
1342 data: {
1343 search_by_raw_query: {
1344 search_timeline: {
1345 timeline: {
1346 instructions: [{ type: 'TimelineAddEntries', entries }],
1347 },
1348 },
1349 },
1350 },
1351 });
1352 }
1353
1354 const client = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' }, timeoutMs: 2000 });
1355
1356 // 1) maxPages: 0 & NaN perform 0 fetches
1357 let zeroCalls = 0;
1358 globalThis.fetch = async () => { zeroCalls += 1; return new Response(makePageBody([], null), { status: 200 }); };
1359 const zeroRes = await client.searchPaged('q', 20, { maxPages: 0, cursor: 'c0' });
1360 const nanRes = await client.searchPaged('q', 20, { maxPages: Number.NaN });
1361
1362 // 2) Multi-step cycle A -> B -> A terminates cleanly
1363 let cycleCalls = 0;
1364 globalThis.fetch = async (url) => {
1365 cycleCalls += 1;
1366 const vars = JSON.parse(new URL(String(url)).searchParams.get('variables'));
1367 if (!vars.cursor) return new Response(makePageBody([{ id: '1', text: 'p1' }], 'A'), { status: 200 });
1368 if (vars.cursor === 'A') return new Response(makePageBody([{ id: '2', text: 'p2' }], 'B'), { status: 200 });
1369 return new Response(makePageBody([{ id: '3', text: 'p3' }], 'A'), { status: 200 });
1370 };
1371 const cycleRes = await client.searchPaged('q', 60);
1372
1373 // 3) Default page cap prevents 60 sequential requests when each page yields 1 tweet
1374 let capCalls = 0;
1375 globalThis.fetch = async () => {
1376 capCalls += 1;
1377 return new Response(makePageBody([{ id: String(100 + capCalls), text: 'one' }], `cur-${capCalls}`), { status: 200 });
1378 };
1379 const capRes = await client.searchPaged('q', 60);
1380
1381 // 4) Unlimited getAllSearchResults also respects a hard default cap
1382 let unlimCalls = 0;
1383 globalThis.fetch = async () => {
1384 unlimCalls += 1;
1385 return new Response(makePageBody([{ id: String(1000 + unlimCalls), text: 'u' }], `ucur-${unlimCalls}`), { status: 200 });
1386 };
1387 const unlimRes = await client.getAllSearchResults('q');
1388
1389 // 5) Page 2 failure preserves already-fetched page 1 tweets
1390 let partialCalls = 0;
1391 globalThis.fetch = async () => {
1392 partialCalls += 1;
1393 if (partialCalls === 1) {
1394 return new Response(makePageBody([{ id: '501', text: 'kept' }], 'page2'), { status: 200 });
1395 }
1396 return new Response('upstream boom', { status: 500 });
1397 };
1398 const partialRes = await client.searchPaged('q', 20);
1399
1400 process.stdout.write(JSON.stringify({
1401 zeroCalls, zeroRes, nanRes,
1402 cycleCalls, cycleIds: cycleRes.tweets.map((t) => t.id),
1403 capCalls, capLen: capRes.tweets.length,
1404 unlimCalls, unlimLen: unlimRes.tweets.length,
1405 partialSuccess: partialRes.success,
1406 partialIds: (partialRes.tweets || []).map((t) => t.id),
1407 partialNextCursor: partialRes.nextCursor ?? null,
1408 }));
1409 """
1410 )
1411 res = _node_eval(script)
1412 assert res.returncode == 0, res.stderr
1413 data = json.loads(res.stdout)
1414 assert data["zeroCalls"] == 0
1415 assert data["zeroRes"] == {"success": True, "tweets": [], "nextCursor": "c0"}
1416 assert data["nanRes"]["success"] is False
1417 assert data["cycleCalls"] == 3
1418 assert data["cycleIds"] == ["1", "2", "3"]
1419 # For limit=60, pageSize=20 -> Math.min(10, ceil(60/20)+2) = 5 pages max
1420 assert data["capCalls"] == 5
1421 assert data["capLen"] == 5
1422 assert data["unlimCalls"] == 20
1423 assert data["unlimLen"] == 20
1424 assert data["partialSuccess"] is False
1425 assert data["partialIds"] == ["501"]
1426 assert data["partialNextCursor"] == "page2"
1427
1428 def test_bird_x_end_to_end_preserves_page1_partial_tweets_on_page2_failure(self, tmp_path):
1429 stub = tmp_path / "stub-page2-fail.mjs"
1430 stub.write_text(
1431 textwrap.dedent(
1432 """
1433 let calls = 0;
1434 globalThis.fetch = async (url) => {
1435 calls += 1;
1436 if (calls === 1) {
1437 const body = {
1438 data: {
1439 search_by_raw_query: {
1440 search_timeline: {
1441 timeline: {
1442 instructions: [{
1443 type: 'TimelineAddEntries',
1444 entries: [
1445 {
1446 entryId: 'tweet-701',
1447 content: {
1448 itemContent: {
1449 tweet_results: {
1450 result: {
1451 __typename: 'Tweet',
1452 rest_id: '701',
1453 legacy: {
1454 id_str: '701',
1455 full_text: 'partial page1 mention of @target',
1456 created_at: 'Wed May 15 12:00:00 +0000 2026',
1457 },
1458 core: {
1459 user_results: {
1460 result: {
1461 rest_id: '10',
1462 legacy: { screen_name: 'observer', name: 'Observer' },
1463 },
1464 },
1465 },
1466 },
1467 },
1468 },
1469 },
1470 },
1471 {
1472 entryId: 'tweet-702',
1473 content: {
1474 itemContent: {
1475 tweet_results: {
1476 result: {
1477 __typename: 'Tweet',
1478 rest_id: '702',
1479 legacy: {
1480 id_str: '702',
1481 full_text: 'own post by target',
1482 created_at: 'Wed May 15 12:01:00 +0000 2026',
1483 },
1484 core: {
1485 user_results: {
1486 result: {
1487 rest_id: '11',
1488 legacy: { screen_name: 'target', name: 'Target' },
1489 },
1490 },
1491 },
1492 },
1493 },
1494 },
1495 },
1496 },
1497 {
1498 entryId: 'cursor-bottom-0',
1499 content: { cursorType: 'Bottom', value: 'cursor-page-2' },
1500 },
1501 ],
1502 }],
1503 },
1504 },
1505 },
1506 },
1507 };
1508 return new Response(JSON.stringify(body), {
1509 status: 200,
1510 headers: { 'content-type': 'application/json' },
1511 });
1512 }
1513 return new Response('page 2 upstream error', { status: 500 });
1514 };
1515 """
1516 ),
1517 encoding="utf-8",
1518 )
1519 real_run = bird_x.subproc.run_with_timeout
1520 spawn_count = 0
1521
1522 def wrapped_run(cmd, **kwargs):
1523 nonlocal spawn_count
1524 spawn_count += 1
1525 env_copy = dict(kwargs.get("env") or {})
1526 env_copy["NODE_OPTIONS"] = f"--import={stub.as_uri()}"
1527 env_copy["AUTH_TOKEN"] = "dummy-auth-token-1234"
1528 env_copy["CT0"] = "dummy-ct0-token-5678"
1529 kwargs["env"] = env_copy
1530 return real_run(cmd, **kwargs)
1531
1532 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=wrapped_run):
1533 # 1) search_x preserves partial tweets and skips zero-result fallback retries
1534 topic_resp = bird_x.search_x(
1535 "multi-word partial topic test",
1536 "2026-05-01",
1537 "2026-05-31",
1538 depth="default",
1539 )
1540 assert spawn_count == 1
1541 assert "500" in topic_resp.get("error", "")
1542 parsed_topic = bird_x.parse_bird_response(topic_resp, query="partial")
1543 assert [it["url"] for it in parsed_topic] == [
1544 "https://x.com/observer/status/701",
1545 "https://x.com/target/status/702",
1546 ]
1547
1548 # 2) search_handles preserves page-1 tweets AND records error in failure_out
1549 handle_failures: list[str] = []
1550 handle_items = bird_x.search_handles(
1551 ["target"],
1552 "partial",
1553 "2026-05-01",
1554 count_per=25,
1555 failure_out=handle_failures,
1556 )
1557 assert len(handle_items) == 2
1558 assert handle_failures and any("500" in msg for msg in handle_failures)
1559
1560 # 3) search_mentions inspects stdout before returncode!=0, preserves third-party
1561 # mentions (dropping own tweet), AND records error in failure_out
1562 mention_failures: list[str] = []
1563 mention_items = bird_x.search_mentions(
1564 ["target"],
1565 "2026-05-01",
1566 count_per=25,
1567 failure_out=mention_failures,
1568 )
1569 assert [it["url"] for it in mention_items] == ["https://x.com/observer/status/701"]
1570 assert mention_failures and any("500" in msg for msg in mention_failures)
1571
1572 # 4) search_x retry returning partial items after an initial clean empty response
1573 # keeps the partial items instead of reverting to last_clean_response
1574 partial_retry = {
1575 "error": "HTTP 500: page 2 boom",
1576 "items": [{"id": "801", "text": "partial retry hit", "author": {"username": "alice"}}],
1577 }
1578 with mock.patch.object(
1579 bird_x,
1580 "_run_bird_search",
1581 side_effect=[{"items": []}, partial_retry],
1582 ):
1583 retry_resp = bird_x.search_x("alpha-beta gamma delta", "2026-05-01", "2026-05-31")
1584 assert retry_resp is partial_retry
1585 assert [it["url"] for it in bird_x.parse_bird_response(retry_resp)] == ["https://x.com/alice/status/801"]
1586 # Zero-item error still returns [] from parse_bird_response
1587 assert bird_x.parse_bird_response({"error": "HTTP 500", "items": []}) == []
1588
1589
1590 # ---------------------------------------------------------------------------
1591 # HIGH-160: cookies.js consent flags & bird_x.py failover/credential reset
1592 # ---------------------------------------------------------------------------
1593
1594
1595 class TestHigh160CookieConsentAndFailoverReset:
1596 def setup_method(self):
1597 self._saved_creds = dict(bird_x._credentials)
1598 self._saved_seen = set(bird_x._seen_secrets)
1599 self._saved_browser = bird_x._session_browser
1600 self._saved_next = bird_x._next_session
1601 bird_x._credentials.clear()
1602 bird_x.set_session_failover(None, None)
1603
1604 def teardown_method(self):
1605 bird_x._credentials.clear()
1606 bird_x._credentials.update(self._saved_creds)
1607 bird_x._seen_secrets.clear()
1608 bird_x._seen_secrets.update(self._saved_seen)
1609 bird_x.set_session_failover(self._saved_browser, self._saved_next)
1610
1611 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
1612 @pytest.mark.parametrize(
1613 "consent_env",
1614 [
1615 {"FROM_BROWSER": "off"},
1616 {"FROM_BROWSER": " OFF "},
1617 {"BROWSER_CONSENT": "false"},
1618 {"BROWSER_CONSENT": "0"},
1619 {"BROWSER_CONSENT": "no"},
1620 {"BROWSER_CONSENT": "off"},
1621 {"BROWSER_CONSENT": ""},
1622 {"BROWSER_CONSENT": " "},
1623 {"BROWSER_CONSENT": "maybe"},
1624 ],
1625 )
1626 def test_cookies_js_blocks_browser_extraction_on_from_browser_off_or_non_truthy_consent(
1627 self, tmp_path, consent_env
1628 ):
1629 register = _register_sweet_cookie_stub(tmp_path)
1630 run_env = os.environ.copy()
1631 for key in (
1632 "AUTH_TOKEN",
1633 "CT0",
1634 "TWITTER_AUTH_TOKEN",
1635 "TWITTER_CT0",
1636 "BIRD_DISABLE_BROWSER_COOKIES",
1637 "LAST30DAYS_DISABLE_BROWSER_COOKIES",
1638 "FROM_BROWSER",
1639 "BROWSER_CONSENT",
1640 ):
1641 run_env.pop(key, None)
1642 run_env.update(consent_env)
1643
1644 script = textwrap.dedent(
1645 """
1646 import { resolveCredentials } from './skills/last30days/scripts/lib/vendor/bird-search/lib/cookies.js';
1647 const res = await resolveCredentials({ cookieSource: ['safari', 'chrome'] });
1648 process.stdout.write(JSON.stringify(res));
1649 """
1650 )
1651 res = subprocess.run(
1652 ["node", "--import", register.as_uri(), "--input-type=module", "-e", script],
1653 cwd=REPO_ROOT,
1654 env=run_env,
1655 capture_output=True,
1656 text=True,
1657 check=False,
1658 )
1659 assert res.returncode == 0, res.stderr
1660 assert "SWEET_COOKIE_CALLED" not in res.stderr
1661 payload = json.loads(res.stdout)
1662 assert payload["cookies"]["authToken"] is None
1663 assert payload["cookies"]["ct0"] is None
1664 assert payload["warnings"]
1665
1666 def test_set_credentials_clears_stale_failover_and_removed_keys(self):
1667 failover_calls = []
1668
1669 def fake_next(deadline=None, cancel=None):
1670 failover_calls.append(True)
1671 return ("stale-browser-auth-9999", "stale-browser-ct0-9999", "chrome")
1672
1673 # Simulate prior browser-sourced run registering failover
1674 bird_x.set_credentials("browser-auth-token-1111", "browser-ct0-token-1111")
1675 bird_x.set_session_failover("safari", fake_next)
1676 assert bird_x._session_browser == "safari"
1677 assert bird_x._next_session is fake_next
1678
1679 # Subsequent explicit non-browser run calls env._inject_bird_credentials -> set_credentials only
1680 explicit_cfg = {
1681 "AUTH_TOKEN": "explicit-auth-token-2222",
1682 "CT0": "explicit-ct0-token-2222",
1683 "FROM_BROWSER": "off",
1684 "BROWSER_CONSENT": "false",
1685 }
1686 env._inject_bird_credentials(explicit_cfg)
1687 assert bird_x._session_browser is None
1688 assert bird_x._next_session is None
1689
1690 # A 401 or 500 must NOT invoke the stale browser failover callback
1691 search_401 = (
1692 SubprocResult(
1693 returncode=0,
1694 stdout='{"error": "HTTP 401: Could not authenticate you", "items": []}',
1695 stderr="",
1696 ),
1697 None,
1698 )
1699 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[search_401]):
1700 resp = bird_x._run_bird_search("topic", count=5, timeout=15)
1701 assert failover_calls == []
1702 assert "cookies from safari" not in resp["error"]
1703
1704 # Passing None/empty clears stale credentials while preserving retired secret scrubbing
1705 bird_x.set_credentials(None, None)
1706 assert bird_x._credentials == {}
1707 scrubbed = bird_x._scrub_credentials("leaked explicit-auth-token-2222 and browser-auth-token-1111")
1708 assert "explicit-auth-token-2222" not in scrubbed
1709 assert "browser-auth-token-1111" not in scrubbed
1710
1711 def test_internal_failover_preserves_multi_browser_rotation(self):
1712 rotations = [
1713 ("chrome-auth-token-3333", "chrome-ct0-token-3333", "chrome"),
1714 ("edge-auth-token-4444", "edge-ct0-token-4444", "edge"),
1715 ]
1716
1717 def next_browser(deadline=None, cancel=None):
1718 return rotations.pop(0) if rotations else None
1719
1720 bird_x.set_credentials("safari-auth-token-1111", "safari-ct0-token-1111")
1721 bird_x.set_session_failover("safari", next_browser)
1722
1723 err_401 = (SubprocResult(returncode=0, stdout='{"error": "HTTP 401: Could not authenticate you"}', stderr=""), None)
1724 ok_resp = (SubprocResult(returncode=0, stdout='[{"id": "1", "text": "ok"}]', stderr=""), None)
1725 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[err_401, err_401, ok_resp]):
1726 resp = bird_x._run_bird_search("topic", count=5, timeout=15)
1727
1728 assert resp["items"] == [{"id": "1", "text": "ok"}]
1729 assert bird_x._credentials["AUTH_TOKEN"] == "edge-auth-token-4444"
1730 assert bird_x._session_browser == "edge"
1731 assert bird_x._next_session is next_browser
1732
1733 def test_browser_failover_preserves_page1_partial_posts_when_retry_yields_nothing(self):
1734 partial_page1 = (
1735 SubprocResult(
1736 returncode=1,
1737 stdout=json.dumps({
1738 "error": "Internal server error",
1739 "items": [{"id": "901", "text": "page 1 tweet", "author": {"username": "alice"}}],
1740 }),
1741 stderr="",
1742 ),
1743 None,
1744 )
1745 empty_retry = (SubprocResult(returncode=0, stdout="[]", stderr=""), None)
1746 failed_retry = (
1747 SubprocResult(returncode=1, stdout='{"error": "HTTP 401: Could not authenticate you", "items": []}', stderr=""),
1748 None,
1749 )
1750 better_retry = (
1751 SubprocResult(
1752 returncode=0,
1753 stdout=json.dumps([
1754 {"id": "901", "text": "page 1 tweet", "author": {"username": "alice"}},
1755 {"id": "902", "text": "page 2 tweet", "author": {"username": "bob"}},
1756 ]),
1757 stderr="",
1758 ),
1759 None,
1760 )
1761
1762 # Case 1: Retry returns empty clean list -> keep safari's partial page-1 post
1763 rotations = [("chrome-auth-1111", "chrome-ct0-1111", "chrome")]
1764 bird_x.set_credentials("safari-auth-1111", "safari-ct0-1111")
1765 bird_x.set_session_failover("safari", lambda deadline=None, cancel=None: rotations.pop(0) if rotations else None)
1766 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[partial_page1, empty_retry]):
1767 resp = bird_x._run_bird_search("topic", count=20, timeout=15)
1768 assert [it["url"] for it in bird_x.parse_bird_response(resp)] == ["https://x.com/alice/status/901"]
1769
1770 # Case 2: Safari returns partial post + Internal server error, Chrome fails with 401 ->
1771 # keep Safari's partial page-1 post AND attribute Chrome's 401 error to Chrome (not Safari's error).
1772 rotations = [("chrome-auth-2222", "chrome-ct0-2222", "chrome")]
1773 bird_x.set_credentials("safari-auth-2222", "safari-ct0-2222")
1774 bird_x.set_session_failover("safari", lambda deadline=None, cancel=None: rotations.pop(0) if rotations else None)
1775 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[partial_page1, failed_retry]):
1776 resp2 = bird_x._run_bird_search("topic", count=20, timeout=15)
1777 assert [it["url"] for it in bird_x.parse_bird_response(resp2)] == ["https://x.com/alice/status/901"]
1778 assert "cookies from chrome" in resp2["error"]
1779 assert "HTTP 401" in resp2["error"]
1780 assert "Internal server error" not in resp2["error"]
1781
1782 # Case 2b: Chrome fails with a non-suspect error (e.g. HTTP 429) -> keep Safari's post + Chrome's error
1783 rate_limited_retry = (
1784 SubprocResult(returncode=1, stdout='{"error": "HTTP 429: Rate limit exceeded", "items": []}', stderr=""),
1785 None,
1786 )
1787 rotations = [("chrome-auth-2223", "chrome-ct0-2223", "chrome")]
1788 bird_x.set_credentials("safari-auth-2223", "safari-ct0-2223")
1789 bird_x.set_session_failover("safari", lambda deadline=None, cancel=None: rotations.pop(0) if rotations else None)
1790 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[partial_page1, rate_limited_retry]):
1791 resp2b = bird_x._run_bird_search("topic", count=20, timeout=15)
1792 assert [it["url"] for it in bird_x.parse_bird_response(resp2b)] == ["https://x.com/alice/status/901"]
1793 assert "HTTP 429" in resp2b["error"]
1794 assert "Internal server error" not in resp2b["error"]
1795
1796 # Case 3: Retry succeeds with clean posts -> retry wins
1797 rotations = [("chrome-auth-3333", "chrome-ct0-3333", "chrome")]
1798 bird_x.set_credentials("safari-auth-3333", "safari-ct0-3333")
1799 bird_x.set_session_failover("safari", lambda deadline=None, cancel=None: rotations.pop(0) if rotations else None)
1800 with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[partial_page1, better_retry]):
1801 resp3 = bird_x._run_bird_search("topic", count=20, timeout=15)
1802 assert "error" not in resp3
1803 assert [it["url"] for it in bird_x.parse_bird_response(resp3)] == [
1804 "https://x.com/alice/status/901",
1805 "https://x.com/bob/status/902",
1806 ]
1807
1808
1809 # ---------------------------------------------------------------------------
1810 # HIGH-161: cancel, deadline_monotonic & capture_limit_bytes forwarded to subproc
1811 # ---------------------------------------------------------------------------
1812
1813
1814 class TestHigh161SubprocessLifecycleForwarding:
1815 def test_all_three_bird_call_sites_forward_cancel_deadline_and_capture_limit(self):
1816 cancel = threading.Event()
1817 deadline = time.monotonic() + 30.0
1818 seen_kwargs: list[dict] = []
1819
1820 def fake_run(cmd, **kwargs):
1821 seen_kwargs.append(kwargs)
1822 return SubprocResult(returncode=0, stdout="[]", stderr="")
1823
1824 with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run):
1825 bird_x._invoke_bird_subprocess("hello", count=5, timeout=10, deadline=deadline, cancel=cancel)
1826 bird_x.search_handles(["alice"], "topic", "2026-05-01", count_per=2, deadline=deadline, cancel=cancel)
1827 bird_x.search_mentions(["alice"], "2026-05-01", count_per=2, deadline=deadline, cancel=cancel)
1828
1829 assert len(seen_kwargs) == 3
1830 for kw in seen_kwargs:
1831 assert kw["cancel"] is cancel
1832 assert kw["deadline_monotonic"] == deadline
1833 assert kw["capture_limit_bytes"] == bird_x._BIRD_CAPTURE_LIMIT_BYTES
1834 assert kw["capture_limit_bytes"] == 8 * 1024 * 1024
1835
1836 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
1837 def test_setting_cancel_terminates_inflight_node_subprocess_promptly(self, tmp_path):
1838 sleeper = tmp_path / "sleeper.mjs"
1839 sleeper.write_text("setTimeout(() => {}, 30000);\n", encoding="utf-8")
1840
1841 cancel = threading.Event()
1842 timer = threading.Timer(0.2, cancel.set)
1843 timer.start()
1844 started = time.monotonic()
1845 try:
1846 with mock.patch.object(bird_x, "_BIRD_SEARCH_MJS", sleeper):
1847 result, err = bird_x._invoke_bird_subprocess(
1848 "hello",
1849 count=1,
1850 timeout=15,
1851 deadline=time.monotonic() + 15.0,
1852 cancel=cancel,
1853 )
1854 finally:
1855 timer.cancel()
1856 elapsed = time.monotonic() - started
1857 assert result is None
1858 assert err is not None
1859 assert "cancelled" in err["error"].lower()
1860 assert elapsed < 3.0
1861
1862 @pytest.mark.skipif(not HAS_NODE, reason="node is required")
1863 def test_setting_cancel_terminates_inflight_handle_and_mention_workers_promptly(self, tmp_path):
1864 sleeper = tmp_path / "sleeper-lane.mjs"
1865 sleeper.write_text("setTimeout(() => {}, 30000);\n", encoding="utf-8")
1866
1867 for lane in ("handles", "mentions"):
1868 cancel = threading.Event()
1869 failures: list[str] = []
1870 timer = threading.Timer(0.2, cancel.set)
1871 timer.start()
1872 started = time.monotonic()
1873 try:
1874 with mock.patch.object(bird_x, "_BIRD_SEARCH_MJS", sleeper):
1875 if lane == "handles":
1876 items = bird_x.search_handles(
1877 ["alice", "bob"],
1878 "topic",
1879 "2026-05-01",
1880 count_per=1,
1881 failure_out=failures,
1882 deadline=time.monotonic() + 15.0,
1883 cancel=cancel,
1884 )
1885 else:
1886 items = bird_x.search_mentions(
1887 ["alice", "bob"],
1888 "2026-05-01",
1889 count_per=1,
1890 failure_out=failures,
1891 deadline=time.monotonic() + 15.0,
1892 cancel=cancel,
1893 )
1894 finally:
1895 timer.cancel()
1896 elapsed = time.monotonic() - started
1897 assert items == []
1898 assert elapsed < 3.0
1899 assert failures and any("cancelled" in msg.lower() for msg in failures)
1900
1900 lines PYTHON