AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix: recover Instagram reels within shared request deadlines (#1253)
Som Samantrayee1ccfe4ee01
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex deb5c069..f00c9896 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -192,6 +192,8 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \| Caption-free transcription | `GROQ_API_KEY` (free tier, preferred) or `OPENAI_API_KEY` (paid backstop); requires `ffmpeg` | Whisper transcription for audio/video without captions (groundwork: module shipped, not yet auto-invoked by the engine) | Groq free tier is generous; needs ffmpeg installed || Jobs / careers pages | none for public ATS pages; web backend improves fallback discovery | `--hiring-signals` and strong Hiring Signals in standard company reports | yes |+**Instagram recovery budget.** When the primary reels search returns no results or HTTP 404, Instagram can recover Google-indexed reels through ScrapeCreators. Each source fetch shares at most 1 Google page and 9 post-detail attempts at quick depth, 2 and 16 at default depth, or 3 and 27 at deep depth across its expanded queries. These calls spend credits; primary searches, transcripts, comments, and later source retries are outside those counts. Successful details are reused by reel shortcode within the fetch. The source's time budget also covers transcripts and comments: if it expires, completed reels remain available as partial coverage and no further requests start. A request already accepted by the provider can still be charged.+**Reddit keyless pacing.** Unauthenticated reddit.com requests (site search, listing partials, shreddit) share one token bucket. The default is `1` request per second with a burst of 2, slow enough that engine fan-out does not trip HTTP 429 on a typical home IP. Set `LAST30DAYS_REDDIT_KEYLESS_RATE` to a float req/sec to trade wall-clock for coverage: higher finishes faster and loses more sub-requests to 429; lower is safer and slower. Invalid or non-positive values fall back to `1`. A 429'd search or listing sub-request is retried once after a short jittered pause, still through the limiter. Identical reddit.com requests within one command (subreddit listings, listing feeds, comment pages, which repeat across subqueries) are fetched once and memoized, so a typical four-subquery run issues roughly a quarter of the requests it used to. Comment enrichment covers 4 / 8 / 12 threads per subquery at quick / default / deep depth. This does not change ScrapeCreators routing (`LAST30DAYS_REDDIT_BACKEND` / `LAST30DAYS_REDDIT_SC_MIN_ITEMS`).**YouTube proxy.** Set `YOUTUBE_PROXY` (or the shorter alias `YT_PROXY`) to route all yt-dlp traffic through a proxy. Useful when YouTube is blocked in your region. Accepts any proxy URL that yt-dlp supports: `socks5://127.0.0.1:1080`, `http://proxy.example.com:3128`, etc. `YOUTUBE_PROXY` takes precedence over `YT_PROXY`. Only yt-dlp calls are routed through this proxy — other HTTP requests the skill makes (ScrapeCreators, OpenAI, etc.) are unaffected. To route all traffic, use the standard `HTTP_PROXY` / `HTTPS_PROXY` environment variables instead.diff --git a/changelog.d/1020.fixed.md b/changelog.d/1020.fixed.mdnew file mode 100644index 00000000..34add3ad--- /dev/null+++ b/changelog.d/1020.fixed.md@@ -0,0 +1 @@+Instagram keyword search falls back to a bounded Google-indexed reel search and fetches post details when the primary reels search returns no results. Recovery and enrichment share the source deadline, preserve completed results as partial coverage, and stop starting requests after timeout or cancellation.diff --git a/skills/last30days/scripts/lib/instagram.py b/skills/last30days/scripts/lib/instagram.pyindex 354ea02a..4e53ff79 100644--- a/skills/last30days/scripts/lib/instagram.py+++ b/skills/last30days/scripts/lib/instagram.py@@ -10,8 +10,12 @@ API docs: https://scrapecreators.com/docsimport osimport reimport sys-from datetime import datetime+import threading+import time+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait+from datetime import datetime, timedeltafrom typing import Any, Dict, List, Optional, Set+from urllib.parse import urlsplitfrom . import dates, http, logfrom .query import infer_query_intent@@ -26,8 +30,18 @@ DEPTH_CONFIG = {"deep": {"results_per_page": 40, "max_captions": 8},}+# Keep the Google discovery fallback bounded because each post detail request+# costs one credit. The page/post totals match the fallback's observed depth+# budgets: 1 + 9, 2 + 16, and 3 + 27 requests.+GOOGLE_FALLBACK_BUDGETS = {+ "quick": (1, 9),+ "default": (2, 16),+ "deep": (3, 27),+}+# Max words to keep from each captionCAPTION_MAX_WORDS = 500+RESEARCH_TIMEOUT = "Instagram research timed out or was cancelled; returning collected reels"# Default transcript fetch timeout (seconds). SC's# /v2/instagram/media/transcript regularly takes >15s on real workloads,@@ -133,6 +147,23 @@ def _log(msg: str):log.source_log("Instagram", msg, tty_only=False)+def _budget_expired(deadline: float | None, cancel: threading.Event | None) -> bool:+ return bool(+ (cancel is not None and cancel.is_set())+ or (deadline is not None and time.monotonic() >= deadline)+ )+++def _request_options(timeout: float, deadline: float | None, cancel: threading.Event | None) -> dict:+ options = {"timeout": timeout}+ if deadline is not None:+ options["timeout"] = min(timeout, max(0.001, deadline - time.monotonic()))+ options["deadline_monotonic"] = deadline+ if cancel is not None:+ options["cancel"] = cancel+ return options++def _parse_date(item: Dict[str, Any]) -> Optional[str]:"""Parse date from ScrapeCreators Instagram item to YYYY-MM-DD.@@ -245,6 +276,9 @@ def _parse_items(raw_items: List[Dict[str, Any]], core_topic: str) -> List[Dict[def _user_reels(handle: str,token: str,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,) -> List[Dict[str, Any]]:"""Fetch an Instagram user's recent reels via ScrapeCreators.@@ -255,6 +289,8 @@ def _user_reels(Returns:List of raw Instagram reel dicts."""+ if _budget_expired(deadline, cancel):+ return []_log(f"User reels: @{handle}")reels_url = f"{SCRAPECREATORS_BASE}/v1/instagram/user/reels"try:@@ -262,8 +298,8 @@ def _user_reels(reels_url,params={"handle": handle},headers=http.scrapecreators_headers(token),- timeout=30,retries=2,+ **_request_options(30, deadline, cancel),)except Exception as e:_log(f"User reels error for @{handle}: {e}")@@ -282,13 +318,201 @@ def _user_reels(]+def _normalize_google_post(+ payload: dict[str, Any], url: str+) -> dict[str, Any] | None:+ """Convert a ScrapeCreators post detail response to the reels/search shape."""+ if not isinstance(payload, dict):+ return None+ data = payload.get("data")+ if not isinstance(data, dict):+ return None+ media = data.get("xdt_shortcode_media")+ if not isinstance(media, dict):+ return None++ caption = media.get("caption")+ if not caption:+ edges = (media.get("edge_media_to_caption") or {}).get("edges") or []+ if edges and isinstance(edges[0], dict):+ caption = (edges[0].get("node") or {}).get("text", "")++ likes = (media.get("edge_media_preview_like") or {}).get("count")+ comments = (media.get("edge_media_to_parent_comment") or {}).get("count")+ if comments is None:+ comments = (media.get("edge_media_to_comment") or {}).get("count")++ return {+ "id": media.get("id", ""),+ "shortcode": media.get("shortcode", ""),+ "url": url,+ "caption": caption or "",+ "taken_at": media.get("taken_at_timestamp") or media.get("created_at"),+ "video_play_count": media.get("video_play_count") or 0,+ "like_count": likes or 0,+ "comment_count": comments or 0,+ "owner": media.get("owner") or media.get("user") or {},+ }+++def _google_reel_fallback(+ topic: str,+ depth: str,+ token: str,+ from_date: str,+ to_date: str,+ budget: dict[str, int] | None = None,+ detail_cache: dict[str, dict[str, Any]] | None = None,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,+) -> list[dict[str, Any]]:+ """Discover Instagram reels through Google and fetch their post details."""+ if budget is None:+ pages, max_posts = GOOGLE_FALLBACK_BUDGETS.get(+ depth, GOOGLE_FALLBACK_BUDGETS["default"]+ )+ budget = {"pages": pages, "posts": max_posts}+ pages = max(0, budget.get("pages", 0))+ max_posts = max(0, budget.get("posts", 0))+ if not pages or not max_posts:+ return []+ headers = http.scrapecreators_headers(token)+ detail_cache = detail_cache if detail_cache is not None else {}+ shortcode_urls: dict[str, str] = {}+ ordered_shortcodes: list[str] = []+ end_exclusive = (+ datetime.strptime(to_date, "%Y-%m-%d") + timedelta(days=1)+ ).strftime("%Y-%m-%d")++ for page in range(1, pages + 1):+ if _budget_expired(deadline, cancel):+ break+ budget["pages"] -= 1+ try:+ data = http.get(+ f"{SCRAPECREATORS_BASE}/v1/google/search",+ params={+ "query": (+ f"site:instagram.com/reel {topic} "+ f"after:{from_date} before:{end_exclusive}"+ ),+ "page": page,+ },+ headers=headers,+ retries=1,+ **_request_options(30, deadline, cancel),+ )+ except Exception as e:+ _log(f"Google Instagram fallback search failed on page {page}: {e}")+ break+ if not isinstance(data, dict):+ _log(f"Google Instagram fallback returned invalid data on page {page}")+ break++ results = data.get("results") or data.get("items") or []+ if not isinstance(results, list):+ _log(f"Google Instagram fallback returned invalid results on page {page}")+ continue+ for result in results:+ if not isinstance(result, dict):+ continue+ url = result.get("url", "")+ try:+ parsed_url = urlsplit(url) if isinstance(url, str) else None+ except ValueError:+ continue+ hostname = parsed_url.hostname.lower() if parsed_url and parsed_url.hostname else ""+ is_instagram = hostname == "instagram.com" or hostname.endswith(".instagram.com")+ is_reel_path = bool(+ parsed_url+ and re.fullmatch(r"/reel/[A-Za-z0-9_-]+/?", parsed_url.path)+ )+ shortcode_match = (+ re.fullmatch(r"/reel/([A-Za-z0-9_-]+)/?", parsed_url.path)+ if parsed_url+ else None+ )+ if (+ parsed_url+ and parsed_url.scheme == "https"+ and is_instagram+ and is_reel_path+ ):+ shortcode = shortcode_match.group(1)+ if shortcode not in shortcode_urls and shortcode not in detail_cache:+ if len(shortcode_urls) >= max_posts:+ continue+ shortcode_urls[shortcode] = url+ if shortcode not in ordered_shortcodes:+ ordered_shortcodes.append(shortcode)+ if len(shortcode_urls) >= max_posts:+ break+ if len(shortcode_urls) >= max_posts:+ break++ budget["posts"] -= len(shortcode_urls)++ def fetch_post(url: str) -> dict[str, Any] | None:+ if _budget_expired(deadline, cancel):+ return None+ try:+ payload = http.get(+ f"{SCRAPECREATORS_BASE}/v1/instagram/post",+ params={"url": url},+ headers=headers,+ retries=1,+ **_request_options(30, deadline, cancel),+ )+ except Exception as e:+ _log(f"Instagram post detail failed for {url}: {e}")+ return None+ try:+ return _normalize_google_post(payload, url)+ except (AttributeError, TypeError, ValueError) as e:+ _log(f"Instagram post detail had an invalid response for {url}: {e}")+ return None++ if shortcode_urls:+ executor = ThreadPoolExecutor(max_workers=min(4, len(shortcode_urls)))+ try:+ futures = {+ http.submit_with_context(executor, fetch_post, url): shortcode+ for shortcode, url in shortcode_urls.items()+ }+ pending = set(futures)+ while pending:+ remaining = 0.05 if deadline is None else max(0, min(0.05, deadline - time.monotonic()))+ done, pending = wait(pending, timeout=remaining, return_when=FIRST_COMPLETED)+ for future in done:+ reel = future.result()+ if reel:+ detail_cache[futures[future]] = reel+ if _budget_expired(deadline, cancel):+ break+ finally:+ executor.shutdown(wait=False, cancel_futures=True)++ reels = []+ for shortcode in ordered_shortcodes:+ reel = detail_cache.get(shortcode)+ if reel:+ reels.append(reel)+ return reels++def search_instagram(topic: str,from_date: str,to_date: str,depth: str = "default",token: str = None,-) -> Dict[str, Any]:+ _fallback_budget: dict[str, int] | None = None,+ _fallback_cache: dict[str, dict[str, Any]] | None = None,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,+) -> dict[str, Any]:"""Search Instagram Reels via ScrapeCreators API.Args:@@ -303,37 +527,54 @@ def search_instagram("""if not token:return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"}+ if _budget_expired(deadline, cancel):+ return {"items": [], "error": RESEARCH_TIMEOUT}config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])core_topic = _extract_core_subject(topic)_log(f"Searching Instagram for '{core_topic}' (depth={depth}, count={config['results_per_page']})")+ primary_error = Nonetry:data = http.get(f"{SCRAPECREATORS_BASE}/v2/instagram/reels/search",params={"query": core_topic},headers=http.scrapecreators_headers(token),- timeout=30,retries=2,+ **_request_options(30, deadline, cancel),)except http.HTTPError as e:# SC's v2 reels search wraps Google Search and 500s frequently on# multi-token queries. Single tokens hit the stable hashtag-page# path. Retry once with hashtag form before bubbling up.- if getattr(e, "status_code", None) == 500 and ' ' in core_topic:+ if (getattr(e, "status_code", None) == 500 and ' ' in core_topic+ and not _budget_expired(deadline, cancel)):_log(f"IG search 500 on '{core_topic}', retrying with hashtag form")try:data = http.get(f"{SCRAPECREATORS_BASE}/v2/instagram/reels/search",params={"query": _to_hashtag_form(core_topic)},headers=http.scrapecreators_headers(token),- timeout=30,retries=2,+ **_request_options(30, deadline, cancel),)except Exception as retry_e:- _log(f"IG search retry failed: {retry_e}")- return {"items": [], "error": f"{type(retry_e).__name__}: {retry_e}"}+ if (+ isinstance(retry_e, http.HTTPError)+ and getattr(retry_e, "status_code", None) == 404+ ):+ primary_error = retry_e+ data = {"reels": []}+ else:+ _log(f"IG search retry failed: {retry_e}")+ return {"items": [], "error": f"{type(retry_e).__name__}: {retry_e}"}+ elif getattr(e, "status_code", None) == 404:+ # A 404 is ScrapeCreators' current response for both empty searches+ # and the reported reels-search outage. Try the independent Google+ # discovery + post-detail lane before treating Instagram as failed.+ primary_error = e+ data = {"reels": []}else:_log(f"ScrapeCreators error: {e}")return {"items": [], "error": f"{type(e).__name__}: {e}"}@@ -344,6 +585,22 @@ def search_instagram(# Items are in the 'reels' array (ScrapeCreators v2 response)raw_items = data.get("reels") or data.get("items") or data.get("data") or []+ used_google_fallback = not raw_items+ if used_google_fallback:+ if primary_error:+ _log("IG reels search returned 404; trying Google Search fallback")+ else:+ _log("IG reels search returned no results; trying Google Search fallback")+ raw_items = _google_reel_fallback(+ core_topic, depth, token, from_date, to_date,+ _fallback_budget, _fallback_cache,+ deadline=deadline, cancel=cancel,+ )++ if not raw_items and primary_error and not _budget_expired(deadline, cancel):+ _log(f"Google Instagram fallback returned no reels: {primary_error}")+ return {"items": [], "error": f"{type(primary_error).__name__}: {primary_error}"}+# Limit to configured countraw_items = raw_items[:config["results_per_page"]]@@ -353,7 +610,11 @@ def search_instagram(# Hard date filterin_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date]out_of_range = len(items) - len(in_range)- if in_range:+ if used_google_fallback:+ items = in_range+ if out_of_range:+ _log(f"Filtered {out_of_range} Google reels outside date range")+ elif in_range:items = in_rangeif out_of_range:_log(f"Filtered {out_of_range} reels outside date range")@@ -364,6 +625,8 @@ def search_instagram(items.sort(key=lambda x: x["engagement"]["views"], reverse=True)_log(f"Found {len(items)} Instagram reels")+ if _budget_expired(deadline, cancel):+ return {"items": items, "error": RESEARCH_TIMEOUT}return {"items": items}@@ -373,6 +636,9 @@ def fetch_captions(depth: str = "default",timeout: Optional[float] = None,config: Optional[Dict[str, Any]] = None,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,) -> Dict[str, str]:"""Fetch transcripts for top N Instagram reels via ScrapeCreators.@@ -418,6 +684,8 @@ def fetch_captions(# Second pass: try to get spoken-word transcripts (1 credit each)for item in top_items:+ if _budget_expired(deadline, cancel):+ breakvid = item["video_id"]url = item.get("url", "")if not url:@@ -431,8 +699,8 @@ def fetch_captions(f"{SCRAPECREATORS_BASE}/v2/instagram/media/transcript",params={"url": url},headers=http.scrapecreators_headers(token),- timeout=transcript_timeout,retries=1,+ **_request_options(transcript_timeout, deadline, cancel),)transcripts = data.get("transcripts") or []if transcripts and isinstance(transcripts, list):@@ -460,6 +728,9 @@ def search_and_enrich(depth: str = "default",token: str = None,ig_creators: List[str] | None = None,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,) -> Dict[str, Any]:"""Full Instagram search: find reels, then fetch captions for top results.@@ -485,7 +756,9 @@ def search_and_enrich(# Step 0: Creator reels (high-signal, runs first)if ig_creators and token:for creator in ig_creators:- raw_items = _user_reels(creator, token)+ if _budget_expired(deadline, cancel):+ break+ raw_items = _user_reels(creator, token, deadline=deadline, cancel=cancel)parsed = _parse_items(raw_items, core_topic)for item in parsed:vid = item.get("video_id", "")@@ -495,8 +768,25 @@ def search_and_enrich(# Step 1: Multi-query keyword search — run ScrapeCreators for each expanded queryqueries = expand_instagram_queries(topic, depth)- for q in queries:- search_result = search_instagram(q, from_date, to_date, depth, token)+ fallback_pages, fallback_posts = GOOGLE_FALLBACK_BUDGETS.get(+ depth, GOOGLE_FALLBACK_BUDGETS["default"]+ )+ fallback_cache: dict[str, dict[str, Any]] = {}+ for index, q in enumerate(queries):+ if _budget_expired(deadline, cancel):+ break+ query_count = len(queries)+ query_budget = {+ "pages": fallback_pages // query_count+ + (1 if index < fallback_pages % query_count else 0),+ "posts": fallback_posts // query_count+ + (1 if index < fallback_posts % query_count else 0),+ }+ search_result = search_instagram(+ q, from_date, to_date, depth, token,+ _fallback_budget=query_budget, _fallback_cache=fallback_cache,+ deadline=deadline, cancel=cancel,+ )if search_result.get("error"):last_error = search_result["error"]for item in search_result.get("items", []):@@ -508,11 +798,13 @@ def search_and_enrich(# Sort merged results by views descendingitems.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)+ if _budget_expired(deadline, cancel):+ last_error = RESEARCH_TIMEOUTif not items:return {"items": [], "error": last_error}# Step 2: Fetch captions for top N- captions = fetch_captions(items, token, depth)+ captions = fetch_captions(items, token, depth, deadline=deadline, cancel=cancel)# Step 3: Attach captions to itemsfor item in items:@@ -521,6 +813,8 @@ def search_and_enrich(if caption:item["caption_snippet"] = caption+ if _budget_expired(deadline, cancel):+ last_error = RESEARCH_TIMEOUTreturn {"items": items, "error": last_error}@@ -549,6 +843,9 @@ def enrich_with_comments(token: str,max_posts: int = 3,max_comments: int = 5,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,) -> List[Dict[str, Any]]:"""Enrich top Instagram posts with comment data from ScrapeCreators.@@ -556,34 +853,42 @@ def enrich_with_comments(for the top N posts by engagement, fetch comments and attach them as a``top_comments`` field (highest-liked first). Failures never crash the run."""- if not items or not token or max_posts <= 0:+ if not items or not token or max_posts <= 0 or _budget_expired(deadline, cancel):return itemsranked = sorted(items, key=_ig_total_engagement, reverse=True)top_items = ranked[:max_posts]_log(f"Enriching comments for {len(top_items)} Instagram posts")- from concurrent.futures import ThreadPoolExecutor, as_completed-- def _enrich_one(item: dict) -> bool:+ def _enrich_one(item: dict) -> list[dict]:post_url = item.get("url", "")if not post_url:- return False+ return []try:- comments = _fetch_post_comments(post_url, token, max_comments)- if comments:- item["top_comments"] = comments- return True+ return _fetch_post_comments(+ post_url, token, max_comments, deadline=deadline, cancel=cancel,+ )except Exception as exc:_log(f"Comment enrichment failed for {post_url}: {exc}")- return False+ return []enriched_count = 0- with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:+ executor = ThreadPoolExecutor(max_workers=min(4, len(top_items)))+ try:futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}- for future in as_completed(futures):- if future.result():- enriched_count += 1+ pending = set(futures)+ while pending:+ remaining = 0.05 if deadline is None else max(0, min(0.05, deadline - time.monotonic()))+ done, pending = wait(pending, timeout=remaining, return_when=FIRST_COMPLETED)+ for future in done:+ comments = future.result()+ if comments:+ futures[future]["top_comments"] = comments+ enriched_count += 1+ if _budget_expired(deadline, cancel):+ break+ finally:+ executor.shutdown(wait=False, cancel_futures=True)_log(f"Enriched {enriched_count}/{len(top_items)} posts with comments")return items@@ -593,6 +898,9 @@ def _fetch_post_comments(post_url: str,token: str,max_comments: int = 5,+ *,+ deadline: float | None = None,+ cancel: threading.Event | None = None,) -> List[Dict[str, Any]]:"""Fetch comments for a single Instagram post/reel via ScrapeCreators.@@ -604,13 +912,15 @@ def _fetch_post_comments(List of comment dicts with author, text, comment_like_count (likes), date,highest-liked first. Empty list on any error — never crashes the pipeline."""+ if _budget_expired(deadline, cancel):+ return []try:data = http.get(f"{SCRAPECREATORS_BASE}/v2/instagram/post/comments",params={"url": post_url},headers=http.scrapecreators_headers(token),- timeout=30,retries=2,+ **_request_options(30, deadline, cancel),)except Exception as exc:_log(f"Comment fetch error for {post_url}: {exc}")diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 04af639a..fff8bfd0 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -6046,6 +6046,11 @@ def _retrieve_stream_impl(# Use raw_topic so expand_instagram_queries() generates diverse variants# from the original user topic, not the planner's narrowed search_query.ig_query = raw_topic or subquery.search_query+ ig_deadline = _research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS)+ # Leave time to publish collected reels before the outer stream wait expires.+ remaining = max(0, ig_deadline - time.monotonic())+ ig_deadline -= min(1.0, remaining / 10)+ ig_cancel = config.get("_enrich_cancel")def _fetch_instagram() -> tuple[list[dict], dict]:result = instagram.search_and_enrich(@@ -6055,11 +6060,18 @@ def _retrieve_stream_impl(depth=depth,token=env.get_instagram_token(config),ig_creators=ig_creators,+ deadline=ig_deadline,+ cancel=ig_cancel,)items = instagram.parse_instagram_response(result)if items and env.is_instagram_comments_available(config):instagram.enrich_with_comments(items, token=config.get("SCRAPECREATORS_API_KEY", ""),+ deadline=ig_deadline, cancel=ig_cancel,+ )+ if (ig_cancel is not None and ig_cancel.is_set()) or time.monotonic() >= ig_deadline:+ return items, _outcome_artifact(+ health.PARTIAL if items else health.TIMEOUT, instagram.RESEARCH_TIMEOUT,)return items, _result_outcome_artifact(source, result)diff --git a/tests/test_instagram_deadlines.py b/tests/test_instagram_deadlines.pynew file mode 100644index 00000000..79ec9d1e--- /dev/null+++ b/tests/test_instagram_deadlines.py@@ -0,0 +1,245 @@+import io+import json+import threading+import time+import urllib.error+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import Mock+from urllib.parse import parse_qs, urlsplit++import pytest++from lib import health, http, instagram, pipeline, schema+++def response(payload):+ result = io.BytesIO(json.dumps(payload).encode())+ result.status = 200+ return result+++def post(shortcode):+ return {"data": {"xdt_shortcode_media": {+ "id": shortcode,+ "shortcode": shortcode,+ "taken_at_timestamp": 1786900800,+ "caption": "Coffee roasting guide",+ "owner": {"username": "test_creator"},+ }}}+++def test_stream_retains_completed_detail_before_its_deadline(monkeypatch):+ release = threading.Event()+ finished = threading.Event()+ requests = []++ def transport(request, timeout):+ url = urlsplit(request.full_url)+ query = parse_qs(url.query)+ requests.append((url.path, timeout))+ if url.path == "/v2/instagram/reels/search":+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))+ if url.path == "/v1/google/search":+ return response({"results": [+ {"url": "https://www.instagram.com/reel/SLOW/"},+ {"url": "https://www.instagram.com/reel/FAST/"},+ ]})+ if url.path == "/v1/instagram/post":+ if "/SLOW/" in query["url"][0]:+ try:+ release.wait(3)+ return response(post("SLOW"))+ finally:+ finished.set()+ return response(post("FAST"))+ raise AssertionError(f"Unexpected paid request: {url.path}")++ monkeypatch.setattr(http, "_open_request", transport)+ config = {+ "SCRAPECREATORS_API_KEY": "dummy-key",+ "INCLUDE_SOURCES": "instagram,instagram_comments",+ "_research_deadline": time.monotonic() + 1,+ }+ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(+ pipeline._retrieve_stream,+ topic="coffee",+ subquery=schema.SubQuery(+ label="primary", search_query="coffee", ranking_query="coffee",+ sources=["instagram"], weight=1.0,+ ),+ source="instagram", config=config, depth="default",+ date_range=("2026-08-01", "2026-08-31"), runtime=Mock(), mock=False,+ )+ try:+ done, pending = pipeline._wait_for_research([future], config)+ assert not pending, "Instagram must return its recovered reels before the stream expires"+ items, artifact = future.result()+ assert [item["video_id"] for item in items] == ["FAST"]+ assert artifact["_source_outcome"]["state"] == health.PARTIAL+ assert "timed out" in artifact["_source_outcome"]["detail"]+ assert len(requests) == 4+ assert all(0 < timeout < 1 for _, timeout in requests)+ finally:+ release.set()+ assert finished.wait(2)++[email protected]("stage", ["creator", "query", "transcript"])+def test_cancellation_retains_items_and_stops_later_requests(monkeypatch, stage):+ cancel = threading.Event()+ requests = []+ reel = {+ "id": "EARLY", "shortcode": "EARLY", "caption": "Coffee roasting guide",+ "taken_at": "2026-08-16T12:00:00Z", "owner": {"username": "test_creator"},+ }++ def transport(request, timeout):+ path = urlsplit(request.full_url).path+ requests.append(path)+ if path == "/v1/instagram/user/reels":+ if requests.count(path) == 2:+ cancel.set()+ return response({"items": [{"media": reel}]})+ if path == "/v2/instagram/reels/search":+ if stage == "query" and requests.count(path) == 2:+ cancel.set()+ return response({"reels": [reel]})+ if path == "/v2/instagram/media/transcript":+ cancel.set()+ return response({"transcripts": [{"text": "Fresh transcript"}]})+ raise AssertionError(f"Unexpected paid request: {path}")++ monkeypatch.setattr(http, "_open_request", transport)+ result = instagram.search_and_enrich(+ "coffee", "2026-08-01", "2026-08-31", token="dummy-key",+ depth="quick" if stage == "transcript" else "deep",+ ig_creators=["first", "second", "third"] if stage == "creator" else None,+ deadline=time.monotonic() + 2, cancel=cancel,+ )+ assert [item["video_id"] for item in result["items"]] == ["EARLY"]+ expected = {+ "creator": ["/v1/instagram/user/reels"] * 2,+ "query": ["/v2/instagram/reels/search"] * 2,+ "transcript": ["/v2/instagram/reels/search", "/v2/instagram/media/transcript"],+ }+ assert requests == expected[stage]+ assert "cancelled" in result["error"]+++def test_transcript_timeout_preserves_free_captions_and_skips_next_transcript(monkeypatch):+ release = threading.Event()+ finished = threading.Event()+ requests = []+ items = [+ {"video_id": name, "url": f"https://www.instagram.com/reel/{name}/", "text": f"Caption {name}"}+ for name in ("FIRST", "SECOND")+ ]++ def transport(request, timeout):+ requests.append(request.full_url)+ try:+ release.wait(2)+ return response({"transcripts": [{"text": "Too late"}]})+ finally:+ finished.set()++ monkeypatch.setattr(http, "_open_request", transport)+ try:+ captions = instagram.fetch_captions(items, "dummy-key", deadline=time.monotonic() + 0.15)+ assert captions == {"FIRST": "Caption FIRST", "SECOND": "Caption SECOND"}+ assert len(requests) == 1+ finally:+ release.set()+ assert finished.wait(2)+++def test_comment_timeout_keeps_completed_comments_without_late_mutation(monkeypatch):+ release = threading.Event()+ finished = threading.Event()+ items = [+ {"video_id": name, "url": f"https://www.instagram.com/reel/{name}/", "engagement": {"likes": 10}}+ for name in ("SLOW", "FAST")+ ]++ def transport(request, timeout):+ query = parse_qs(urlsplit(request.full_url).query)+ if "/SLOW/" in query["url"][0]:+ try:+ release.wait(2)+ return response({"comments": [{"text": "Too late", "comment_like_count": 100}]})+ finally:+ finished.set()+ return response({"comments": [{"text": "Helpful early comment", "comment_like_count": 50}]})++ monkeypatch.setattr(http, "_open_request", transport)+ try:+ result = instagram.enrich_with_comments(items, "dummy-key", deadline=time.monotonic() + 0.15)+ assert result is items+ assert "top_comments" not in items[0]+ assert items[1]["top_comments"][0]["text"] == "Helpful early comment"+ snapshot = json.dumps(items)+ finally:+ release.set()+ assert finished.wait(2)+ assert json.dumps(items) == snapshot+++def test_cancellation_stops_queued_detail_requests(monkeypatch):+ cancel = threading.Event()+ in_flight = threading.Barrier(4)+ requests = []++ def transport(request, timeout):+ path = urlsplit(request.full_url).path+ requests.append(path)+ if path == "/v1/google/search":+ return response({"results": [+ {"url": f"https://www.instagram.com/reel/POST{index}/"}+ for index in range(9)+ ]})+ in_flight.wait(timeout=2)+ cancel.set()+ return response(post("POST0"))++ monkeypatch.setattr(http, "_open_request", transport)+ instagram._google_reel_fallback(+ "coffee", "quick", "dummy-key", "2026-08-01", "2026-08-31",+ deadline=time.monotonic() + 2, cancel=cancel,+ )+ assert requests == ["/v1/google/search"] + ["/v1/instagram/post"] * 4++[email protected]("depth,pages,posts", [("quick", 1, 9), ("default", 2, 16), ("deep", 3, 27)])+def test_deadline_enabled_recovery_preserves_paid_request_caps(monkeypatch, depth, pages, posts):+ requests = []+ page_count = 0++ def transport(request, timeout):+ nonlocal page_count+ url = urlsplit(request.full_url)+ query = parse_qs(url.query)+ requests.append(url.path)+ if url.path == "/v2/instagram/reels/search":+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))+ if url.path == "/v1/google/search":+ page_count += 1+ return response({"results": [+ {"url": f"https://www.instagram.com/reel/P{page_count}_{index}/"}+ for index in range(40)+ ]})+ if url.path == "/v1/instagram/post":+ return response(post(urlsplit(query["url"][0]).path.split("/")[2]))+ if url.path == "/v2/instagram/media/transcript":+ return response({"transcripts": []})+ raise AssertionError(f"Unexpected paid request: {url.path}")++ monkeypatch.setattr(http, "_open_request", transport)+ result = instagram.search_and_enrich(+ "coffee", "2026-08-01", "2026-08-31", token="dummy-key", depth=depth,+ deadline=time.monotonic() + 5,+ )+ assert len(result["items"]) == posts+ assert not result["error"]+ assert requests.count("/v1/google/search") == pages+ assert requests.count("/v1/instagram/post") == postsdiff --git a/tests/test_instagram_sc.py b/tests/test_instagram_sc.pyindex 6751c127..73f721fd 100644--- a/tests/test_instagram_sc.py+++ b/tests/test_instagram_sc.py@@ -113,7 +113,9 @@ class TestSearchRetryOn500(unittest.TestCase):"""Multi-word query 500 -> retry with collapsed hashtag form."""from lib import http as http_modulefirst_error = http_module.HTTPError("HTTP 500: Server Error", 500, "")- second_payload = {"reels": []}+ second_payload = {+ "reels": [{"id": "retry-result", "taken_at": "2026-04-15T12:00:00Z"}]+ }with patch.object(http_module, "get") as mock_http_get:mock_http_get.side_effect = [first_error, second_payload]instagram.search_instagram(@@ -145,7 +147,9 @@ class TestSearchRetryOn500(unittest.TestCase):def test_first_call_succeeds_no_retry(self):"""200 on first call -> retry path is never entered."""from lib import http as http_module- ok_payload = {"reels": []}+ ok_payload = {+ "reels": [{"id": "search-result", "taken_at": "2026-04-15T12:00:00Z"}]+ }with patch.object(http_module, "get") as mock_http_get:mock_http_get.return_value = ok_payloadinstagram.search_instagram(@@ -167,6 +171,318 @@ class TestSearchRetryOn500(unittest.TestCase):self.assertIn("SCRAPECREATORS_API_KEY", result["error"])+class TestGoogleSearchFallback(unittest.TestCase):+ """The Google-indexed post lane recovers when reels search is empty."""++ def _post_payload(self):+ return {+ "data": {+ "xdt_shortcode_media": {+ "id": "post-1020",+ "shortcode": "ABC1020",+ "taken_at_timestamp": 1786900800,+ "edge_media_to_caption": {+ "edges": [{"node": {"text": "AI automation for small business"}}]+ },+ "video_play_count": 900,+ "edge_media_preview_like": {"count": 80},+ "edge_media_to_parent_comment": {"count": 12},+ "owner": {"username": "creator1020"},+ }+ }+ }++ def test_404_search_falls_back_to_google_reel_urls_and_post_details(self):+ from lib import http as http_module++ not_found = http_module.HTTPError(+ 'HTTP 404: No scrapeable reels found for that query', 404, ""+ )+ with patch.object(+ http_module,+ "get",+ side_effect=[+ not_found,+ {+ "results": [+ {"url": "https://www.instagram.com/reel/ABC1020/"},+ {"url": "https://www.instagram.com/reel/ABC1020/"},+ ]+ },+ self._post_payload(),+ ],+ ) as mock_http_get:+ result = instagram.search_instagram(+ "AI automation for small business",+ "2026-08-01",+ "2026-08-31",+ depth="quick",+ token="fake-token",+ )++ self.assertNotIn("error", result)+ self.assertEqual(1, len(result["items"]))+ item = result["items"][0]+ self.assertEqual("post-1020", item["video_id"])+ self.assertEqual("creator1020", item["author_name"])+ self.assertEqual("AI automation for small business", item["text"])+ self.assertEqual("2026-08-16", item["date"])+ self.assertEqual(+ {"views": 900, "likes": 80, "comments": 12}, item["engagement"]+ )+ self.assertEqual(3, mock_http_get.call_count)+ google_call = mock_http_get.call_args_list[1]+ self.assertEqual(+ "site:instagram.com/reel ai automation for small business "+ "after:2026-08-01 before:2026-09-01",+ google_call.kwargs["params"]["query"],+ )+ self.assertNotIn("date_posted", google_call.kwargs["params"])+ self.assertEqual(1, google_call.kwargs["params"]["page"])+ post_call = mock_http_get.call_args_list[2]+ self.assertEqual(+ "https://www.instagram.com/reel/ABC1020/",+ post_call.kwargs["params"]["url"],+ )+ self.assertEqual(1, post_call.kwargs["retries"])++ def test_404_is_preserved_when_google_fallback_has_no_results(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ with patch.object(+ http_module, "get", side_effect=[not_found, {"results": []}]+ ):+ result = instagram.search_instagram(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="quick", token="fake-token",+ )++ self.assertEqual([], result["items"])+ self.assertIn("404", result["error"])++ def test_404_is_preserved_when_google_search_fails(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ google_error = http_module.HTTPError("HTTP 503: unavailable", 503, "")+ with patch.object(+ http_module, "get", side_effect=[not_found, google_error]+ ):+ result = instagram.search_instagram(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="quick", token="fake-token",+ )++ self.assertEqual([], result["items"])+ self.assertIn("404", result["error"])++ def test_google_fallback_rejects_non_instagram_and_non_reel_urls(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ results = {+ "results": [+ {"url": "https://example.com/reel/EXAMPLE/"},+ {"url": "http://instagram.com/reel/HTTP/"},+ {"url": "https://instagram.com.example.org/reel/LOOKALIKE/"},+ {"url": "https://instagram.com/p/POST/"},+ {"url": "https://instagram.com/not/reel/PREFIX/"},+ {"url": "https://[invalid/reel/MALFORMED/"},+ ]+ }+ with patch.object(+ http_module, "get", side_effect=[not_found, results]+ ) as mock_http_get:+ result = instagram.search_instagram(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="quick", token="fake-token",+ )++ self.assertEqual([], result["items"])+ self.assertIn("404", result["error"])+ self.assertEqual(2, mock_http_get.call_count)++ def test_google_fallback_drops_posts_outside_requested_date_range(self):+ from lib import http as http_module++ with patch.object(+ http_module,+ "get",+ side_effect=[+ {"reels": []},+ {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]},+ self._post_payload(),+ ],+ ):+ result = instagram.search_instagram(+ "AI automation", "2025-08-01", "2025-08-31",+ depth="quick", token="fake-token",+ )++ self.assertEqual([], result["items"])+ self.assertNotIn("error", result)++ def test_empty_reels_search_uses_google_fallback(self):+ from lib import http as http_module++ with patch.object(+ http_module,+ "get",+ side_effect=[+ {"reels": []},+ {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]},+ self._post_payload(),+ ],+ ) as mock_http_get:+ result = instagram.search_instagram(+ "AI automation for small business",+ "2026-08-01",+ "2026-08-31",+ depth="quick",+ token="fake-token",+ )++ self.assertEqual(1, len(result["items"]))+ self.assertEqual(3, mock_http_get.call_count)++ def test_default_depth_fallback_searches_the_second_page(self):+ from lib import http as http_module++ with patch.object(+ http_module,+ "get",+ side_effect=[+ {"reels": []},+ {"results": []},+ {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]},+ self._post_payload(),+ ],+ ) as mock_http_get:+ result = instagram.search_instagram(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="default", token="fake-token",+ )++ self.assertEqual(1, len(result["items"]))+ google_calls = [+ call for call in mock_http_get.call_args_list+ if call.args[0].endswith("/v1/google/search")+ ]+ self.assertEqual(+ [1, 2], [call.kwargs["params"]["page"] for call in google_calls]+ )++ def test_expanded_queries_share_the_depth_fallback_budget(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ with (+ patch.object(+ instagram,+ "expand_instagram_queries",+ return_value=["first", "second"],+ ),+ patch.object(instagram, "fetch_captions", return_value={}),+ patch.object(+ http_module,+ "get",+ side_effect=[+ not_found,+ {"results": []},+ not_found,+ {"results": []},+ ],+ ) as mock_http_get,+ ):+ result = instagram.search_and_enrich(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="default", token="fake-token",+ )++ self.assertEqual([], result["items"])+ google_calls = [+ call for call in mock_http_get.call_args_list+ if call.args[0].endswith("/v1/google/search")+ ]+ self.assertEqual(2, len(google_calls))+ self.assertEqual(+ [1, 1], [call.kwargs["params"]["page"] for call in google_calls]+ )++ def test_expanded_queries_fetch_each_reel_shortcode_once(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ with (+ patch.object(+ instagram,+ "expand_instagram_queries",+ return_value=["first", "second"],+ ),+ patch.object(instagram, "fetch_captions", return_value={}),+ patch.object(+ http_module,+ "get",+ side_effect=[+ not_found,+ {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]},+ self._post_payload(),+ not_found,+ {"results": [{"url": "https://instagram.com/reel/ABC1020"}]},+ ],+ ) as mock_http_get,+ ):+ result = instagram.search_and_enrich(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="default", token="fake-token",+ )++ detail_calls = [+ call for call in mock_http_get.call_args_list+ if call.args[0].endswith("/v1/instagram/post")+ ]+ self.assertEqual(1, len(result["items"]))+ self.assertEqual(1, len(detail_calls))++ def test_expanded_queries_retry_a_failed_detail_within_the_budget(self):+ from lib import http as http_module++ not_found = http_module.HTTPError("HTTP 404: no reels", 404, "")+ temporary_error = http_module.HTTPError("HTTP 503: unavailable", 503, "")+ with (+ patch.object(+ instagram,+ "expand_instagram_queries",+ return_value=["first", "second"],+ ),+ patch.object(instagram, "fetch_captions", return_value={}),+ patch.object(+ http_module,+ "get",+ side_effect=[+ not_found,+ {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]},+ temporary_error,+ not_found,+ {"results": [{"url": "https://instagram.com/reel/ABC1020"}]},+ self._post_payload(),+ ],+ ) as mock_http_get,+ ):+ result = instagram.search_and_enrich(+ "AI automation", "2026-08-01", "2026-08-31",+ depth="default", token="fake-token",+ )++ detail_calls = [+ call for call in mock_http_get.call_args_list+ if call.args[0].endswith("/v1/instagram/post")+ ]+ self.assertEqual(1, len(result["items"]))+ self.assertEqual(2, len(detail_calls))++class TestTranscriptTimeoutConfig(unittest.TestCase):"""Tests for LAST30DAYS_TRANSCRIPT_TIMEOUT configuration.@@ -262,7 +578,10 @@ class TestInstagramArabicTopicEncoding(unittest.TestCase):resp = MagicMock()resp.__enter__ = MagicMock(return_value=resp)resp.__exit__ = MagicMock(return_value=False)- resp.read.return_value = b'{"reels": []}'+ resp.read.return_value = (+ b'{"reels": [{"id": "arabic-result", '+ b'"taken_at": "2026-06-10T00:00:00Z"}]}'+ )resp.status = 200mock_urlopen.return_value = resp