Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(youtube): stop comparison-mode search timeouts under fan-out (#901)

Trevin Chow5cc8e7ccebd1
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 3d9e7788..8c8810ae 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -160,7 +160,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \
| Jobs / careers pages | none for public ATS pages; web backend improves fallback discovery | `--hiring-signals` and strong Hiring Signals in standard company reports | yes |
| Apify (alternate scraper) | `APIFY_API_TOKEN` | fallback for Reddit/TikTok/Instagram when ScrapeCreators is exhausted | yes (limited) |
-**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded.
+**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.
**X on cookie-less hosts.** Bird (the free X source) scrapes X using your logged-in browser cookies (`AUTH_TOKEN`/`CT0`), which agent hosts like OpenClaw, CI, or headless runs often can't supply — and scraping carries some account risk. On those, set `XQUIK_API_KEY` (or `XAI_API_KEY`) for full, ranked X coverage from a single API key: the same engagement-based ranking, first-party authorship, and handle (from/mentions) lanes the native X source gets. `--diagnose` reports whether the key is working (and flags an unpaid key).
diff --git a/changelog.d/+youtube-search-fanout-timeout.fixed.md b/changelog.d/+youtube-search-fanout-timeout.fixed.md
new file mode 100644
index 00000000..a2999fc7
--- /dev/null
+++ b/changelog.d/+youtube-search-fanout-timeout.fixed.md
@@ -0,0 +1 @@
+YouTube yt-dlp search under comparison-mode fan-out no longer self-throttles into 120s timeouts: concurrent yt-dlp invocations are process-wide capped, identical searches are deduped within a run, and a search timeout is recorded as `timeout` rather than `no-results`. `LAST30DAYS_YT_SEARCH_TIMEOUT` configures the search deadline.
diff --git a/skills/last30days/scripts/lib/competitors.py b/skills/last30days/scripts/lib/competitors.py
index 0a7c7e22..f246d1de 100644
--- a/skills/last30days/scripts/lib/competitors.py
+++ b/skills/last30days/scripts/lib/competitors.py
@@ -24,6 +24,9 @@ COMPETITORS_MIN = 1
COMPETITORS_MAX = 6
COMPETITORS_DEFAULT = 2
COMPARISON_ENTITY_MAX = COMPETITORS_MAX + 1
+# Discovery SERP fan-out is small (3 queries today) but still needs a ceiling
+# so a future query expansion cannot open one worker per query unbounded.
+MAX_DISCOVERY_WORKERS = 3
# A "brand-shaped" token starts with uppercase OR is camelCase with an
# uppercase letter later. Catches "Anthropic", "OpenAI", "xAI", "iPhone",
@@ -178,7 +181,7 @@ def discover_competitors(
items, _artifact = grounding.web_search(query, date_range, config)
return label, items
- with ThreadPoolExecutor(max_workers=len(queries)) as executor:
+ with ThreadPoolExecutor(max_workers=min(len(queries), MAX_DISCOVERY_WORKERS)) as executor:
futures = {
executor.submit(_search, label, q): label
for label, q in queries.items()
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index eb57d3b6..78da3a1e 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -565,6 +565,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('GROQ_API_KEY', None),
('LAST30DAYS_YT_SUB_LANGS', 'en,es,pt'),
('LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT', None),
+ ('LAST30DAYS_YT_SEARCH_TIMEOUT', None),
('GITHUB_TOKEN', None),
]
@@ -579,16 +580,13 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
# youtube_yt reads these tuning knobs lazily from os.environ, so values
# loaded from .env must be exported into the current engine process.
- if config.get('LAST30DAYS_YT_SUB_LANGS'):
- os.environ.setdefault(
- 'LAST30DAYS_YT_SUB_LANGS',
- config['LAST30DAYS_YT_SUB_LANGS'],
- )
- if config.get('LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT'):
- os.environ.setdefault(
- 'LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT',
- config['LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT'],
- )
+ for key in (
+ 'LAST30DAYS_YT_SUB_LANGS',
+ 'LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT',
+ 'LAST30DAYS_YT_SEARCH_TIMEOUT',
+ ):
+ if config.get(key):
+ os.environ.setdefault(key, config[key])
# Backward-compat: ScrapeCreators' own examples and tutorials use the
# SCRAPE_CREATORS_API_KEY spelling (with underscore between SCRAPE and
diff --git a/skills/last30days/scripts/lib/fanout.py b/skills/last30days/scripts/lib/fanout.py
index 945ed8ab..2ccc4ad9 100644
--- a/skills/last30days/scripts/lib/fanout.py
+++ b/skills/last30days/scripts/lib/fanout.py
@@ -16,7 +16,7 @@ from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable
-from . import log, schema
+from . import log, schema, youtube_yt
# Sub-runs hit the same upstream APIs as the main topic. Cap parallelism so a
# 6-way fan-out does not stampede a single backend's rate limit.
@@ -51,6 +51,10 @@ def run_competitor_fanout(
report = main_runner()
return [(main_topic, report)]
+ # One clear for the whole comparison so entity sub-runs share the YouTube
+ # search cache without inheriting a prior run's results in this process.
+ youtube_yt.reset_search_cache()
+
workers = min(len(competitors) + 1, MAX_PARALLEL_SUBRUNS)
def _run_one(label: str, fn: Callable[[], schema.Report]) -> tuple[str, schema.Report | None, Exception | None]:
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index dcead0a9..574ed602 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -888,6 +888,7 @@ def enrich_nominations(
# real - stragglers cannot delay process exit. Abandonment is safe because
# internal_subrun passes write nothing to disk (no save, no library sync,
# no store), and every fetch layer inside run() carries its own timeout.
+ youtube_yt.reset_search_cache()
enriched: dict[str, EnrichedTopic] = {}
results_queue: queue.Queue[tuple[Nomination, schema.Report | None, Exception | None]] = queue.Queue()
slots = threading.Semaphore(max(1, max_workers))
@@ -1910,6 +1911,11 @@ def run(
corpus_dirs: list[str] | None = None,
corpus_all_time: bool = False,
) -> schema.Report:
+ # Standalone runs (not competitor/discover sub-runs) own the YouTube
+ # search-cache lifecycle. Comparison fan-out clears once before submit so
+ # parallel entity sub-runs can still share in-run hits.
+ if not internal_subrun:
+ youtube_yt.reset_search_cache()
settings = _resolve_depth_settings(depth, config)
requested_sources = normalize_requested_sources(requested_sources)
from_date, to_date = dates.get_date_range(lookback_days, as_of_date=as_of_date)
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index c5ed195b..393098c0 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -6,6 +6,7 @@ transcript extraction. No API keys needed — just have yt-dlp installed.
Inspired by Peter Steinberger's toolchain approach (yt-dlp + summarize CLI).
"""
+import copy
import json
import math
import os
@@ -14,6 +15,7 @@ import shlex
import shutil
import sys
import tempfile
+import threading
import time
import urllib.error
import urllib.request
@@ -71,6 +73,18 @@ _TRANSCRIPT_MAX_RETRIES = 2
_TRANSCRIPT_BACKOFF_BASE = 2.0 # seconds; multiplied by (attempt + 1)
_TRANSCRIPT_TIMEOUT = 30 # seconds per yt-dlp attempt (keyless: no fallback to fail over to)
_TRANSCRIPT_FAST_TIMEOUT = 12 # seconds per attempt when a ScrapeCreators fallback exists
+_SEARCH_TIMEOUT = 120 # seconds per ytsearch metadata extraction
+# Comparison-mode fan-out (and nested transcript/comment pools) can stampede the
+# same throttled YouTube IP. Cap concurrent yt-dlp processes process-wide.
+_YTDLP_MAX_CONCURRENT = 2
+_ytdlp_slots = threading.Semaphore(_YTDLP_MAX_CONCURRENT)
+# In-run search cache: comparison mode re-issues identical ytsearch queries from
+# every entity sub-run; cache hits avoid the redundant expensive --dump-json work.
+# Inflight coalescing prevents N concurrent identical searches from all missing
+# the cache and stampeding YouTube together.
+_search_cache: Dict[Tuple[str, int, str], Dict[str, Any]] = {}
+_search_inflight: Dict[Tuple[str, int, str], tuple[threading.Event, list]] = {}
+_search_cache_lock = threading.Lock()
# Comments are enrichment, not core evidence: keep the budget tight so a slow
# comment API can never dominate a run's wall clock (bounded to 3 videos).
_COMMENT_TIMEOUT = 20
@@ -146,11 +160,118 @@ def _log(msg: str):
log.source_log("YouTube", msg, tty_only=False)
+def reset_search_cache() -> None:
+ """Clear the in-run ytsearch cache.
+
+ Call at the start of each top-level research run so a long-lived process
+ (agent host, REPL, test suite) does not reuse results across runs. Within
+ one comparison fan-out the cache stays hot so identical queries coalesce.
+ """
+ with _search_cache_lock:
+ _search_cache.clear()
+ _search_inflight.clear()
+
+
+def _env_positive_float(name: str, default: float) -> float:
+ """Read a positive finite float from the environment, else ``default``."""
+ raw = os.environ.get(name, "").strip()
+ try:
+ value = float(raw) if raw else float(default)
+ except ValueError:
+ return float(default)
+ if not math.isfinite(value) or value <= 0:
+ return float(default)
+ return value
+
+
+def _search_timeout() -> float:
+ """Return the ytsearch timeout, preserving the 120s default."""
+ return _env_positive_float("LAST30DAYS_YT_SEARCH_TIMEOUT", float(_SEARCH_TIMEOUT))
+
+
+def _run_ytdlp(cmd: List[str], *, timeout: float) -> subproc.SubprocResult:
+ """Run a yt-dlp (or SSH-wrapped) command under the process-wide concurrency gate."""
+ with _ytdlp_slots:
+ return subproc.run_with_timeout(cmd, timeout=timeout)
+
+
+def _claim_search_slot(
+ cache_key: Tuple[str, int, str],
+) -> tuple[Optional[Dict[str, Any]], Optional[threading.Event], Optional[list], bool]:
+ """Return ``(cached, event, slot, is_leader)`` for search coalesce.
+
+ - Cache hit: ``(payload, None, None, False)`` — caller returns ``payload``.
+ - Waiter: ``(None, event, slot, False)`` — caller awaits ``slot`` via ``event``.
+ - Leader: ``(None, event, slot, True)`` — caller runs yt-dlp and finishes the slot.
+ """
+ with _search_cache_lock:
+ cached = _search_cache.get(cache_key)
+ if cached is not None:
+ return copy.deepcopy(cached), None, None, False
+ existing = _search_inflight.get(cache_key)
+ if existing is not None:
+ return None, existing[0], existing[1], False
+ event = threading.Event()
+ slot: list = [None]
+ _search_inflight[cache_key] = (event, slot)
+ return None, event, slot, True
+
+
+def _finish_search_slot(
+ cache_key: Tuple[str, int, str],
+ payload: Dict[str, Any],
+ *,
+ event: threading.Event,
+ slot: list,
+) -> Dict[str, Any]:
+ """Publish a search result to waiters; cache only clean (non-error) payloads.
+
+ Ownership is by slot identity: after ``reset_search_cache()`` clears the
+ registry, a stale leader must still wake its own waiters but must not pop
+ or overwrite a newer run's registration for the same key.
+ """
+ shared = copy.deepcopy(payload)
+ with _search_cache_lock:
+ if slot[0] is not None:
+ # Idempotent re-finish of this slot (e.g. finally after return).
+ event.set()
+ return payload
+ slot[0] = shared
+ current = _search_inflight.get(cache_key)
+ if current is not None and current[1] is slot:
+ if not payload.get("error"):
+ _search_cache[cache_key] = shared
+ _search_inflight.pop(cache_key, None)
+ # else: stale leader after a reset — wake local waiters only.
+ event.set()
+ return payload
+
+
+def _await_search_slot(
+ event: threading.Event,
+ slot: list,
+) -> Dict[str, Any]:
+ """Wait for a leader search to publish.
+
+ Waiters block until the leader finishes (success or failure). The leader
+ path always publishes via ``_finish_search_slot``, including on unexpected
+ exceptions, so a timed wait would only invent a false timeout while the
+ leader was still queued behind other yt-dlp work.
+ """
+ event.wait()
+ shared = slot[0]
+ if isinstance(shared, dict):
+ return copy.deepcopy(shared)
+ return {"items": [], "error": "YouTube search failed"}
+
+
def classify_run_failure(detail: str) -> str:
"""Map yt-dlp's text-only throttling and bot-gate errors."""
text = detail.lower()
if any(marker in text for marker in ("yt-dlp not installed", "yt-dlp not found")):
return health.SKIPPED_UNCONFIGURED
+ if any(marker in text for marker in ("timed out", "timeout")):
+ return health.TIMEOUT
if any(
marker in text
for marker in ("http error 429", "confirm you're not a bot", "confirm you’re not a bot", "bot-gate")
@@ -317,6 +438,20 @@ def search_youtube(
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
core_topic = _extract_core_subject(topic)
+ cache_key = (core_topic, count, from_date)
+ timeout = _search_timeout()
+
+ cached, event, slot, is_leader = _claim_search_slot(cache_key)
+ if cached is not None:
+ _log(f"YouTube search cache hit for '{core_topic}' (count={count})")
+ return cached
+ assert event is not None and slot is not None
+ if not is_leader:
+ _log(f"YouTube search awaiting in-flight query for '{core_topic}'")
+ return _await_search_slot(event, slot)
+
+ def _publish(payload: Dict[str, Any]) -> Dict[str, Any]:
+ return _finish_search_slot(cache_key, payload, event=event, slot=slot)
_log(f"Searching YouTube for '{core_topic}' (since {from_date}, count={count})")
@@ -336,82 +471,97 @@ def search_youtube(
cmd = _wrap_ytdlp_cmd(cmd)
ssh_host = _ytdlp_ssh_host()
+ published: Dict[str, Any] | None = None
try:
- result = subproc.run_with_timeout(cmd, timeout=120)
- except subproc.SubprocTimeout:
- _log("YouTube search timed out (120s)")
- return {"items": [], "error": "Search timed out"}
- except FileNotFoundError:
- return {"items": [], "error": "yt-dlp not found"}
-
- stdout = result.stdout
- if ssh_host and result.returncode != 0 and not stdout.strip():
- stderr_first = (result.stderr or "").strip().splitlines()
- first_line = stderr_first[0] if stderr_first else "(no stderr)"
- _log(
- f"YouTube search via SSH host {ssh_host!r} failed "
- f"(rc={result.returncode}): {first_line}"
- )
- return {
- "items": [],
- "error": f"SSH routing to {ssh_host!r} failed: {first_line}",
- }
- if not stdout.strip():
- _log("YouTube search returned 0 results")
- return {"items": []}
-
- # Parse JSON-per-line output
- items = []
- for line in stdout.strip().split("\n"):
- line = line.strip()
- if not line:
- continue
try:
- video = json.loads(line)
- except json.JSONDecodeError:
- continue
-
- video_id = video.get("id", "")
- view_count = video.get("view_count") if video.get("view_count") is not None else 0
- like_count = video.get("like_count") if video.get("like_count") is not None else 0
- comment_count = video.get("comment_count") if video.get("comment_count") is not None else 0
- upload_date = video.get("upload_date", "") # YYYYMMDD
-
- # Convert YYYYMMDD to YYYY-MM-DD
- date_str = None
- if upload_date and len(upload_date) == 8:
- date_str = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
-
- description = str(video.get("description", ""))[:500]
- items.append({
- "video_id": video_id,
- "title": video.get("title", ""),
- "url": f"https://www.youtube.com/watch?v={video_id}",
- "channel_name": video.get("channel", video.get("uploader", "")),
- "date": date_str,
- "engagement": {
- "views": view_count,
- "likes": like_count,
- "comments": comment_count,
- },
- "duration": video.get("duration"),
- "relevance": _compute_relevance(core_topic, f"{video.get('title', '')} {description}"),
- "why_relevant": f"YouTube: {video.get('title', core_topic)[:60]}",
- "description": description,
- })
-
- # Soft date filter: prefer recent items but fall back to all if too few
- recent = [i for i in items if i["date"] and i["date"] >= from_date]
- if len(recent) >= 3:
- items = recent
- _log(f"Found {len(items)} videos within date range")
- else:
- _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
+ result = _run_ytdlp(cmd, timeout=timeout)
+ except subproc.SubprocTimeout:
+ _log(f"YouTube search timed out ({timeout:g}s)")
+ published = _publish(
+ {"items": [], "error": f"Search timed out after {timeout:g}s"}
+ )
+ return published
+ except FileNotFoundError:
+ published = _publish({"items": [], "error": "yt-dlp not found"})
+ return published
- # Sort by views descending
- items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
+ stdout = result.stdout
+ if ssh_host and result.returncode != 0 and not stdout.strip():
+ stderr_first = (result.stderr or "").strip().splitlines()
+ first_line = stderr_first[0] if stderr_first else "(no stderr)"
+ _log(
+ f"YouTube search via SSH host {ssh_host!r} failed "
+ f"(rc={result.returncode}): {first_line}"
+ )
+ published = _publish(
+ {"items": [], "error": f"SSH routing to {ssh_host!r} failed: {first_line}"},
+ )
+ return published
+ if not stdout.strip():
+ _log("YouTube search returned 0 results")
+ published = _publish({"items": []})
+ return published
+
+ # Parse JSON-per-line output
+ items = []
+ for line in stdout.strip().split("\n"):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ video = json.loads(line)
+ except json.JSONDecodeError:
+ continue
- return {"items": items}
+ video_id = video.get("id", "")
+ view_count = video.get("view_count") if video.get("view_count") is not None else 0
+ like_count = video.get("like_count") if video.get("like_count") is not None else 0
+ comment_count = video.get("comment_count") if video.get("comment_count") is not None else 0
+ upload_date = video.get("upload_date", "") # YYYYMMDD
+
+ # Convert YYYYMMDD to YYYY-MM-DD
+ date_str = None
+ if upload_date and len(upload_date) == 8:
+ date_str = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
+
+ description = str(video.get("description", ""))[:500]
+ items.append({
+ "video_id": video_id,
+ "title": video.get("title", ""),
+ "url": f"https://www.youtube.com/watch?v={video_id}",
+ "channel_name": video.get("channel", video.get("uploader", "")),
+ "date": date_str,
+ "engagement": {
+ "views": view_count,
+ "likes": like_count,
+ "comments": comment_count,
+ },
+ "duration": video.get("duration"),
+ "relevance": _compute_relevance(core_topic, f"{video.get('title', '')} {description}"),
+ "why_relevant": f"YouTube: {video.get('title', core_topic)[:60]}",
+ "description": description,
+ })
+
+ # Soft date filter: prefer recent items but fall back to all if too few
+ recent = [i for i in items if i["date"] and i["date"] >= from_date]
+ if len(recent) >= 3:
+ items = recent
+ _log(f"Found {len(items)} videos within date range")
+ else:
+ _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
+
+ # Sort by views descending
+ items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
+ published = _publish({"items": items})
+ return published
+ except Exception as exc:
+ # Post-subprocess failures (parse/relevance/sort) must still unblock
+ # coalesced waiters — otherwise the inflight key orphans forever.
+ published = _publish({"items": [], "error": str(exc)})
+ return published
+ finally:
+ if published is None:
+ _publish({"items": [], "error": "YouTube search failed"})
def _clean_vtt(vtt_text: str) -> str:
@@ -564,7 +714,7 @@ def _fetch_transcript_ytdlp_via_ssh(video_id: str, ssh_host: str) -> Optional[st
)
cmd = ["ssh", "-o", "BatchMode=yes", "--", ssh_host, remote_script]
try:
- result = subproc.run_with_timeout(cmd, timeout=45)
+ result = _run_ytdlp(cmd, timeout=45)
except subproc.SubprocTimeout:
_log(f"SSH yt-dlp transcript timed out for {video_id} via {ssh_host!r}")
return None
@@ -593,15 +743,10 @@ def _ytdlp_sub_langs() -> str:
def _transcript_fast_timeout() -> float:
"""Return the keyed-run yt-dlp timeout, preserving the 12s default."""
- raw = os.environ.get("LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT", "").strip()
- try:
- timeout = float(raw) if raw else float(_TRANSCRIPT_FAST_TIMEOUT)
- except ValueError:
- return float(_TRANSCRIPT_FAST_TIMEOUT)
- if not math.isfinite(timeout) or timeout <= 0:
- return float(_TRANSCRIPT_FAST_TIMEOUT)
- return timeout
-
+ return _env_positive_float(
+ "LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT",
+ float(_TRANSCRIPT_FAST_TIMEOUT),
+ )
def _pick_ytdlp_vtt(video_id: str, temp_dir: str, priority: List[str]) -> Optional[Path]:
"""Return the best on-disk VTT match for video_id, preferring priority order."""
@@ -686,7 +831,7 @@ def _fetch_transcript_ytdlp(
last_reason: Optional[str] = None
for attempt in range(attempts):
try:
- result = subproc.run_with_timeout(cmd, timeout=timeout)
+ result = _run_ytdlp(cmd, timeout=timeout)
except subproc.SubprocTimeout:
last_reason = f"timed out after {timeout}s"
_log(f"yt-dlp transcript timed out after {timeout}s for {video_id} "
@@ -984,6 +1129,22 @@ def _transcript_candidate_sort_key(item: dict) -> tuple:
return (views, recency)
+def _prefer_search_error(current: Optional[str], new: str) -> str:
+ """Keep the most actionable search failure across multi-query merges."""
+ if current is None:
+ return new
+ priority = ("timed out", "timeout", "429", "bot")
+
+ def _rank(text: str) -> int:
+ lower = text.lower()
+ for index, marker in enumerate(priority):
+ if marker in lower:
+ return index
+ return len(priority)
+
+ return new if _rank(new) < _rank(current) else current
+
+
def search_and_transcribe(
topic: str,
from_date: str,
@@ -1011,8 +1172,12 @@ def search_and_transcribe(
queries = expand_youtube_queries(topic, depth)
seen_ids: Set[str] = set()
items: List[Dict[str, Any]] = []
+ search_error: Optional[str] = None
for q in queries:
search_result = search_youtube(q, from_date, to_date, depth)
+ err = search_result.get("error")
+ if err:
+ search_error = _prefer_search_error(search_error, str(err))
for item in search_result.get("items", []):
vid = item.get("video_id", "")
if vid and vid not in seen_ids:
@@ -1023,7 +1188,7 @@ def search_and_transcribe(
items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
if not items:
- return search_result
+ return {"items": [], **({"error": search_error} if search_error else {})}
# Step 2: Fetch transcripts for top videos.
# Sort candidates by a combination of views and recency so that recent
@@ -1070,7 +1235,12 @@ def search_and_transcribe(
)
item["captions_disabled"] = vid in captions_disabled_ids
- return {"items": items}
+ result: Dict[str, Any] = {"items": items}
+ if search_error:
+ # Partial coverage: some queries succeeded; keep the failure visible so
+ # source_status becomes partial/timeout rather than a quiet OK.
+ result["error"] = search_error
+ return result
def parse_youtube_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
@@ -1185,7 +1355,7 @@ def _ytdlp_comments_result(
])
try:
- result = subproc.run_with_timeout(cmd, timeout=_COMMENT_TIMEOUT)
+ result = _run_ytdlp(cmd, timeout=_COMMENT_TIMEOUT)
except Exception as exc:
_log(f"yt-dlp comment fetch failed for {video_id}: {exc}")
return [], False
diff --git a/tests/test_competitor_fanout.py b/tests/test_competitor_fanout.py
index a04a44b3..67b74a1f 100644
--- a/tests/test_competitor_fanout.py
+++ b/tests/test_competitor_fanout.py
@@ -101,6 +101,29 @@ class FanoutOrchestratorTests(unittest.TestCase):
)
self.assertEqual([label for label, _ in results], ["OpenAI"])
+ def test_fanout_clears_youtube_search_cache_before_parallel_work(self):
+ """Comparison mode must not inherit a prior run's ytsearch cache."""
+ from lib import youtube_yt
+
+ youtube_yt._search_cache[("prior", 8, "2026-01-01")] = {"items": []}
+ cleared = []
+
+ def main_runner():
+ cleared.append("main" in youtube_yt._search_cache or len(youtube_yt._search_cache) == 0)
+ return _fake_report("OpenAI")
+
+ with mock.patch.object(
+ youtube_yt, "reset_search_cache", wraps=youtube_yt.reset_search_cache
+ ) as reset_mock, redirect_stderr(io.StringIO()):
+ fanout.run_competitor_fanout(
+ main_topic="OpenAI",
+ main_runner=main_runner,
+ competitors=["Anthropic"],
+ competitor_runner=lambda e: _fake_report(e),
+ )
+ reset_mock.assert_called()
+ self.assertNotIn(("prior", 8, "2026-01-01"), youtube_yt._search_cache)
+
def test_sub_runs_execute_in_parallel(self):
"""Wall clock should be closer to max(latency) than sum(latency)."""
delay = 0.2
diff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.py
index 129c503a..573f42b3 100644
--- a/tests/test_source_outcomes.py
+++ b/tests/test_source_outcomes.py
@@ -74,6 +74,7 @@ def test_source_specific_text_failures_are_mapped():
assert bird_x.classify_run_failure("likely Twitter anti-bot interstitial") == schema.SCHEMA_DRIFT
assert reddit.classify_run_failure("blocked by Reddit interstitial") == schema.RATE_LIMITED
assert youtube_yt.classify_run_failure("Sign in to confirm you're not a bot") == schema.RATE_LIMITED
+ assert youtube_yt.classify_run_failure("Search timed out after 1s") == health.TIMEOUT
def test_bundle_distinguishes_clean_no_results_from_failure():
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index cc963e84..39352c6b 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -62,6 +62,9 @@ class TestYouTubeEngagementZero(unittest.TestCase):
class TestYtDlpFlags(unittest.TestCase):
+ def setUp(self):
+ youtube_yt.reset_search_cache()
+
def _fake_result(self, stdout: str = "", returncode: int = 0):
from lib.subproc import SubprocResult
return SubprocResult(returncode=returncode, stdout=stdout, stderr="")
@@ -683,6 +686,7 @@ class TestYtdlpSSHRouting(unittest.TestCase):
def setUp(self):
# Ensure clean env for each test
self._saved_env = os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None)
+ youtube_yt.reset_search_cache()
def tearDown(self):
os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None)
@@ -1134,5 +1138,196 @@ class TestYoutubeCommentsGating(unittest.TestCase):
))
+class TestYouTubeSearchTimeoutAndCache(unittest.TestCase):
+ """Comparison-mode load: timeouts, status honesty, and in-run dedup."""
+
+ def setUp(self):
+ youtube_yt.reset_search_cache()
+
+ def _fake_result(self, stdout: str = "", returncode: int = 0):
+ from lib.subproc import SubprocResult
+ return SubprocResult(returncode=returncode, stdout=stdout, stderr="")
+
+ def test_search_timeout_reports_timeout_error_not_empty(self):
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.dict(os.environ, {"LAST30DAYS_YT_SEARCH_TIMEOUT": "1"}), \
+ mock.patch.object(
+ youtube_yt.subproc, "run_with_timeout",
+ side_effect=youtube_yt.subproc.SubprocTimeout("boom"),
+ ):
+ out = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")
+ self.assertEqual(out.get("items"), [])
+ self.assertIn("timed out", (out.get("error") or "").lower())
+ self.assertEqual(
+ youtube_yt.classify_run_failure(out["error"]),
+ youtube_yt.health.TIMEOUT,
+ )
+
+ def test_search_timeout_env_is_passed_to_subprocess(self):
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.dict(os.environ, {"LAST30DAYS_YT_SEARCH_TIMEOUT": "7"}), \
+ mock.patch.object(
+ youtube_yt.subproc, "run_with_timeout",
+ return_value=self._fake_result(),
+ ) as run_mock:
+ youtube_yt.search_youtube("Alo Yoga", "2026-06-01", "2026-07-01")
+ self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 7.0)
+
+ def test_identical_searches_are_cached_within_run(self):
+ video = {
+ "id": "abc123",
+ "title": "Vuori review",
+ "view_count": 100,
+ "like_count": 1,
+ "comment_count": 0,
+ "upload_date": "20260615",
+ "description": "desc",
+ "channel": "Tester",
+ }
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(
+ youtube_yt.subproc, "run_with_timeout",
+ return_value=self._fake_result(stdout=json.dumps(video) + "\n"),
+ ) as run_mock:
+ first = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")
+ second = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")
+ self.assertEqual(run_mock.call_count, 1)
+ self.assertEqual(len(first["items"]), 1)
+ self.assertEqual(len(second["items"]), 1)
+ self.assertEqual(first["items"][0]["video_id"], second["items"][0]["video_id"])
+ # Callers get independent copies so mutations cannot poison the cache.
+ second["items"][0]["title"] = "mutated"
+ self.assertNotEqual(first["items"][0]["title"], "mutated")
+
+ def test_timeout_errors_are_not_cached(self):
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(
+ youtube_yt.subproc, "run_with_timeout",
+ side_effect=youtube_yt.subproc.SubprocTimeout("boom"),
+ ) as run_mock:
+ youtube_yt.search_youtube("lululemon", "2026-06-01", "2026-07-01")
+ youtube_yt.search_youtube("lululemon", "2026-06-01", "2026-07-01")
+ self.assertEqual(run_mock.call_count, 2)
+
+ def test_waiter_receives_leader_result_without_synthetic_timeout(self):
+ """A coalesced waiter must not invent a timeout while the leader runs."""
+ import threading
+ from lib.subproc import SubprocResult
+
+ video = {
+ "id": "waiter1",
+ "title": "Vuori review",
+ "view_count": 10,
+ "like_count": 1,
+ "comment_count": 0,
+ "upload_date": "20260615",
+ "description": "desc",
+ "channel": "Tester",
+ }
+ started = threading.Event()
+ release = threading.Event()
+
+ def slow_run(cmd, timeout=None):
+ started.set()
+ release.wait(timeout=5)
+ return SubprocResult(
+ returncode=0, stdout=json.dumps(video) + "\n", stderr="",
+ )
+
+ results = []
+
+ def leader():
+ results.append(
+ youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")
+ )
+
+ def waiter():
+ started.wait(timeout=5)
+ results.append(
+ youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01")
+ )
+
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_run):
+ t_leader = threading.Thread(target=leader)
+ t_waiter = threading.Thread(target=waiter)
+ t_leader.start()
+ self.assertTrue(started.wait(timeout=5))
+ t_waiter.start()
+ release.set()
+ t_leader.join(timeout=5)
+ t_waiter.join(timeout=5)
+
+ self.assertEqual(len(results), 2)
+ self.assertTrue(all(r.get("items") for r in results))
+ self.assertTrue(all(not r.get("error") for r in results))
+
+ def test_stale_leader_after_reset_does_not_pop_newer_inflight(self):
+ """A leader that outlives reset_search_cache must not drop the new slot."""
+ import threading
+
+ key = ("ownership", 8, "2026-06-01")
+ old_event = threading.Event()
+ old_slot: list = [None]
+ new_event = threading.Event()
+ new_slot: list = [None]
+
+ with youtube_yt._search_cache_lock:
+ youtube_yt._search_inflight[key] = (old_event, old_slot)
+
+ youtube_yt.reset_search_cache()
+ with youtube_yt._search_cache_lock:
+ youtube_yt._search_inflight[key] = (new_event, new_slot)
+
+ youtube_yt._finish_search_slot(
+ key,
+ {"items": [{"video_id": "old"}]},
+ event=old_event,
+ slot=old_slot,
+ )
+
+ with youtube_yt._search_cache_lock:
+ current = youtube_yt._search_inflight.get(key)
+ cached = youtube_yt._search_cache.get(key)
+
+ self.assertIsNotNone(current)
+ self.assertIs(current[1], new_slot)
+ self.assertIsNone(cached)
+ self.assertTrue(old_event.is_set())
+ self.assertEqual(old_slot[0]["items"][0]["video_id"], "old")
+
+ def test_multi_query_preserves_timeout_over_later_empty(self):
+ responses = [
+ {"items": [], "error": "Search timed out after 1s"},
+ {"items": []},
+ ]
+
+ def fake_search(*_args, **_kwargs):
+ return responses.pop(0)
+
+ with mock.patch.object(youtube_yt, "expand_youtube_queries", return_value=["a", "b"]), \
+ mock.patch.object(youtube_yt, "search_youtube", side_effect=fake_search):
+ out = youtube_yt.search_and_transcribe(
+ "topic", "2026-06-01", "2026-07-01", depth="default",
+ )
+ self.assertEqual(out.get("items"), [])
+ self.assertIn("timed out", (out.get("error") or "").lower())
+ self.assertEqual(
+ youtube_yt.classify_run_failure(out["error"]),
+ youtube_yt.health.TIMEOUT,
+ )
+
+ def test_bundle_records_timeout_not_no_results(self):
+ from lib import health, schema
+
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("youtube")
+ state = youtube_yt.classify_run_failure("Search timed out after 1s")
+ bundle.record_failure("youtube", state, "Search timed out after 1s")
+ bundle.add_items("main", "youtube", [])
+ self.assertEqual(bundle.source_status["youtube"].state, health.TIMEOUT)
+ self.assertNotEqual(bundle.source_status["youtube"].state, schema.NO_RESULTS)
+
+
if __name__ == "__main__":
unittest.main()