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(reddit): keep keyless Reddit discovery working after the RSS shutdown (#1189)
Matt Van Horn39a0adda954f
diff --git a/CONCEPTS.md b/CONCEPTS.mdindex 8a1d404d..d99cef19 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -42,7 +42,7 @@ The fused unit of evidence that ranking, clustering, and rendering operate on: e### Keyless path-The research flow available with no API keys: source data is gathered by scraping and RSS rather than authenticated APIs, and ranking falls back to local scoring instead of LLM-based reranking. This is the free tier of the Skill; lexical quality safeguards like Entity grounding matter most here, because no LLM is available to judge relevance semantically.+The research flow available with no API keys: source data is gathered by scraping public web pages rather than authenticated APIs, and ranking falls back to local scoring instead of LLM-based reranking. This is the free tier of the Skill; lexical quality safeguards like Entity grounding matter most here, because no LLM is available to judge relevance semantically.### Comment-enrichment slotsdiff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex c42d7648..076a1d1a 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -150,7 +150,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \| Source | Key(s) | Required for | Free tier ||---|---|---|---|| Local corpus | `--corpus <dir>` or `LAST30DAYS_CORPUS_DIRS` | private `.md`/`.txt`; `.pdf` when `pdftotext` is on PATH | yes (offline) |-| Reddit (public) | none (default free keyless path). With `SCRAPECREATORS_API_KEY`: empty-only search backup by default; `LAST30DAYS_REDDIT_SC_MIN_ITEMS=<N>` backfills thin free runs; `LAST30DAYS_REDDIT_BACKEND=scrapecreators` pins SC primary with free fallback. `LAST30DAYS_REDDIT_KEYLESS_RATE` paces unauthenticated reddit.com requests (default `1` req/sec) | always on; SC knobs require `SCRAPECREATORS_API_KEY` | yes |+| Reddit (public) | none (default free keyless path). With `SCRAPECREATORS_API_KEY`: search backfill when the free path returns fewer than 5 items by default (`LAST30DAYS_REDDIT_SC_MIN_ITEMS=<N>` changes the floor, `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` backfills only when it returns nothing); `LAST30DAYS_REDDIT_BACKEND=scrapecreators` pins SC primary with free fallback. `LAST30DAYS_REDDIT_KEYLESS_RATE` paces unauthenticated reddit.com requests (default `1` req/sec) | always on; SC knobs require `SCRAPECREATORS_API_KEY` | yes || Hacker News | none | always on | yes || Polymarket | none | always on | yes || StockTwits | none | auto-on for ticker/crypto topics only (gated by symbol detection); never registered for non-financial topics | yes (public API, ~200 req/hr per IP) |@@ -182,7 +182,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) |-**Reddit keyless pacing.** Unauthenticated reddit.com requests (RSS, 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 RSS 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`).+**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 transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. `LAST30DAYS_YT_PLAYER_CLIENT` defaults to `android` so yt-dlp can pass YouTube's web bot-gate without cookies (search, transcripts, and comments); set it empty to disable. 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.@@ -528,7 +528,7 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json| `AGENTCOOKIE` | `on` opts any host (incl. a MacBook) into the extra bird cookie lookups (agentcookie sidecar + live Chrome CDP); `off` disables the agentcookie sidecar reader. Unset uses host detection (Linux / Mac mini / Darwin sink get the extras). See "Extra bird cookie lookups" above. || `BROWSER_CDP_URL` | Explicit Chrome DevTools endpoint (e.g. `http://127.0.0.1:18800`) for the extra-host CDP cookie lookup. Preferred over the `18800` / `9222`+`$DISPLAY` defaults. Extra hosts only. || `LAST30DAYS_REDDIT_BACKEND` | `scrapecreators` makes ScrapeCreators the primary Reddit backend; doctor renders Reddit's conditional routing with the pin applied. |-| `LAST30DAYS_REDDIT_SC_MIN_ITEMS` | Integer thinness floor for ScrapeCreators Reddit **search** backfill. Default `0` = empty-only (free path keeps any non-empty result; no credit spend). Set above `0` to backfill when free yield is below that count; merged results dedupe by post id. Requires `SCRAPECREATORS_API_KEY`. Ignored when `LAST30DAYS_REDDIT_BACKEND=scrapecreators` (SC is already primary). |+| `LAST30DAYS_REDDIT_SC_MIN_ITEMS` | Integer thinness floor for ScrapeCreators Reddit **search** backfill. Default `5`: backfill when the free path returns fewer than 5 items, spending ScrapeCreators credits. Set another positive count to move the floor, or `0` to backfill only when the free path returns nothing. Unset or blank means `5`; a malformed value behaves like `0` (spends nothing extra). A run makes at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set, and each backfill is several API calls (searches plus comment fetches, roughly 10 at default depth). A failed backfill after free items only adds a detail note. Merged results dedupe by post id. Requires `SCRAPECREATORS_API_KEY`. Ignored when `LAST30DAYS_REDDIT_BACKEND=scrapecreators` (SC is already primary). |Web search has **no** env pin — pin it per-run with `--web-backend=<name>` only (see [Web search backend priority](#web-search-backend-priority)).diff --git a/changelog.d/+reddit-sc-backfill-floor.changed.md b/changelog.d/+reddit-sc-backfill-floor.changed.mdnew file mode 100644index 00000000..9360b8cd--- /dev/null+++ b/changelog.d/+reddit-sc-backfill-floor.changed.md@@ -0,0 +1 @@+With `SCRAPECREATORS_API_KEY` set, Reddit now spends ScrapeCreators credits to backfill search whenever the free path returns fewer than 5 items, instead of only when it returns nothing. A run makes at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set, and each backfill is several API calls (searches plus comment fetches, roughly 10 at default depth). Set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` to restore the old backfill-only-when-empty behavior.diff --git a/changelog.d/+reddit-site-search.added.md b/changelog.d/+reddit-site-search.added.mdnew file mode 100644index 00000000..07f01322--- /dev/null+++ b/changelog.d/+reddit-site-search.added.md@@ -0,0 +1 @@+Keyless Reddit discovery now uses Reddit's own site search, alongside subreddit listings, arctic-shift, and shreddit comments, so Reddit keeps working with no API key after the RSS shutdown.diff --git a/changelog.d/+reddit-site-search.removed.md b/changelog.d/+reddit-site-search.removed.mdnew file mode 100644index 00000000..ed0c370e--- /dev/null+++ b/changelog.d/+reddit-site-search.removed.md@@ -0,0 +1 @@+Keyless Reddit discovery no longer uses Reddit RSS feeds, which Reddit shuts off on 2026-11-13.diff --git a/docs/solutions/logic-errors/fusion-source-item-dedupe-by-stream-local-id-drops-enrichment.md b/docs/solutions/logic-errors/fusion-source-item-dedupe-by-stream-local-id-drops-enrichment.mdindex 325e3b23..052febdf 100644--- a/docs/solutions/logic-errors/fusion-source-item-dedupe-by-stream-local-id-drops-enrichment.md+++ b/docs/solutions/logic-errors/fusion-source-item-dedupe-by-stream-local-id-drops-enrichment.md@@ -76,7 +76,7 @@ A thread's URL is the same in every stream; its per-stream id is not. Keying on## Prevention-- Never de-duplicate across subquery streams by an adapter-assigned id. Ids like `R{n}` (`skills/last30days/scripts/lib/reddit_keyless.py:397`, `skills/last30days/scripts/lib/reddit_rss.py:236`) are positions within one call, not identities. Use `fusion.candidate_key` for identity and `fusion.merge_source_items` for the merge.+- Never de-duplicate across subquery streams by an adapter-assigned id. Ids like `R{n}` (`skills/last30days/scripts/lib/reddit_keyless.py:388`, `skills/last30days/scripts/lib/reddit_search.py:291`) are positions within one call, not identities. Use `fusion.candidate_key` for identity and `fusion.merge_source_items` for the merge.- When two copies of one item can differ in enrichment, dedupe must merge, not pick. A dedupe that keeps the first or highest-ranked copy silently loses whatever the other copy was enriched with; assert in tests that the retained copy carries the union.- The cheapest detector is in `last-report.json`: count duplicate URLs per source in `items_by_source`, and compare `metadata.top_comments` between `items_by_source` and the corresponding `ranked_candidates[*].source_items`. Any thread with comments in the former and none in the latter is this class of bug.- Multi-subquery plans are the trigger. A single-subquery run never produces two copies, so a fix verified only on `--quick` or one-subquery runs can miss it; the live check is a four-subquery plan on a busy topic with a dedicated subreddit.diff --git a/fixtures/reddit_search_challenge.html b/fixtures/reddit_search_challenge.htmlnew file mode 100644index 00000000..f3fb758d--- /dev/null+++ b/fixtures/reddit_search_challenge.html@@ -0,0 +1,22 @@+<!-- FIXTURE: SYNTHETIC, not a live capture. Models an HTTP 200 anti-bot interstitial served in place of reddit.com/svc/shreddit/search/ (no search result units, no no-results unit). Written 2026-09-30 because a challenge page could not be triggered on demand. -->+<!DOCTYPE html>+<html lang="en-US">+<head>+<title>Reddit - Please wait for verification</title>+<meta name="robots" content="noindex, nofollow">+</head>+<body>+<shreddit-app>+<main id="main-content">+<div>+<h1>Please wait for verification</h1>+<p>Reddit is checking that your connection is secure before continuing.</p>+<noscript>JavaScript is required to continue.</noscript>+<form id="challenge-form" method="POST" action="/svc/shreddit/js-challenge">+<input type="hidden" name="solution" value="">+</form>+</div>+</main>+</shreddit-app>+</body>+</html>diff --git a/fixtures/reddit_search_last_page.html b/fixtures/reddit_search_last_page.htmlnew file mode 100644index 00000000..99b7b69b--- /dev/null+++ b/fixtures/reddit_search_last_page.html@@ -0,0 +1,117 @@+<!-- FIXTURE: captured live from reddit.com/svc/shreddit/r/TubiTV/search/?q=Tubi&type=posts&t=week&sort=relevance (page 5, reached by following cursors) on 2026-09-30; head, scripts, styles, svg, session ids, and class/style attrs stripped. 2 post units, no next-page cursor. -->+<body>+ <a rpl href="#main-content" id="shreddit-skip-link"><span>+ <span>Skip to main content</span>+ </span>+ </a>+ <shreddit-async-loader bundleName="reputation_recaptcha">+ <reputation-recaptcha site-key="6LfirrMoAAAAAHZOipvza4kpp_VtTwLNuXVwURNQ"></reputation-recaptcha>+ </shreddit-async-loader>+ <shreddit-app>+ <app-plugin-overlay-manager-controller parent="shreddit-app">+ </app-plugin-overlay-manager-controller>+ <app-plugin-navigation-controller parent="shreddit-app">+ </app-plugin-navigation-controller>+ <app-plugin-performance-observer-controller parent="shreddit-app">+ </app-plugin-performance-observer-controller>+ <app-plugin-platform-health-controller parent="shreddit-app">+ </app-plugin-platform-health-controller>+ <app-plugin-pwa-controller parent="shreddit-app"></app-plugin-pwa-controller>+ <app-plugin-deferred-experience-batch-controller parent="shreddit-app">+ </app-plugin-deferred-experience-batch-controller>+ <faceplate-server-session timestamp="1790807258919"></faceplate-server-session>+ <shreddit-good-visit-tracker referrerType="other" pageType="unknown">+ </shreddit-good-visit-tracker><shreddit-seo-good-visit-tracker referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker>+ <shreddit-async-loader bundleName="screen_reader_alerts">+ <screen-reader-alert-outlet></screen-reader-alert-outlet>+ </shreddit-async-loader>+ <!-- routable page start -->+ <shreddit-activated-feature-meta></shreddit-activated-feature-meta>+ <shreddit-page-meta>+ <template>+ <shreddit-app-attrs>+ </shreddit-app-attrs>+ <shreddit-good-visit-tracker-attrs pageType="unknown" referrerType="other">+ </shreddit-good-visit-tracker-attrs>+ <shreddit-seo-good-visit-tracker-attrs referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker-attrs>+ </template>+ </shreddit-page-meta> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":28,"relative_position":28},"post":{"id":"t3_1wtoesn","nsfw":false,"spoiler":false,"title":"Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff."},"profile":{"id":"t2_1day19axra","name":"Additional_Stuff4168"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post" data-testid="search-sdui-post" data-thingid="t3_1wtoesn"><div data-testid="search-post-unit">+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":28,"relative_position":28,"type":"post"},"post":{"id":"t3_1wtoesn","nsfw":false,"spoiler":false,"title":"Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff."},"profile":{"id":"t2_1day19axra","name":"Additional_Stuff4168"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/TubiTV/comments/1wtoesn/just_finished_watching_the_mobsters_series_i/" aria-label="Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff.">+ <faceplate-screen-reader-content>Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff.</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/TubiTV" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":28,"relative_position":28,"type":"community"},"post":{"id":"t3_1wtoesn","nsfw":false,"spoiler":false,"title":"Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff."},"profile":{"id":"t2_1day19axra","name":"Additional_Stuff4168"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/TubiTV/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/TubiTV</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/TubiTV" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-29T22:39:01.143000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1wtoesn" href="/r/TubiTV/comments/1wtoesn/just_finished_watching_the_mobsters_series_i/">+ Just finished watching the mobsters series. I definitely enjoyed it. Anyone else watched it? It's worth a watch if you like mafia stuff.+ </a> <div data-testid="search-counter-row">+ <span><faceplate-number number="9" pretty></faceplate-number> votes</span><span>·</span><span><faceplate-number number="5" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div></search-telemetry-tracker><hr> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":29,"relative_position":29},"post":{"id":"t3_1wns3fq","nsfw":false,"spoiler":false,"title":"Subtitles toggling off via VPN"},"profile":{"id":"t2_bwuq7evl","name":"NoRuin9991"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post" data-testid="search-sdui-post" data-thingid="t3_1wns3fq"><div data-testid="search-post-unit">+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":29,"relative_position":29,"type":"post"},"post":{"id":"t3_1wns3fq","nsfw":false,"spoiler":false,"title":"Subtitles toggling off via VPN"},"profile":{"id":"t2_bwuq7evl","name":"NoRuin9991"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/TubiTV/comments/1wns3fq/subtitles_toggling_off_via_vpn/" aria-label="Subtitles toggling off via VPN">+ <faceplate-screen-reader-content>Subtitles toggling off via VPN</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/TubiTV" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":29,"relative_position":29,"type":"community"},"post":{"id":"t3_1wns3fq","nsfw":false,"spoiler":false,"title":"Subtitles toggling off via VPN"},"profile":{"id":"t2_bwuq7evl","name":"NoRuin9991"},"search":{"range":"week","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_3cc2e","name":"TubiTV","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/TubiTV/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/TubiTV</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/TubiTV" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-23T01:22:44.786000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1wns3fq" href="/r/TubiTV/comments/1wns3fq/subtitles_toggling_off_via_vpn/">+ Subtitles toggling off via VPN+ </a> <div data-testid="search-counter-row">+ <span><faceplate-number number="1" pretty></faceplate-number> vote</span><span>·</span><span><faceplate-number number="0" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div></search-telemetry-tracker><hr>+ <!-- routable page end --><faceplate-partial name="DataProtectionConsent_qBKqbZ" src="/svc/shreddit/data-protection-consent" loading="eager"></faceplate-partial><faceplate-perfmetric-collector endpoint="/svc/shreddit/perfMetrics">+ <data value="first-contentful-paint"></data> <data value="time-to-first-byte"></data> <data value="largest-contentful-paint"></data> <data value="cumulative-layout-shift"></data>+ </faceplate-perfmetric-collector>+ </shreddit-app>+ <img>+ <navigation-indicator></navigation-indicator>+ </body>+ </html>+ <suspense-execute-deferred-scripts></suspense-execute-deferred-scripts>diff --git a/fixtures/reddit_search_no_results.html b/fixtures/reddit_search_no_results.htmlnew file mode 100644index 00000000..1eb4035d--- /dev/null+++ b/fixtures/reddit_search_no_results.html@@ -0,0 +1,60 @@+<!-- FIXTURE: captured live from reddit.com/svc/shreddit/search/?q=%22zxqvbnmplkqqwerty7731%22&type=posts&t=hour&sort=relevance on 2026-09-30; head, scripts, styles, svg, session ids, and class/style attrs stripped. Reddit's explicit no-results unit (tracking context reason=empty). -->+<body>+ <a rpl href="#main-content" id="shreddit-skip-link"><span>+ <span>Skip to main content</span>+ </span>+ </a>+ <shreddit-async-loader bundleName="reputation_recaptcha">+ <reputation-recaptcha site-key="6LfirrMoAAAAAHZOipvza4kpp_VtTwLNuXVwURNQ"></reputation-recaptcha>+ </shreddit-async-loader>+ <shreddit-app>+ <app-plugin-overlay-manager-controller parent="shreddit-app">+ </app-plugin-overlay-manager-controller>+ <app-plugin-navigation-controller parent="shreddit-app">+ </app-plugin-navigation-controller>+ <app-plugin-performance-observer-controller parent="shreddit-app">+ </app-plugin-performance-observer-controller>+ <app-plugin-platform-health-controller parent="shreddit-app">+ </app-plugin-platform-health-controller>+ <app-plugin-pwa-controller parent="shreddit-app"></app-plugin-pwa-controller>+ <app-plugin-deferred-experience-batch-controller parent="shreddit-app">+ </app-plugin-deferred-experience-batch-controller>+ <faceplate-server-session timestamp="1790807198011"></faceplate-server-session>+ <shreddit-good-visit-tracker referrerType="other" pageType="unknown">+ </shreddit-good-visit-tracker><shreddit-seo-good-visit-tracker referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker>+ <shreddit-async-loader bundleName="screen_reader_alerts">+ <screen-reader-alert-outlet></screen-reader-alert-outlet>+ </shreddit-async-loader>+ <!-- routable page start -->+ <shreddit-activated-feature-meta></shreddit-activated-feature-meta>+ <shreddit-page-meta>+ <template>+ <shreddit-app-attrs>+ </shreddit-app-attrs>+ <shreddit-good-visit-tracker-attrs pageType="unknown" referrerType="other">+ </shreddit-good-visit-tracker-attrs>+ <shreddit-seo-good-visit-tracker-attrs referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker-attrs>+ </template>+ </shreddit-page-meta> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"reason":"empty"},"search":{"range":"hour","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/no_results"><div data-testid="search-error-message">+ <img>+ <div>Hm...we couldn’t find any results for "zxqvbnmplkqqwerty7731"</div>+ <div>Double-check your spelling or try different keywords</div>+ <div data-testid="search-error-message-ctas">+ <adjust-search-query-link input-selector="reddit-header-large"><button rpl data-testid="search-error-message-primary-cta">+ <span>+ <span>Adjust your search</span>+ </span>+ </button></adjust-search-query-link>+ </div>+ </div></search-telemetry-tracker>+ <!-- routable page end --><faceplate-partial name="DataProtectionConsent_qBKqbZ" src="/svc/shreddit/data-protection-consent" loading="eager"></faceplate-partial><faceplate-perfmetric-collector endpoint="/svc/shreddit/perfMetrics">+ <data value="first-contentful-paint"></data> <data value="time-to-first-byte"></data> <data value="largest-contentful-paint"></data> <data value="cumulative-layout-shift"></data>+ </faceplate-perfmetric-collector>+ </shreddit-app>+ <img>+ <navigation-indicator></navigation-indicator>+ </body>+ </html>+ <suspense-execute-deferred-scripts></suspense-execute-deferred-scripts>diff --git a/fixtures/reddit_search_page1.html b/fixtures/reddit_search_page1.htmlnew file mode 100644index 00000000..308f2f2f--- /dev/null+++ b/fixtures/reddit_search_page1.html@@ -0,0 +1,425 @@+<!-- FIXTURE: captured live from reddit.com/svc/shreddit/search/?q=ButcherBox&type=posts&t=month&sort=relevance on 2026-09-30; head, scripts, styles, svg, session ids, and class/style attrs stripped. 7 post units, query suggestions, and a next-page cursor partial. -->+<body>+ <a rpl href="#main-content" id="shreddit-skip-link"><span>+ <span>Skip to main content</span>+ </span>+ </a>+ <shreddit-async-loader bundleName="reputation_recaptcha">+ <reputation-recaptcha site-key="6LfirrMoAAAAAHZOipvza4kpp_VtTwLNuXVwURNQ"></reputation-recaptcha>+ </shreddit-async-loader>+ <shreddit-app>+ <app-plugin-overlay-manager-controller parent="shreddit-app">+ </app-plugin-overlay-manager-controller>+ <app-plugin-navigation-controller parent="shreddit-app">+ </app-plugin-navigation-controller>+ <app-plugin-performance-observer-controller parent="shreddit-app">+ </app-plugin-performance-observer-controller>+ <app-plugin-platform-health-controller parent="shreddit-app">+ </app-plugin-platform-health-controller>+ <app-plugin-pwa-controller parent="shreddit-app"></app-plugin-pwa-controller>+ <app-plugin-deferred-experience-batch-controller parent="shreddit-app">+ </app-plugin-deferred-experience-batch-controller>+ <faceplate-server-session timestamp="1790807210509"></faceplate-server-session>+ <shreddit-good-visit-tracker referrerType="other" pageType="unknown">+ </shreddit-good-visit-tracker><shreddit-seo-good-visit-tracker referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker>+ <shreddit-async-loader bundleName="screen_reader_alerts">+ <screen-reader-alert-outlet></screen-reader-alert-outlet>+ </shreddit-async-loader>+ <!-- routable page start -->+ <shreddit-activated-feature-meta></shreddit-activated-feature-meta>+ <shreddit-page-meta>+ <template>+ <shreddit-app-attrs>+ </shreddit-app-attrs>+ <shreddit-good-visit-tracker-attrs pageType="unknown" referrerType="other">+ </shreddit-good-visit-tracker-attrs>+ <shreddit-seo-good-visit-tracker-attrs referrer-type="other" page-type="unknown">+ </shreddit-seo-good-visit-tracker-attrs>+ </template>+ </shreddit-page-meta> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":0,"relative_position":0},"post":{"id":"t3_1w6swt2","nsfw":false,"spoiler":false,"title":"Looking for a ButcherBox referral code"},"profile":{"id":"t2_9nl0jfz0","name":"grassyglassy"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_31den","name":"referralcodes","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post" data-testid="search-sdui-post" data-thingid="t3_1w6swt2"><div data-testid="search-post-unit">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":0,"relative_position":0,"type":"post"},"post":{"id":"t3_1w6swt2","nsfw":false,"spoiler":false,"title":"Looking for a ButcherBox referral code"},"profile":{"id":"t2_9nl0jfz0","name":"grassyglassy"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_31den","name":"referralcodes","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/referralcodes/comments/1w6swt2/looking_for_a_butcherbox_referral_code/" aria-label="Looking for a ButcherBox referral code">+ <faceplate-screen-reader-content>Looking for a ButcherBox referral code</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/referralcodes" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":0,"relative_position":0,"type":"community"},"post":{"id":"t3_1w6swt2","nsfw":false,"spoiler":false,"title":"Looking for a ButcherBox referral code"},"profile":{"id":"t2_9nl0jfz0","name":"grassyglassy"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_31den","name":"referralcodes","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/referralcodes/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/referralcodes</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/referralcodes" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-04T03:26:52.161000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1w6swt2" href="/r/referralcodes/comments/1w6swt2/looking_for_a_butcherbox_referral_code/">+ Looking for a <span data-testid="post-title-query">ButcherBox</span> referral code+ </a> <div data-testid="search-counter-row">+ <span><faceplate-number number="1" pretty></faceplate-number> vote</span><span>·</span><span><faceplate-number number="27" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ </div>+ </div></search-telemetry-tracker><hr><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":1},"post":{"id":"t3_1wkybur","nsfw":false,"spoiler":false,"title":"Today’s Ad Read for ButcherBox"},"profile":{"id":"t2_ttj8l3j1d","name":"Altruistic_Echidna86"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE","snippet_id":"t1_pbbf2p4"},"subreddit":{"id":"t5_3iptz","name":"TimDillon","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post"><div data-testid="search-post-with-content-preview">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":1,"type":"post"},"post":{"id":"t3_1wkybur","nsfw":false,"spoiler":false,"title":"Today’s Ad Read for ButcherBox"},"profile":{"id":"t2_ttj8l3j1d","name":"Altruistic_Echidna86"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE","snippet_id":"t1_pbbf2p4"},"subreddit":{"id":"t5_3iptz","name":"TimDillon","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/TimDillon/comments/1wkybur/todays_ad_read_for_butcherbox/" aria-label="Today’s Ad Read for ButcherBox">+ <faceplate-screen-reader-content>Today’s Ad Read for ButcherBox</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/TimDillon" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":1,"type":"community"},"post":{"id":"t3_1wkybur","nsfw":false,"spoiler":false,"title":"Today’s Ad Read for ButcherBox"},"profile":{"id":"t2_ttj8l3j1d","name":"Altruistic_Echidna86"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE","snippet_id":"t1_pbbf2p4"},"subreddit":{"id":"t5_3iptz","name":"TimDillon","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/TimDillon/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/TimDillon</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/TimDillon" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-19T21:35:16.906000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1wkybur" href="/r/TimDillon/comments/1wkybur/todays_ad_read_for_butcherbox/">+ Today’s Ad Read for <span data-testid="post-title-query">ButcherBox</span>+ </a> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":1,"type":"snippet"},"post":{"id":"t3_1wkybur","nsfw":false,"spoiler":false,"title":"Today’s Ad Read for ButcherBox"},"profile":{"id":"t2_ttj8l3j1d","name":"Altruistic_Echidna86"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE","snippet_id":"t1_pbbf2p4"},"subreddit":{"id":"t5_3iptz","name":"TimDillon","nsfw":false,"quarantined":false}}" click-events="search/click/post">+ <a href="/r/TimDillon/comments/1wkybur/todays_ad_read_for_butcherbox/">+ You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE+ </a>+ </search-telemetry-tracker> <div data-testid="search-counter-row">+ <span><faceplate-number number="144" pretty></faceplate-number> votes</span><span>·</span><span><faceplate-number number="26" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":1,"type":"thumbnail"},"post":{"id":"t3_1wkybur","nsfw":false,"spoiler":false,"title":"Today’s Ad Read for ButcherBox"},"profile":{"id":"t2_ttj8l3j1d","name":"Altruistic_Echidna86"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"You shouldn’t be eating ice cream, you should be eating protein, like I am. I got a steak on the grill. SIIIIZZZZZLLLLEEEEE","snippet_id":"t1_pbbf2p4"},"subreddit":{"id":"t5_3iptz","name":"TimDillon","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a rpl aria-label="Today’s Ad Read for ButcherBox thumbnail image" href="/r/TimDillon/comments/1wkybur/todays_ad_read_for_butcherbox/"><div>+ <div>+ <faceplate-img alt="Today’s Ad Read for ButcherBox" data-testid="search_post_thumbnail" src="https://preview.redd.it/8awn85c1qjqh1.jpeg?width=140&height=140&crop=1%3A1%2Csmart&auto=webp&s=a814c5744fe9ff8d8c4871c0729ed3db7dd6cb18"></faceplate-img>+ </div>+ </div></a></search-telemetry-tracker>+ </div>+ </div></search-telemetry-tracker><hr><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":2},"post":{"id":"t3_1w9s403","nsfw":false,"spoiler":false,"title":"Best online butchers in the Netherlands?🥩"},"profile":{"id":"t2_gdx477np","name":"Shreddedsickcuntt"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I’m mainly interested high-quality beef, veal, chicken and duck.","snippet_id":"t3_1w9s403"},"subreddit":{"id":"t5_2r0ol","name":"Netherlands","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post"><div data-testid="search-post-with-content-preview">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":2,"type":"post"},"post":{"id":"t3_1w9s403","nsfw":false,"spoiler":false,"title":"Best online butchers in the Netherlands?🥩"},"profile":{"id":"t2_gdx477np","name":"Shreddedsickcuntt"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I’m mainly interested high-quality beef, veal, chicken and duck.","snippet_id":"t3_1w9s403"},"subreddit":{"id":"t5_2r0ol","name":"Netherlands","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/Netherlands/comments/1w9s403/best_online_butchers_in_the_netherlands/" aria-label="Best online butchers in the Netherlands?🥩">+ <faceplate-screen-reader-content>Best online butchers in the Netherlands?🥩</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/Netherlands" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":2,"type":"community"},"post":{"id":"t3_1w9s403","nsfw":false,"spoiler":false,"title":"Best online butchers in the Netherlands?🥩"},"profile":{"id":"t2_gdx477np","name":"Shreddedsickcuntt"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I’m mainly interested high-quality beef, veal, chicken and duck.","snippet_id":"t3_1w9s403"},"subreddit":{"id":"t5_2r0ol","name":"Netherlands","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/Netherlands/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/Netherlands</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/Netherlands" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-07T13:24:35.698000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1w9s403" href="/r/Netherlands/comments/1w9s403/best_online_butchers_in_the_netherlands/">+ Best online butchers in the Netherlands?🥩+ </a> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":2,"type":"snippet"},"post":{"id":"t3_1w9s403","nsfw":false,"spoiler":false,"title":"Best online butchers in the Netherlands?🥩"},"profile":{"id":"t2_gdx477np","name":"Shreddedsickcuntt"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I’m mainly interested high-quality beef, veal, chicken and duck.","snippet_id":"t3_1w9s403"},"subreddit":{"id":"t5_2r0ol","name":"Netherlands","nsfw":false,"quarantined":false}}" click-events="search/click/post">+ <a href="/r/Netherlands/comments/1w9s403/best_online_butchers_in_the_netherlands/">+ I’m mainly interested high-quality beef, veal, chicken and duck.+ </a>+ </search-telemetry-tracker> <div data-testid="search-counter-row">+ <span><faceplate-number number="0" pretty></faceplate-number> votes</span><span>·</span><span><faceplate-number number="62" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ </div>+ </div></search-telemetry-tracker><hr> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":3,"relative_position":3},"post":{"id":"t3_1wbvi5s","nsfw":false,"spoiler":false,"title":"Anyone has a butcher box referral code?"},"profile":{"id":"t2_1wevpozvnf","name":"superbabydoll"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post" data-testid="search-sdui-post" data-thingid="t3_1wbvi5s"><div data-testid="search-post-unit">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":3,"relative_position":3,"type":"post"},"post":{"id":"t3_1wbvi5s","nsfw":false,"spoiler":false,"title":"Anyone has a butcher box referral code?"},"profile":{"id":"t2_1wevpozvnf","name":"superbabydoll"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/findareferralcode/comments/1wbvi5s/anyone_has_a_butcher_box_referral_code/" aria-label="Anyone has a butcher box referral code?">+ <faceplate-screen-reader-content>Anyone has a butcher box referral code?</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/findareferralcode" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":3,"relative_position":3,"type":"community"},"post":{"id":"t3_1wbvi5s","nsfw":false,"spoiler":false,"title":"Anyone has a butcher box referral code?"},"profile":{"id":"t2_1wevpozvnf","name":"superbabydoll"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/findareferralcode/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ </span></span>+ </span>+ <span>r/findareferralcode</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/findareferralcode" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-09T19:25:01.448000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1wbvi5s" href="/r/findareferralcode/comments/1wbvi5s/anyone_has_a_butcher_box_referral_code/">+ Anyone has a butcher box referral code?+ </a> <div data-testid="search-counter-row">+ <span><faceplate-number number="1" pretty></faceplate-number> vote</span><span>·</span><span><faceplate-number number="1" pretty></faceplate-number> comment</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ </div>+ </div></search-telemetry-tracker><hr><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":4},"post":{"id":"t3_1w7w7k3","nsfw":false,"spoiler":false,"title":"Found the free gems"},"profile":{"id":"t2_2l77xnacn4","name":"TurbulentWater8581"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I don't have this quest thing on my game, is there any other website or app where can I get this or what?","snippet_id":"t1_p8014zk"},"subreddit":{"id":"t5_hwp7tm","name":"ButcherHero_HooknChew","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post"><div data-testid="search-post-with-content-preview">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":4,"type":"post"},"post":{"id":"t3_1w7w7k3","nsfw":false,"spoiler":false,"title":"Found the free gems"},"profile":{"id":"t2_2l77xnacn4","name":"TurbulentWater8581"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I don't have this quest thing on my game, is there any other website or app where can I get this or what?","snippet_id":"t1_p8014zk"},"subreddit":{"id":"t5_hwp7tm","name":"ButcherHero_HooknChew","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/ButcherHero_HooknChew/comments/1w7w7k3/found_the_free_gems/" aria-label="Found the free gems">+ <faceplate-screen-reader-content>Found the free gems</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/ButcherHero_HooknChew" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":4,"type":"community"},"post":{"id":"t3_1w7w7k3","nsfw":false,"spoiler":false,"title":"Found the free gems"},"profile":{"id":"t2_2l77xnacn4","name":"TurbulentWater8581"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I don't have this quest thing on my game, is there any other website or app where can I get this or what?","snippet_id":"t1_p8014zk"},"subreddit":{"id":"t5_hwp7tm","name":"ButcherHero_HooknChew","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/ButcherHero_HooknChew/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/ButcherHero_HooknChew</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/ButcherHero_HooknChew" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-05T09:39:24.993000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1w7w7k3" href="/r/ButcherHero_HooknChew/comments/1w7w7k3/found_the_free_gems/">+ Found the free gems+ </a> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":4,"type":"snippet"},"post":{"id":"t3_1w7w7k3","nsfw":false,"spoiler":false,"title":"Found the free gems"},"profile":{"id":"t2_2l77xnacn4","name":"TurbulentWater8581"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I don't have this quest thing on my game, is there any other website or app where can I get this or what?","snippet_id":"t1_p8014zk"},"subreddit":{"id":"t5_hwp7tm","name":"ButcherHero_HooknChew","nsfw":false,"quarantined":false}}" click-events="search/click/post">+ <a href="/r/ButcherHero_HooknChew/comments/1w7w7k3/found_the_free_gems/">+ I don't have this quest thing on my game, is there any other website or app where can I get this or what?+ </a>+ </search-telemetry-tracker> <div data-testid="search-counter-row">+ <span><faceplate-number number="7" pretty></faceplate-number> votes</span><span>·</span><span><faceplate-number number="8" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":4,"type":"thumbnail"},"post":{"id":"t3_1w7w7k3","nsfw":false,"spoiler":false,"title":"Found the free gems"},"profile":{"id":"t2_2l77xnacn4","name":"TurbulentWater8581"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"I don't have this quest thing on my game, is there any other website or app where can I get this or what?","snippet_id":"t1_p8014zk"},"subreddit":{"id":"t5_hwp7tm","name":"ButcherHero_HooknChew","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a rpl aria-label="Found the free gems thumbnail image" href="/r/ButcherHero_HooknChew/comments/1w7w7k3/found_the_free_gems/"><div>+ <div>+ <faceplate-img alt="Found the free gems" data-testid="search_post_thumbnail" src="https://preview.redd.it/cdr2byxj9onh1.jpeg?width=140&height=140&crop=1%3A1%2Csmart&auto=webp&s=c474f0c84ba205b07d4c94b5016fc4fff6c1437b"></faceplate-img>+ </div>+ </div></a></search-telemetry-tracker>+ </div>+ </div></search-telemetry-tracker><hr><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":5},"post":{"id":"t3_1wmumud","nsfw":false,"spoiler":false,"title":"What! Butcher’s website"},"profile":{"id":"t2_rizxib6c","name":"Unusual-Slip-4414"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"Fake primal diet not the one by aajonus","snippet_id":"t1_pbbc4i9"},"subreddit":{"id":"t5_u5k0q","name":"rawprimal","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post"><div data-testid="search-post-with-content-preview">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":5,"type":"post"},"post":{"id":"t3_1wmumud","nsfw":false,"spoiler":false,"title":"What! Butcher’s website"},"profile":{"id":"t2_rizxib6c","name":"Unusual-Slip-4414"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"Fake primal diet not the one by aajonus","snippet_id":"t1_pbbc4i9"},"subreddit":{"id":"t5_u5k0q","name":"rawprimal","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/rawprimal/comments/1wmumud/what_butchers_website/" aria-label="What! Butcher’s website">+ <faceplate-screen-reader-content>What! Butcher’s website</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/rawprimal" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":5,"type":"community"},"post":{"id":"t3_1wmumud","nsfw":false,"spoiler":false,"title":"What! Butcher’s website"},"profile":{"id":"t2_rizxib6c","name":"Unusual-Slip-4414"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"Fake primal diet not the one by aajonus","snippet_id":"t1_pbbc4i9"},"subreddit":{"id":"t5_u5k0q","name":"rawprimal","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/rawprimal/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ <img>+ </span></span>+ </span>+ <span>r/rawprimal</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/rawprimal" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-22T00:37:11.970000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1wmumud" href="/r/rawprimal/comments/1wmumud/what_butchers_website/">+ What! Butcher’s website+ </a> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":5,"type":"snippet"},"post":{"id":"t3_1wmumud","nsfw":false,"spoiler":false,"title":"What! Butcher’s website"},"profile":{"id":"t2_rizxib6c","name":"Unusual-Slip-4414"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"Fake primal diet not the one by aajonus","snippet_id":"t1_pbbc4i9"},"subreddit":{"id":"t5_u5k0q","name":"rawprimal","nsfw":false,"quarantined":false}}" click-events="search/click/post">+ <a href="/r/rawprimal/comments/1wmumud/what_butchers_website/">+ Fake primal diet not the one by aajonus+ </a>+ </search-telemetry-tracker> <div data-testid="search-counter-row">+ <span><faceplate-number number="3" pretty></faceplate-number> votes</span><span>·</span><span><faceplate-number number="7" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":5,"type":"thumbnail"},"post":{"id":"t3_1wmumud","nsfw":false,"spoiler":false,"title":"What! Butcher’s website"},"profile":{"id":"t2_rizxib6c","name":"Unusual-Slip-4414"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search","snippet":"Fake primal diet not the one by aajonus","snippet_id":"t1_pbbc4i9"},"subreddit":{"id":"t5_u5k0q","name":"rawprimal","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a rpl aria-label="What! Butcher’s website thumbnail image" href="/r/rawprimal/comments/1wmumud/what_butchers_website/"><div>+ <div>+ <faceplate-img alt="What! Butcher’s website" data-testid="search_post_thumbnail" src="https://preview.redd.it/sj1v15abwyqh1.jpg?width=140&height=140&crop=1%3A1%2Csmart&auto=webp&s=71d8538b77a3fab342fc108539a1180a793b1850"></faceplate-img>+ </div>+ </div></a></search-telemetry-tracker><div>+ <shreddit-async-loader bundleName="gallery_carousel">+ <gallery-carousel post-id="t3_1wmumud" permalink="" carousel-style="" fetch-ahead-count="3" use-media-lightbox advance-animation device-type="desktop">+ <ul>+ <li slot="page-1">+ <img>+ <figure>+ <img>+ </figure>+ </li><li slot="page-2">+ <img>+ <figure>+ <img>+ </figure>+ </li><li slot="page-3">+ <img>+ <figure>+ <img>+ </figure>+ </li>+ </ul>+ </gallery-carousel>+ </shreddit-async-loader>+ </div>+ </div>+ </div></search-telemetry-tracker><hr> <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":6,"relative_position":6},"post":{"id":"t3_1w4tbqb","nsfw":false,"spoiler":false,"title":"Anybody have a referral code or link for Butcher Box?"},"profile":{"id":"t2_fjx4t3i99","name":"Taco_97"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" view-events="search/view/post" leave-events="post/leave/post" consume-events="post/consume/post" data-testid="search-sdui-post" data-thingid="t3_1w4tbqb"><div data-testid="search-post-unit">+ <div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":6,"relative_position":6,"type":"post"},"post":{"id":"t3_1w4tbqb","nsfw":false,"spoiler":false,"title":"Anybody have a referral code or link for Butcher Box?"},"profile":{"id":"t2_fjx4t3i99","name":"Taco_97"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" click-events="search/click/post"><h2>+ <a data-testid="post-title" href="/r/findareferralcode/comments/1w4tbqb/anybody_have_a_referral_code_or_link_for_butcher/" aria-label="Anybody have a referral code or link for Butcher Box?">+ <faceplate-screen-reader-content>Anybody have a referral code or link for Butcher Box?</faceplate-screen-reader-content>+ </a>+ </h2></search-telemetry-tracker>+ <div data-testid="sdui-post-unit">+ <div><div>+ <span>+ <faceplate-hovercard enter-delay="500" leave-delay="150" position="bottom-start" data-id="community-hover-card" label="r/findareferralcode" mouse-only>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":6,"relative_position":6,"type":"community"},"post":{"id":"t3_1w4tbqb","nsfw":false,"spoiler":false,"title":"Anybody have a referral code or link for Butcher Box?"},"profile":{"id":"t2_fjx4t3i99","name":"Taco_97"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"},"subreddit":{"id":"t5_6zhz9a","name":"findareferralcode","nsfw":false,"quarantined":false}}" click-events="search/click/post"><a href="/r/findareferralcode/">+ <span>+ <span rpl avatar data-no-rtl-mirror>+ <span rpl>+ </span></span>+ </span>+ <span>r/findareferralcode</span></a></search-telemetry-tracker>+ <div slot="content">+ <faceplate-partial src="/svc/shreddit/community-hover-card/findareferralcode" loading="programmatic">+ <div>+ <faceplate-progress value="20"></faceplate-progress>+ </div>+ </faceplate-partial>+ </div>+ </faceplate-hovercard>+ <span>·</span><faceplate-timeago format="narrow" ts="2026-09-01T23:21:31.728000+0000"></faceplate-timeago></span>+ </div> </div>+ <a data-testid="post-title-text" id="search-post-title-t3_1w4tbqb" href="/r/findareferralcode/comments/1w4tbqb/anybody_have_a_referral_code_or_link_for_butcher/">+ Anybody have a referral code or link for Butcher Box?+ </a> <div data-testid="search-counter-row">+ <span><faceplate-number number="1" pretty></faceplate-number> vote</span><span>·</span><span><faceplate-number number="2" pretty></faceplate-number> comments</span>+ </div>+ </div>+ </div><div>+ <ac-gql-mutate operation="ExposeVariant" trigger="click" variables="{"input":{"experimentName":"shreddit_search_media_tap_targets","variant":"control_1","experimentVersion":"5"}}"></ac-gql-mutate>+ </div>+ </div></search-telemetry-tracker><hr> <div>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"type":"thumbs_up_down"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/survey" data-type="search-survey-unit"><ac-gql-mutate operation="StoreUxtargetingAction" trigger="view" variables="{"input":{"action":"VIEW","eligibleExperience":{"experience":"STRING_ID_EXPERIENCE","experienceName":"SEARCH_IN_FEED_SURVEY","uxVariant":{"variantId":"search_survey"}}}}"></ac-gql-mutate> <search-sdui-view-states-container initial-view-state-id="default"><div slot="view-state_default">+ <div>+ <img>+ <span>Did you find what you were looking for?</span>+ </div>+ <div>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"type":"positive"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/survey"><button rpl>+ <span>+ <span><ac-dispatch detail="{"viewStateId":"complete"}" event-name="view-state-change" trigger="click"></ac-dispatch>Yes</span>+ </span>+ </button></search-telemetry-tracker>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"type":"negative"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/survey"><button rpl>+ <span>+ <span><ac-dispatch detail="{"viewStateId":"complete"}" event-name="view-state-change" trigger="click"></ac-dispatch>No</span>+ </span>+ </button></search-telemetry-tracker>+ </div>+ </div><div slot="view-state_complete">+ <ac-dispatch once detail="{"level":7,"message":"Thanks for your feedback!"}" event-name="faceplate-alert" trigger-elem="closest(div)" trigger="view"></ac-dispatch>+ <ac-toggle-attribute once target-attribute="disabled" target="closest([data-type="search-survey-unit"])" trigger="view"></ac-toggle-attribute>+ <ac-call once method="remove" target="div:has(div[slot="view-state_complete"]) ~ hr" trigger="view"></ac-call>+ </div></search-sdui-view-states-container></search-telemetry-tracker>+ </div><hr>+ <div>+ <span>People also search for</span>+ </div>+ <search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"type":"query_suggestion_row"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/unit"> <div><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":0,"relative_position":7},"meta_search":{"display_query":"Butcher Box reviews and customer feedback","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":0,"relative_position":7,"type":"query_suggestion_row"},"meta_search":{"display_query":"Butcher Box reviews and customer feedback","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Butcher+Box+reviews+and+customer+feedback&cId=03c94e08-b845-4083-b489-90fd3f80dab5&iId=b1c83b65-3e5e-45c6-a7a7-aa48bb1879b1"><span>+ <span></span>+ <span>Butcher Box reviews and customer feedback</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":8},"meta_search":{"display_query":"Butcher Box customer experiences and reviews","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":1,"relative_position":8,"type":"query_suggestion_row"},"meta_search":{"display_query":"Butcher Box customer experiences and reviews","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Butcher+Box+customer+experiences+and+reviews&cId=9d3d3d83-bd5c-40a2-a413-6a9119d91788&iId=b0261377-f26e-452b-a211-5f6be09c6465"><span>+ <span></span>+ <span>Butcher Box customer experiences and reviews</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":9},"meta_search":{"display_query":"Are online butcher meat boxes worth it?","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":2,"relative_position":9,"type":"query_suggestion_row"},"meta_search":{"display_query":"Are online butcher meat boxes worth it?","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Are+online+butcher+meat+boxes+worth+it%3F&cId=86d411cf-9f90-4655-a451-10efae647d70&iId=7e0969a2-d8a6-4633-9b13-ff6aaf23b9da"><span>+ <span></span>+ <span>Are online butcher meat boxes worth it?</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":3,"relative_position":10},"meta_search":{"display_query":"Butcher Box meat grade and quality","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":3,"relative_position":10,"type":"query_suggestion_row"},"meta_search":{"display_query":"Butcher Box meat grade and quality","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Butcher+Box+meat+grade+and+quality&cId=c5e10a6e-1bfa-4cd0-b4e7-7f0d489bf606&iId=65f3a119-50de-4355-8bf5-e42908008844"><span>+ <span></span>+ <span>Butcher Box meat grade and quality</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":11},"meta_search":{"display_query":"Meat box delivery options","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":4,"relative_position":11,"type":"query_suggestion_row"},"meta_search":{"display_query":"Meat box delivery options","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Meat+box+delivery+options&cId=16463923-112c-40f5-8047-c79dcff38e37&iId=2601a77d-5699-4033-b975-56b0e005d7f4"><span>+ <span></span>+ <span>Meat box delivery options</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":12},"meta_search":{"display_query":"Best meat boxes for delivery","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" view-events="search/view/query_suggestion" data-testid="search-sdui-query-suggestion-wrapper"><search-telemetry-tracker data-faceplate-tracking-context="{"action_info":{"position":5,"relative_position":12,"type":"query_suggestion_row"},"meta_search":{"display_query":"Best meat boxes for delivery","raw_query":"ButcherBox"},"search":{"range":"month","sort":"RELEVANCE","safe_search":"UNAVAILABLE","structure_type":"search"}}" click-events="search/click/query_suggestion"><a rpl data-testid="search-sdui-query-suggestion" href="/search/?q=Best+meat+boxes+for+delivery&cId=095b5cb3-56b3-484c-9d28-91c957acc7a9&iId=01dbde33-9ed1-4dc1-b851-5c7bf8b42d67"><span>+ <span></span>+ <span>Best meat boxes for delivery</span>+ </span>+ </a></search-telemetry-tracker></search-telemetry-tracker></div></search-telemetry-tracker><hr>+ <faceplate-partial loading="lazy" src="/svc/shreddit/search/?q=ButcherBox&type=posts&sort=relevance&t=month&cursor=eyJjYW5kaWRhdGVzX3JldHVybmVkIjoie1wic2VjdGlvbl8xX3BpcGVsaW5lXzBfZ2xvYmFsX21vZGlmaWVyc1wiOlwiMVwiLFwic2VjdGlvbl8xX3BpcGVsaW5lXzFfbG9jYWxfbW9kaWZpZXJzXCI6XCIyXCIsXCJzZWN0aW9uXzJfcGlwZWxpbmVfMTBfdXh0c191bml0XCI6XCIwXCIsXCJzZWN0aW9uXzJfcGlwZWxpbmVfMTFfcXVlcnlfc3VnZ2VzdGlvbnNcIjpcIjZcIixcInNlY3Rpb25fMl9waXBlbGluZV84X3Bvc3Rfc2VhcmNoXCI6XCI3XCIsXCJzZWN0aW9uXzNfcGlwZWxpbmVfMF9zdWJyZWRkaXRfc2VhcmNoXCI6XCI1XCIsXCJzZWN0aW9uXzNfcGlwZWxpbmVfMV9hdXRob3Jfc2VhcmNoXCI6XCI1XCJ9IiwiZXhwZXJpZW5jZV9zZWxlY3Rpb24iOiJwb3N0X3dpdGhfc2lkZWJhciIsImV4cGVyaWVuY2VfdmVyc2lvbiI6ImRlZmF1bHQiLCJzZWN0aW9uXzJfcGlwZWxpbmVfOF9wb3N0X3NlYXJjaCI6IjcifQ%3D%3D"></faceplate-partial><!-- routable page end --><faceplate-partial name="DataProtectionConsent_qBKqbZ" src="/svc/shreddit/data-protection-consent" loading="eager"></faceplate-partial><faceplate-perfmetric-collector endpoint="/svc/shreddit/perfMetrics">+ <data value="first-contentful-paint"></data> <data value="time-to-first-byte"></data> <data value="largest-contentful-paint"></data> <data value="cumulative-layout-shift"></data>+ </faceplate-perfmetric-collector>+ </shreddit-app>+ <img>+ <navigation-indicator></navigation-indicator>+ </body>+ </html>+ <suspense-execute-deferred-scripts></suspense-execute-deferred-scripts>diff --git a/fixtures/reddit_search_rss_sample.xml b/fixtures/reddit_search_rss_sample.xmldeleted file mode 100644index 982c9cd9..00000000--- a/fixtures/reddit_search_rss_sample.xml+++ /dev/null@@ -1,7 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!-- FIXTURE: captured live from reddit.com/r/Rakuten/top.rss on 2026-05-29; trimmed to 5 entries. Atom shape identical to search.rss. --><feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"><category term="Rakuten" label="r/Rakuten"/><updated>2026-05-29T14:14:32+00:00</updated><icon>https://www.redditstatic.com/icon.png/</icon><id>/r/Rakuten/top.rss?t=month</id><link rel="self" href="https://www.reddit.com/r/Rakuten/top.rss?t=month" type="application/atom+xml" /><link rel="alternate" href="https://www.reddit.com/r/Rakuten/top?t=month" type="text/html" /><subtitle>This is an unofficial subreddit for Rakuten Rewards, the cash back website. We are not affiliated with, endorsed by, or sponsored by Rakuten or any of its subsidiaries.</subtitle><title>top scoring links : Rakuten</title><entry><author><name>/u/InternetUser52</name><uri>https://www.reddit.com/user/InternetUser52</uri></author><category term="Rakuten" label="r/Rakuten"/><content type="html"><!-- SC_OFF --><div class="md"><p>I&#39;m rich!!</p> </div><!-- SC_ON --> &#32; submitted by &#32; <a href="https://www.reddit.com/user/InternetUser52"> /u/InternetUser52 </a> <br/> <span><a href="https://i.redd.it/q8fgmxs29c2h1.jpeg">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/Rakuten/comments/1tiv013/lets_goo_002/">[comments]</a></span></content><id>t3_1tiv013</id><link href="https://www.reddit.com/r/Rakuten/comments/1tiv013/lets_goo_002/" /><updated>2026-05-20T18:48:31+00:00</updated><published>2026-05-20T18:48:31+00:00</published><title>LETS GOO! $0.02!!!</title></entry>-<entry><author><name>/u/Immediate-Duck-6351</name><uri>https://www.reddit.com/user/Immediate-Duck-6351</uri></author><category term="Rakuten" label="r/Rakuten"/><content type="html"><!-- SC_OFF --><div class="md"><p>I don’t travel and I’m buying a house in a few weeks so cash back is amazing 🙌 hoping to keep the pace in the next quarter so I can buy new kitchen appliances lol. </p> </div><!-- SC_ON --> &#32; submitted by &#32; <a href="https://www.reddit.com/user/Immediate-Duck-6351"> /u/Immediate-Duck-6351 </a> <br/> <span><a href="https://i.redd.it/d2a4s0ipvb1h1.jpeg">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/Rakuten/comments/1te1fp8/so_excited/">[comments]</a></span></content><id>t3_1te1fp8</id><link href="https://www.reddit.com/r/Rakuten/comments/1te1fp8/so_excited/" /><updated>2026-05-15T16:29:28+00:00</updated><published>2026-05-15T16:29:28+00:00</published><title>So excited 🥳</title></entry>-<entry><author><name>/u/gnibgnib</name><uri>https://www.reddit.com/user/gnibgnib</uri></author><category term="Rakuten" label="r/Rakuten"/><content type="html"><!-- SC_OFF --><div class="md"><p>128k for the May transfer</p> <p>41k pending for August </p> <p>Got another 9k at Asics not showing but overall pretty happy with Rakuten</p> <p>P2 was able to secure 85k for May transfer</p> </div><!-- SC_ON --> &#32; submitted by &#32; <a href="https://www.reddit.com/user/gnibgnib"> /u/gnibgnib </a> <br/> <span><a href="https://www.reddit.com/gallery/1tb8674">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/Rakuten/comments/1tb8674/had_a_great_run_so_far_this_year_thanks_to_this/">[comments]</a></span></content><id>t3_1tb8674</id><link href="https://www.reddit.com/r/Rakuten/comments/1tb8674/had_a_great_run_so_far_this_year_thanks_to_this/" /><updated>2026-05-12T17:17:19+00:00</updated><published>2026-05-12T17:17:19+00:00</published><title>Had a great run so far this year thanks to this sub!</title></entry>-<entry><author><name>/u/TravelVet93</name><uri>https://www.reddit.com/user/TravelVet93</uri></author><category term="Rakuten" label="r/Rakuten"/><content type="html">&#32; submitted by &#32; <a href="https://www.reddit.com/user/TravelVet93"> /u/TravelVet93 </a> <br/> <span><a href="https://i.redd.it/x6b9whvupb1h1.jpeg">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/Rakuten/comments/1te0hom/my_best_payout_so_far/">[comments]</a></span></content><id>t3_1te0hom</id><link href="https://www.reddit.com/r/Rakuten/comments/1te0hom/my_best_payout_so_far/" /><updated>2026-05-15T15:56:40+00:00</updated><published>2026-05-15T15:56:40+00:00</published><title>My best payout so far</title></entry>-<entry><author><name>/u/Beautiful-Piece-4252</name><uri>https://www.reddit.com/user/Beautiful-Piece-4252</uri></author><category term="Rakuten" label="r/Rakuten"/><content type="html"><!-- SC_OFF --><div class="md"><p>The amount of $$ available in sign up bonuses is amazing. It&#39;s kind of a part time job ensuring Rakuten captures everything, but my August and November payout should be sizeable. I&#39;m new to this and it always seemed like a lot of work for little reward. I know it&#39;s not sustainable, but wow!</p> </div><!-- SC_ON --> &#32; submitted by &#32; <a href="https://www.reddit.com/user/Beautiful-Piece-4252"> /u/Beautiful-Piece-4252 </a> <br/> <span><a href="https://i.redd.it/1vqvajsci42h1.jpeg">[link]</a></span> &#32; <span><a href="https://www.reddit.com/r/Rakuten/comments/1thsnm1/how_can_this_be_real/">[comments]</a></span></content><id>t3_1thsnm1</id><link href="https://www.reddit.com/r/Rakuten/comments/1thsnm1/how_can_this_be_real/" /><updated>2026-05-19T16:46:17+00:00</updated><published>2026-05-19T16:46:17+00:00</published><title>How can this be real?</title></entry>-</feed>diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex cf0d435f..ac500bc8 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -602,7 +602,7 @@ The consented `setup --allow-browser-cookies` run extracts cookies (Chrome/Chrom**Step 4: ScrapeCreators offer (every first run unless the Research Continuation Override already started a waiting topic).** Show this as plain text, then a modal:-ScrapeCreators adds TikTok and Instagram - posts AND top comments - plus YouTube comments, all on by default. 10,000 free calls, no credit card. Your key also backfills Reddit **search** when the free path returns no items (empty-only by default; Reddit comments already come free via shreddit), and backstops YouTube transcripts if yt-dlp gets throttled. (We don't get a cut.) You can widen coverage even further in the next step.+ScrapeCreators adds TikTok and Instagram - posts AND top comments - plus YouTube comments, all on by default. 10,000 free calls, no credit card. Your key also backfills Reddit **search** when the free path returns fewer than 5 items (set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` to backfill only when it finds nothing; Reddit comments already come free via shreddit), and backstops YouTube transcripts if yt-dlp gets throttled. (We don't get a cut.) You can widen coverage even further in the next step.Before the modal, run `which gh` via Bash silently; store as gh_available.@@ -627,7 +627,7 @@ Options:**Step 5: Source opt-in (only if a ScrapeCreators key was saved, not if skipped).** Comments are the DEFAULT, never an opt-in - there is no posts-only tier. Plain text then modal:-Your key is set. On by default: TikTok + Instagram (posts AND top comments), and YouTube comments. Reddit search stays on the free keyless path (with empty-only ScrapeCreators search backup); Reddit comments stay free via shreddit. Want the widest net?+Your key is set. On by default: TikTok + Instagram (posts AND top comments), and YouTube comments. Reddit search stays on the free keyless path (ScrapeCreators backfills search when it returns fewer than 5 items); Reddit comments stay free via shreddit. Want the widest net?**Call AskUserQuestion:**Question: "Which ScrapeCreators sources?"@@ -665,7 +665,7 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**3. Full Disk Access remediation (macOS only).** After `setup`, inspect stderr. If it contains `Permission denied reading Cookies.binarycookies` on macOS, surface: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry only when no research topic is waiting. If a topic is already waiting or the user skips, continue immediately with available sources.-**4. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus optional backups: Reddit search backfill when the free path returns no items (empty-only by default; thin-run / SC-primary are opt-in env knobs — see Reddit backend pin below), and a YouTube transcript fallback when yt-dlp is rate-limited or bot-gated. GitHub signup grants the full 10,000 free calls (more than the web form), and it opens a GitHub authorization page where you enter a short code. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls, ~20-30s) - it opens a browser and you enter a short code. (yes / no)` **Wait for the answer.**+**4. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus optional backups: Reddit search backfill when the free path returns fewer than 5 items (`LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` limits it to empty runs; SC-primary is an opt-in env knob - see Reddit backend pin below), and a YouTube transcript fallback when yt-dlp is rate-limited or bot-gated. GitHub signup grants the full 10,000 free calls (more than the web form), and it opens a GitHub authorization page where you enter a short code. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls, ~20-30s) - it opens a browser and you enter a short code. (yes / no)` **Wait for the answer.**- On **yes** → two commands. FIRST run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-start` in the FOREGROUND - it returns in ~1-2s with a `Your GitHub code: XXXX-XXXX` line plus a JSON blob, copies the code to the clipboard, and opens the browser. Read the `user_code` from that output and immediately tell the user: the code, that it's on their clipboard so they can just paste it (Cmd+V) on the GitHub page - do not make them hunt for it. (If `status == "already_registered"`, stop here - their existing key is active. If the output said the clipboard copy failed, tell them to type the code.) THEN run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll` (background with a 5-min timeout, or foreground) and parse the **LAST** JSON line of its stdout for the final status. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.- On **success but `"persisted": false`** (auth completed yet the key write failed) → do NOT claim sources are active. Tell the user signup worked but saving failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value).- On **`status == "error"` with `message == "Authorized but failed to fetch API key"`** (exact match; often `"reason": "no_api_key"`) → GitHub authorized fine, so do NOT say auth failed. This usually means the GitHub account is already linked to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it, or Skip." Accept a pasted key or offer web/skip.@@ -673,7 +673,7 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI- On **timeout, or any other error** → tell the user it didn't complete and offer to retry or the web signup at scrapecreators.com.- On **no** → note they can run it later by asking to set up ScrapeCreators, then continue.-**4b. Source tier (only if a key was saved).** Comments are the default, never opt-in. Your key runs TikTok + Instagram posts AND top comments, plus YouTube comments. Reddit stays on the free keyless path (empty-only ScrapeCreators search backup; comments via shreddit). Ask whether they want the widest net, e.g.: `Recommended is TikTok + Instagram + all comments (posts and top comments for TikTok/Instagram plus YouTube comments). Or Everything - also Threads + Pinterest (more credits). (recommended / everything)` **Wait for the answer.**+**4b. Source tier (only if a key was saved).** Comments are the default, never opt-in. Your key runs TikTok + Instagram posts AND top comments, plus YouTube comments. Reddit stays on the free keyless path (ScrapeCreators search backfill when it returns fewer than 5 items; comments via shreddit). Ask whether they want the widest net, e.g.: `Recommended is TikTok + Instagram + all comments (posts and top comments for TikTok/Instagram plus YouTube comments). Or Everything - also Threads + Pinterest (more credits). (recommended / everything)` **Wait for the answer.**- On **recommended** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments` to `~/.config/last30days/.env` (include `tiktok,instagram` so they are not treated as excluded). Confirm posts + top comments for TikTok/Instagram/YouTube are on.- On **everything** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest`. Confirm Threads and Pinterest are on too.@@ -744,8 +744,8 @@ The magic of /last30days is Reddit comments + X posts together - and both are fr- **Grok CLI** - run `grok login`, then pin `LAST30DAYS_X_BACKEND=grok` (pin-only; a leftover grok login never auto-steals the X lane). Needs a Grok plan.**Reddit (free, works out of the box):**-- Free keyless discovery (RSS + shreddit listings) gives threads + top comments with upvote counts. No setup required.-- `SCRAPECREATORS_API_KEY=xxx` - optional Reddit search backup when the free path returns **no items** (default). A non-empty free scrape does **not** escalate — set `LAST30DAYS_REDDIT_SC_MIN_ITEMS` or `LAST30DAYS_REDDIT_BACKEND=scrapecreators` if you want paid backfill/primary (see Reddit backend pin).+- Free keyless discovery (Reddit search + shreddit) gives threads + top comments with upvote counts. No setup required.+- `SCRAPECREATORS_API_KEY=xxx` - optional Reddit search backfill when the free path returns **fewer than 5 items** (default floor). A run makes at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set, and a backfill is several API calls (searches plus comment fetches, roughly 10 at default depth). Set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` to backfill only when the free path returns nothing, or `LAST30DAYS_REDDIT_BACKEND=scrapecreators` to make ScrapeCreators primary (see Reddit backend pin).**YouTube (free, open source):**- Run `brew install yt-dlp` (or `pip install yt-dlp`) - enables YouTube search + transcripts.@@ -832,7 +832,7 @@ SKILL_DIR="<absolute path of the directory containing the SKILL.md you just Read**Perplexity source:** use it only when the user asks for Perplexity, Deep Research, or paid grounded synthesis, or when `perplexity` is already enabled in `INCLUDE_SOURCES` / `--search`. Prefer `PERPLEXITY_API_KEY`: normal runs use the controlled Agent API path, `search` returns raw Search API rows, and `both` combines them. Existing `OPENROUTER_API_KEY` installs stay compatible through one synchronous Sonar call; `search` and `both` fall back to Sonar because those direct APIs need a Perplexity key. Every normal mode is capped at one whole-topic planner subquery per command, including competitor fanout, and is not repeated during thin-source retries. With a direct key, normal Agent mode supplies only `web_search`, forces it for citation-critical grounding, uses a bounded step count, and supplies a local instruction. `sonar` remains a deprecated direct-key alias for `agent`. `LAST30DAYS_PERPLEXITY_AGENT_PRESET` is an explicit direct-key choice only; never set it for the user. `--deep-research` requires a normal positional topic. A direct key starts at most one paid `high`-preset background run with a 600-second default wall timeout; OpenRouter preserves the synchronous `perplexity/sonar-deep-research` fallback. It cannot be combined with discovery, drill, cached-only, competitor, or vs-mode. A local timeout does not stop a direct remote run. Report safe model and response metadata, but never expose request headers or raw tool traces.-**Reddit backend pin:** Reddit defaults to the free keyless backend. When `SCRAPECREATORS_API_KEY` is available, ScrapeCreators Reddit **search** backfills only if that free path returns **no items** (empty-only — a thin but non-empty free scrape does not spend credits). If the user wants paid coverage on thin free runs, tell them to set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=<N>` (backfill when free yield is below N). If they say public Reddit is shallow, bot-gated, or missing nested comments, tell them they can set `LAST30DAYS_REDDIT_BACKEND=scrapecreators` alongside `SCRAPECREATORS_API_KEY` to make ScrapeCreators primary and keep the free path as fallback. Do not set either automatically for normal runs.+**Reddit backend pin:** Reddit defaults to the free keyless backend. When `SCRAPECREATORS_API_KEY` is available, ScrapeCreators Reddit **search** backfills when that free path returns **fewer than 5 items** (the default floor; at most one ScrapeCreators Reddit backfill per distinct query, date window, and subreddit set per run; each backfill is several API calls, roughly 10 at default depth). If the user wants to avoid that credit spend, tell them to set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` (backfill only when the free path returns nothing); any other `<N>` backfills when free yield is below N. If they say public Reddit is shallow, bot-gated, or missing nested comments, tell them they can set `LAST30DAYS_REDDIT_BACKEND=scrapecreators` alongside `SCRAPECREATORS_API_KEY` to make ScrapeCreators primary and keep the free path as fallback. Do not set these automatically for normal runs.**Doctor health check:** When the user asks for a health check ("is X working?", "why is a source missing?", "what's broken?", "did setup work?"), run `"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" doctor` (append `--json` for the machine contract) and relay the audit and fix prescriptions. `doctor` renders a **four-state audit** - **WORKING** (verified this run/last run or keyless-always-on), **TURNED ON - UNVERIFIED** (configured/opted-in but no run evidence), **NOT WORKING** (configured but failing, or the last run errored), **COULD BE ON** (available, not yet configured) - one line per source, plus a **CLI-health** block for sources that need a downloaded binary and indented **backup/comment** sub-lanes. Two on-demand modes: `doctor --postmortem` reads the last run's `last-report.json` and reports what actually broke per source (Failed/Partial/Succeeded with fix hints) - reach for it right after a run that returned less than expected; `doctor --probe` runs a **bounded** live test (free HTTP + keyless CLI sources only; credit-gated sources are never probed) to verify WORKING instead of guessing, and the same bounded probe auto-fires on a plain `doctor` when there is no fresh run. Per-source probe deadline is `LAST30DAYS_DOCTOR_PROBE_TIMEOUT` (default 10s). **MANDATORY standing rule.** Before research that depends on login-backed sources (X via cookies, Reddit's ScrapeCreators backfill), consult `doctor --cached --json` — it serves the report cached at `~/.config/last30days/doctor-cache.json` within its TTL (`LAST30DAYS_DOCTOR_TTL` seconds, default 900) for the cost of one file read. Re-run live `doctor` only when the cache is stale or the previous run reported a degraded login-backed source. When X is in ACTIVE_SOURCES_LIST, announce its predicted backend from the report's `sources.x.active_backend` (e.g. "X will use: bird") in the pre-research status line.@@ -2394,7 +2394,7 @@ Want another prompt? Just tell me what you're creating next.## Security & Permissions**What this skill does:**-- Sends search queries to ScrapeCreators API (`api.scrapecreators.com`) for TikTok and Instagram search, and as a Reddit search backup when the free Reddit path returns no items (requires SCRAPECREATORS_API_KEY; empty-only by default — see `LAST30DAYS_REDDIT_SC_MIN_ITEMS` / `LAST30DAYS_REDDIT_BACKEND`)+- Sends search queries to ScrapeCreators API (`api.scrapecreators.com`) for TikTok and Instagram search. With SCRAPECREATORS_API_KEY set, Reddit search queries also go to `api.scrapecreators.com` whenever the free Reddit path returns fewer than 5 items (the default floor; at most one backfill per distinct query, date window, and subreddit set per run, and each backfill is several API calls, roughly 10 at default depth), which spends credits. Set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` to send Reddit queries only when the free path returns nothing (see also `LAST30DAYS_REDDIT_BACKEND`)- Legacy: Sends search queries to OpenAI's Responses API (`api.openai.com`) for Reddit discovery (fallback if no SCRAPECREATORS_API_KEY)- Sends search queries to X/Twitter via the official X API v2 (`api.x.com`, app-only bearer from `X_BEARER_TOKEN`, sent only in the Authorization header; the engine's default X path on a Grok Bot host next to xAI's API), optional user-provided `AUTH_TOKEN`/`CT0` env vars, explicit browser-cookie opt-in (`FROM_BROWSER` or setup consent), xAI's API (`api.x.ai` by default), Xquik's API (`xquik.com` by default), or the official X API v2 via xurl CLI (OAuth2, auto-detected when installed and authenticated)- Accepts a host-provided `--x-posts` envelope (a `.json` file of posts the hosting model fetched through its own X connector) as untrusted input: it replaces the engine's X fetch for that run, every row is validated and its citation URL rebuilt from the post id, and no X backend is called@@ -2418,7 +2418,7 @@ Want another prompt? Just tell me what you're creating next.- Does not log, cache, or write API keys to output files- Endpoint destinations follow configured provider base URLs; `--preflight` reports active and ignored endpoint overrides without printing secrets- Hacker News and Polymarket sources are always available (no API key, no binary dependency)-- TikTok and Instagram sources require SCRAPECREATORS_API_KEY (10,000 free calls, then PAYG). Reddit uses ScrapeCreators search only as a backup when the free path returns no items (default), unless `LAST30DAYS_REDDIT_SC_MIN_ITEMS` or `LAST30DAYS_REDDIT_BACKEND=scrapecreators` is set.+- TikTok and Instagram sources require SCRAPECREATORS_API_KEY (10,000 free calls, then PAYG). With the key set, Reddit spends ScrapeCreators credits on search backfill when the free path returns fewer than 5 items (default); `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` limits that to empty runs, and `LAST30DAYS_REDDIT_BACKEND=scrapecreators` makes ScrapeCreators primary.- Agent hosts invoke the slash-command skill contract; if `--agent` appears in the user's slash-command arguments, treat it as skill-level mode guidance, not a Python CLI flag.**Bundled scripts:** `scripts/last30days.py` (main research engine), `scripts/lib/` (search, enrichment, rendering modules), `scripts/lib/vendor/bird-search/` (vendored X search client, MIT licensed)diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 2b2f3c10..85aa6b9e 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -51,7 +51,7 @@ if os.name == "nt":SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))-from lib import competitors as competitors_mod, corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, registers, render, schema, ui, x_envelope+from lib import competitors as competitors_mod, corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, reddit, registers, render, schema, ui, x_envelope_child_pids: set[int] = set()_child_pids_lock = threading.Lock()@@ -3207,6 +3207,7 @@ def _main(# One memo per command: comparison mode runs pipeline.run per entity in# parallel, so the reset must not live inside the pipeline.http.reset_reddit_keyless_memo()+ reddit.reset_scrapecreators_memo()resolved_corpus_dirs = corpus.resolve_directories(args.corpus, config.get("LAST30DAYS_CORPUS_DIRS"))diff --git a/skills/last30days/scripts/lib/backends.py b/skills/last30days/scripts/lib/backends.pyindex 18aa8567..4a8e553d 100644--- a/skills/last30days/scripts/lib/backends.py+++ b/skills/last30days/scripts/lib/backends.py@@ -21,7 +21,7 @@ Two resolution modes:results fall below the configured thinness floor (see the gating in``lib/pipeline.py``). No probe can pick one winner, so resolution rendershonest conditional wording instead of an ``active_backend``. Reddit's- internal keyless lanes (rss/listing/arctic/shreddit) are sub-probe detail+ internal keyless lanes (search/listing/arctic/shreddit) are sub-probe detailinside the public composite, never chain entries.``active_backend`` semantics: a PREDICTION — "the first backend the probes@@ -456,7 +456,7 @@ def _probe_reddit_public(config: Dict[str, Any]) -> BackendFinding:return BackendFinding(name="public",status=health.OK,- detail="public keyless composite (lanes: rss, listing, arctic, shreddit)",+ detail="public keyless composite (lanes: search, listing, arctic, shreddit)",requires="none (public endpoints)",)@@ -721,15 +721,6 @@ def _resolve_alternative(return res-def _reddit_sc_min_items(config: Dict[str, Any]) -> int:- """The thinness floor, parsed exactly as the pipeline parses it- (lib/pipeline.py reddit fetch: int(... or 0), malformed -> 0)."""- try:- return int(config.get(env.REDDIT_SC_MIN_ITEMS_VAR) or 0)- except (TypeError, ValueError):- return 0--def _resolve_conditional(descriptor: ChainDescriptor,config: Dict[str, Any],@@ -747,7 +738,7 @@ def _resolve_conditional(has_key = bool(config.get("SCRAPECREATORS_API_KEY"))raw_pin = (config.get(descriptor.pin_var) or "").lower() if descriptor.pin_var else ""pinned_sc = has_key and raw_pin == "scrapecreators"- floor = _reddit_sc_min_items(config)+ floor = env.reddit_sc_min_items(config)if pinned_sc:res.pinned = Truediff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex 186ece5a..45009225 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -54,7 +54,7 @@ import urllib.requestfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional-from . import backends, brightdata, env, health, http, prescriptions, x_api+from . import backends, brightdata, env, health, http, prescriptions, reddit_search, x_apifrom .backends import TIER_ERROR, TIER_OK, TIER_WARN# Rollup tiers (R1). ok/warn/error are U2's; only "off" is doctor's own.@@ -1121,10 +1121,12 @@ def _sub_lanes_for(source: str, config: Dict[str, Any]):comments: Optional[Dict[str, Any]] = Nonehas_sc = bool(config.get("SCRAPECREATORS_API_KEY"))if source == "reddit":- backups.append({- "name": "ScrapeCreators backfill", "armed": has_sc,- "note": "fills in when the free public path returns nothing",- })+ floor = env.reddit_sc_min_items(config)+ if floor > 0:+ note = f"fills in when results fall below the {floor}-item floor"+ else:+ note = "fills in when the free public path returns nothing"+ backups.append({"name": "ScrapeCreators backfill", "armed": has_sc, "note": note})elif source == "youtube":backups.append({"name": "ScrapeCreators transcript/search backstop", "armed": has_sc,@@ -1805,11 +1807,10 @@ def _write_cache(report: Dict[str, Any], config: Dict[str, Any]) -> bool:# Free, keyless liveness endpoints (reachability check, tiny payload)._HTTP_PROBE_URLS = {- # The keyless engine's real discovery endpoint (reddit_rss._build_urls).- # /r/all/hot.json is permanently 403 keyless (see the reddit_keyless module- # docstring) and no lane requests it any more, so probing it measured an- # endpoint the engine had already abandoned.- "reddit": "https://www.reddit.com/search.rss?q=test&sort=relevance&t=month",+ # The keyless engine's real discovery endpoint, built by the lane itself so+ # the probe cannot drift from what the engine requests (hand-copied URLs+ # kept certifying endpoints the engine had abandoned).+ "reddit": reddit_search.search_url("test"),"hackernews": "https://hn.algolia.com/api/v1/search?query=test&hitsPerPage=1","polymarket": "https://gamma-api.polymarket.com/events?limit=1","github": "https://api.github.com/rate_limit",@@ -1837,10 +1838,17 @@ _PROBE_RETRY_DELAY_SECONDS = 2.0_PROBE_HEADERS = {"reddit": {"User-Agent": http.BROWSER_USER_AGENT,- "Accept": "application/atom+xml",+ "Accept": "text/html",},}+# Per-source body validators, run on a 2xx: None means the body is the page the+# lane parses, anything else is the reason it is not. Reddit answers a blocked+# keyless client with a 200 challenge page, so status alone reads it as working.+_PROBE_BODY_CHECKS: Dict[str, Callable[[str], Optional[str]]] = {+ "reddit": reddit_search.unrecognized_body,+}+DEFAULT_PROBE_TIMEOUT_SECONDS = 10@@ -1873,6 +1881,7 @@ def _http_ok(*,blocked_statuses: frozenset = frozenset(),headers: Optional[Dict[str, str]] = None,+ body_check: Optional[Callable[[str], Optional[str]]] = None,) -> tuple:"""Reachability check: a 4xx still means the endpoint responded; 5xx or aconnection/timeout error means it did not.@@ -1880,7 +1889,8 @@ def _http_ok(``blocked_statuses`` names the per-source codes that mean "responded, butrefused us" (Reddit's keyless 403/429) — those are a failure, notreachability. ``headers`` overrides the probe identity so a source can be- probed with the same User-Agent its lane sends.+ probed with the same User-Agent its lane sends. ``body_check`` validates+ a 2xx body; a non-None reason fails the probe as blocked."""def _verdict(code: int) -> tuple:return code < 500 and code not in blocked_statuses, f"HTTP {code}"@@ -1890,7 +1900,13 @@ def _http_ok(url, headers=headers or {"User-Agent": "last30days-doctor"})with urllib.request.urlopen(req, timeout=timeout) as resp:- return _verdict(getattr(resp, "status", 200) or 200)+ code = getattr(resp, "status", 200) or 200+ if body_check is not None and code < 300:+ text = resp.read().decode("utf-8", errors="replace")+ reason = body_check(text)+ if reason:+ return False, f"HTTP {code} but blocked: {reason}"+ return _verdict(code)except urllib.error.HTTPError as exc:return _verdict(exc.code)except Exception as exc:@@ -1914,10 +1930,15 @@ def _probe_source(name: str, config: Dict[str, Any], timeout: float) -> Optionalif url:blocked = _PROBE_BLOCKED_STATUSES.get(name, frozenset())headers = _PROBE_HEADERS.get(name)- ok, detail = _http_ok(url, timeout, blocked_statuses=blocked, headers=headers)+ probe_kwargs = {+ "blocked_statuses": blocked,+ "headers": headers,+ "body_check": _PROBE_BODY_CHECKS.get(name),+ }+ ok, detail = _http_ok(url, timeout, **probe_kwargs)if not ok and _transient_probe_detail(name, detail):time.sleep(_PROBE_RETRY_DELAY_SECONDS)- ok, detail = _http_ok(url, timeout, blocked_statuses=blocked, headers=headers)+ ok, detail = _http_ok(url, timeout, **probe_kwargs)if not ok and _transient_probe_detail(name, detail):return {"ok": False,diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex e8ec8908..11293572 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -1211,6 +1211,26 @@ X_OFFICIAL = _X_OFFICIALX_BACKEND_PIN_VAR = 'LAST30DAYS_X_BACKEND'REDDIT_BACKEND_PIN_VAR = 'LAST30DAYS_REDDIT_BACKEND'REDDIT_SC_MIN_ITEMS_VAR = 'LAST30DAYS_REDDIT_SC_MIN_ITEMS'+# Keyed runs backfill Reddit from ScrapeCreators when the free path returns+# fewer than this many items. Thin topics yield 2-3 free results; healthy+# topics many more, so 5 spends credits only where it adds coverage.+REDDIT_SC_MIN_ITEMS_DEFAULT = 5+++def reddit_sc_min_items(config: dict[str, Any]) -> int:+ """The Reddit ScrapeCreators backfill floor, parsed one way for every caller.++ Unset or blank means ``REDDIT_SC_MIN_ITEMS_DEFAULT``; an explicit ``0``+ means backfill only when the free path is empty; a malformed value means+ ``0`` so a typo never spends extra credits. Negative values clamp to 0.+ """+ raw = config.get(REDDIT_SC_MIN_ITEMS_VAR)+ if raw is None or (isinstance(raw, str) and not raw.strip()):+ return REDDIT_SC_MIN_ITEMS_DEFAULT+ try:+ return max(int(raw), 0)+ except (TypeError, ValueError):+ return 0@dataclass(frozen=True)diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.pyindex 21c0a270..f2384137 100644--- a/skills/last30days/scripts/lib/http.py+++ b/skills/last30days/scripts/lib/http.py@@ -15,7 +15,7 @@ from concurrent.futures import Futurefrom contextlib import contextmanagerfrom contextvars import ContextVar, copy_contextfrom pathlib import Path-from typing import Any, Dict, Optional, Union+from typing import Any, Callable, Dict, Optional, Unionfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quotefrom . import health@@ -46,7 +46,7 @@ _EPOCH_RESET_THRESHOLD = 100_000_000.0def retry_delay_from_headers(headers, fallback):"""Seconds to wait after a 429, read from whichever header the host sent.- ``Retry-After`` is the standard, but Reddit's search/RSS endpoints answer an+ ``Retry-After`` is the standard, but Reddit's keyless search endpoints answer ananonymous 429 with ``x-ratelimit-reset`` (seconds until the window rolls) andno ``Retry-After`` at all::@@ -1068,7 +1068,7 @@ def get_text() -> Optional[str]:"""Fetch a URL and return decoded text, or None on any failure.- Keyless helper for Reddit RSS and shreddit HTML endpoints — the free path+ Keyless helper for Reddit site search and shreddit HTML endpoints, the free paththat replaced the now-403 ``.json`` endpoints. Sends a browser User-Agentand never raises: returns None on HTTP error, network failure, or timeoutso tiered callers can fall through to the next source.@@ -1077,7 +1077,7 @@ def get_text(url: Request URLtimeout: HTTP timeout per attempt in secondsretries: Number of retries on failure (kept low — these tiers fail fast)- accept: Accept header value (e.g. "application/atom+xml", "text/html")+ accept: Accept header value (e.g. "text/html")headers: Optional extra headers merged over the defaultsReturns:@@ -1157,10 +1157,10 @@ class RateLimiter:self._waiting -= 1-# Shared across all keyless Reddit tiers (RSS, listing, shreddit) so their+# Shared across all keyless Reddit tiers (site search, listing, shreddit) so their# combined fan-out is throttled as one family. Burst lets the parallel# enrichment workers proceed; sustained rate caps the stampede.-# 1 req/sec is slow enough that home IPs survive RSS + listing + shreddit+# 1 req/sec is slow enough that home IPs survive search + listing + shreddit# fan-out; raise LAST30DAYS_REDDIT_KEYLESS_RATE to trade 429s for wall-clock.REDDIT_KEYLESS_RATE_ENV = "LAST30DAYS_REDDIT_KEYLESS_RATE"DEFAULT_REDDIT_KEYLESS_RATE = 1.0@@ -1218,10 +1218,11 @@ def _sleep_reddit_429_retry() -> None:)-# Run-scoped memo for keyless Reddit GETs. Subreddit listing partials, listing-# RSS feeds, arctic supplements, and shreddit comment pages depend only on the-# subreddit and sort, and the Reddit lane is dispatched with the raw topic for-# every subquery, so a four-subquery run requested each of them four times.+# Run-scoped memo for keyless Reddit GETs. Subreddit listing partials, site+# search pages, arctic supplements, and shreddit comment pages depend only on+# the subreddit, sort, or raw topic, and the Reddit lane is dispatched with the+# raw topic for every subquery, so a four-subquery run requested each of them+# four times.# Memoizing successful bodies for the life of one command turns ~184 requests# into ~50 on the measured 2026-08-31 run shape. Concurrent requesters for the# same URL wait on the first fetch instead of issuing their own (all four@@ -1284,6 +1285,7 @@ def reddit_keyless_get_text(retries: int = 2,accept: str = "*/*",headers: Optional[Dict[str, str]] = None,+ validate: Optional[Callable[[str], Optional[str]]] = None,) -> Optional[str]:"""get_text for the keyless Reddit tiers, memoized per run and throttled.@@ -1292,6 +1294,12 @@ def reddit_keyless_get_text(a limiter token, concurrent requesters for one URL share the in-flightfetch, and cold fetches are spaced via :data:`REDDIT_KEYLESS_LIMITER` so abroad multi-query run does not stampede Reddit's keyless endpoints.++ ``validate`` lets a caller reject a fetched body before it is memoized. It+ returns None for a body the caller recognizes, or a short reason string.+ A rejected body is recorded into the failure sink as schema drift and the+ call returns None, so an HTTP 200 challenge page is neither reported as a+ clean empty result nor served from the memo to later streams."""cached = _reddit_memo_get(url)if cached is not None:@@ -1326,6 +1334,14 @@ def reddit_keyless_get_text(_sync_reddit_keyless_rate()REDDIT_KEYLESS_LIMITER.acquire()text = get_text(url, timeout=timeout, retries=retries, accept=accept, headers=headers)+ if text is not None and validate is not None:+ problem = validate(text)+ if problem:+ _record_failure(HTTPError(+ f"Unrecognized response ({problem}): {url}",+ outcome_state=health.SCHEMA_DRIFT,+ ))+ return Noneif text is not None:_reddit_memo_put(url, text)return text@@ -1340,6 +1356,7 @@ def reddit_keyless_get_text_retry_429(timeout: int = DEFAULT_TIMEOUT,accept: str = "*/*",headers: Optional[Dict[str, str]] = None,+ validate: Optional[Callable[[str], Optional[str]]] = None,) -> tuple[Optional[str], Optional[str]]:"""Limiter-throttled GET with one extra limiter-respecting retry on 429.@@ -1347,7 +1364,8 @@ def reddit_keyless_get_text_retry_429(recovered 429 is not left in the pipeline sink. A second 429, or anynon-429 miss, is recorded as before. Internal ``get_text`` retries areskipped (``retries=1``) so the in-lane retry is the one that re-acquires- the bucket.+ the bucket. ``validate`` is passed through to+ :func:`reddit_keyless_get_text`; a rejected body is a non-429 miss."""# retries=1 on purpose: letting request() sleep out a 42-60s# x-ratelimit-reset inside a lane worker starves the whole batch (the@@ -1360,6 +1378,7 @@ def reddit_keyless_get_text_retry_429("retries": 1,"accept": accept,"headers": headers,+ "validate": validate,}with capture_failures() as first:text = reddit_keyless_get_text(url, **kwargs)diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 15f991eb..d4304b86 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -2,6 +2,7 @@from __future__ import annotations+import contextlibimport copyfrom collections.abc import Iterable, Mappingimport math@@ -4573,13 +4574,18 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:# swallowed sub-requests lost, so doctor can still show it, and# the most specific failure state so a later empty filter result# or the thin-source retry can act on it.+ # Append to any detail the impl already set (e.g. a Reddit+ # backfill note) rather than overwriting it.artifact = dict(artifact or {})- artifact["_source_outcome_detail"] = _summarize_lane_failures(- failures, str(kwargs.get("source") or "")- )+ summary = _summarize_lane_failures(failures, str(kwargs.get("source") or ""))+ prior = artifact.get("_source_outcome_detail")+ artifact["_source_outcome_detail"] = f"{prior}; {summary}" if prior else summary+ states = [f.outcome_state for f in failures]+ if artifact.get("_source_outcome_detail_state"):+ states.append(artifact["_source_outcome_detail_state"])artifact["_source_outcome_detail_state"] = min(- failures, key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9)- ).outcome_state+ states, key=lambda state: _FAILURE_SPECIFICITY.get(state, 9)+ )if module_backed:http.fixture_source_record(fixture_request, [items, artifact])return items, artifact@@ -4757,7 +4763,7 @@ def _retrieve_stream_impl(# env.REDDIT_BACKEND_PIN_VAR=scrapecreators: SC primary, public fallbackprimary_failure: Exception | None = Nonetry:- result = reddit.search_and_enrich(+ result = reddit.search_and_enrich_memo(reddit_query, from_date, to_date, depth=depth,token=config.get("SCRAPECREATORS_API_KEY"),subreddits=subreddits,@@ -4810,13 +4816,10 @@ def _retrieve_stream_impl(return [], {}# Default: public Reddit first (free). ScrapeCreators backfills when the- # free path is empty OR returns fewer than the configured thinness floor- # (env.REDDIT_SC_MIN_ITEMS_VAR, default 0 = empty-only — today's- # behavior, no extra credit spend unless the user opts in).- try:- min_items = int(config.get(env.REDDIT_SC_MIN_ITEMS_VAR) or 0)- except (TypeError, ValueError):- min_items = 0+ # free path returns fewer than the thinness floor (env.reddit_sc_min_items:+ # unset -> env.REDDIT_SC_MIN_ITEMS_DEFAULT, explicit 0 -> empty-only,+ # malformed -> 0 so a typo never spends extra credits).+ min_items = env.reddit_sc_min_items(config)public_results: list[dict] = []public_failure: Exception | None = Nonetry:@@ -4844,12 +4847,23 @@ def _retrieve_stream_impl(f"[Reddit] Free path returned {len(public_results)} "f"(below the {min_items}-item floor); backfilling with ScrapeCreators\n")+ # With free items in hand, scope the backfill's own HTTP failures+ # away from the stream's capture sink: a ScrapeCreators 429 is not a+ # reddit.com rate limit, and a RATE_LIMITED lane state would put+ # 'reddit' in rate_limited_sources and skip later Reddit streams and+ # the thin-source retry. Its failures become the detail note instead.+ # With no free items the backfill IS the source, so failures reach+ # the stream sink as before.+ backfill_scope = (+ http.capture_failures() if public_results else contextlib.nullcontext([])+ )try:- result = reddit.search_and_enrich(- reddit_query, from_date, to_date, depth=depth,- token=config.get("SCRAPECREATORS_API_KEY"),- subreddits=subreddits,- )+ with backfill_scope as backfill_failures:+ result = reddit.search_and_enrich_memo(+ reddit_query, from_date, to_date, depth=depth,+ token=config.get("SCRAPECREATORS_API_KEY"),+ subreddits=subreddits,+ )sc_items = reddit.parse_reddit_response(result)except Exception as exc:sys.stderr.write(@@ -4857,6 +4871,20 @@ def _retrieve_stream_impl(f"({type(exc).__name__}: {exc})\n")state = reddit.classify_run_failure(str(exc))+ if public_results:+ # The free path delivered: Reddit is working. The failed+ # backfill is a detail note, never the source's outcome.+ artifact = {+ "_source_outcome_detail": (+ f"ScrapeCreators backfill failed after "+ f"{len(public_results)} free items: {exc}"+ ),+ }+ if state != health.RATE_LIMITED:+ # A ScrapeCreators rate limit says nothing about+ # reddit.com (and the run memo already stops a retry).+ artifact["_source_outcome_detail_state"] = state+ return public_results, artifactreturn public_results, _outcome_artifact(state,f"Reddit backup failed after {len(public_results)} public items: {exc}",@@ -4869,7 +4897,17 @@ def _retrieve_stream_impl(f"Reddit public search failed; backup returned {len(sc_items)} items: "f"{public_failure}",)- return merged, {}+ trigger = (+ f"below the {min_items}-item floor" if min_items > 0 else "free path empty"+ )+ backfill_detail = (+ f"ScrapeCreators backfill ran ({len(public_results)} free items, "+ f"{trigger}); added {len(merged) - len(public_results)} items"+ )+ if backfill_failures:+ summary = _summarize_lane_failures(backfill_failures, "reddit")+ backfill_detail = f"{backfill_detail}; ScrapeCreators backfill lost {summary}"+ return merged, {"_source_outcome_detail": backfill_detail}if source == "x":if config.get("_x_lane_missing"):# The model declared the connector lane but passed no envelope.diff --git a/skills/last30days/scripts/lib/reddit.py b/skills/last30days/scripts/lib/reddit.pyindex 9476b90e..c662d7df 100644--- a/skills/last30days/scripts/lib/reddit.py+++ b/skills/last30days/scripts/lib/reddit.py@@ -7,9 +7,11 @@ Requires SCRAPECREATORS_API_KEY in config (same key as TikTok + Instagram).API docs: https://scrapecreators.com/docs"""+import copyimport mathimport reimport sys+import threadingimport timefrom collections import Counterfrom concurrent.futures import ThreadPoolExecutor, as_completed, wait as futures_wait@@ -796,6 +798,87 @@ def search_and_enrich(return result+# Run-scoped memo for the paid ScrapeCreators Reddit call (R9). All subquery+# streams share the raw topic, and the thin-source retry repeats it, so without+# this one run could pay for the same query five times. Concurrent callers for+# one key wait on the first call; results AND failures are kept until the+# per-command reset, so a failed backfill is never retried within the run.+_SC_MEMO: Dict[tuple, tuple] = {}+_SC_INFLIGHT: Dict[tuple, threading.Event] = {}+_SC_MEMO_LOCK = threading.Lock()+++def reset_scrapecreators_memo() -> None:+ """Forget memoized ScrapeCreators Reddit calls. Called once per command, and by tests."""+ with _SC_MEMO_LOCK:+ _SC_MEMO.clear()+ _SC_INFLIGHT.clear()+++def _sc_memo_outcome(entry: tuple, replay_failures: bool = True) -> Dict[str, Any]:+ ok, value, failures = entry+ if replay_failures:+ # search_and_enrich swallows ScrapeCreators HTTP errors into the+ # caller's failure sink; a later caller must see them too, or an+ # empty cached result reads as a clean no-results.+ for failure in failures:+ http._record_failure(failure)+ if not ok:+ raise value+ # Each caller gets its own copy so one stream cannot mutate another's items.+ return copy.deepcopy(value)+++def search_and_enrich_memo(+ topic: str,+ from_date: str,+ to_date: str,+ depth: str = "default",+ token: str = None,+ subreddits: List[str] | None = None,+) -> Dict[str, Any]:+ """:func:`search_and_enrich`, at most once per key per command.++ Keyed by query, date window, depth, and sorted subreddits.+ """+ key = (topic, from_date, to_date, depth, tuple(sorted(subreddits or ())))+ while True:+ with _SC_MEMO_LOCK:+ entry = _SC_MEMO.get(key)+ if entry is None:+ gate = _SC_INFLIGHT.get(key)+ owner = gate is None+ if owner:+ gate = threading.Event()+ _SC_INFLIGHT[key] = gate+ if entry is not None:+ return _sc_memo_outcome(entry)+ if owner:+ break+ gate.wait()+ # Loop: read the owner's cached outcome, or re-elect if it was+ # interrupted before caching one (e.g. KeyboardInterrupt).+ try:+ with http.tee_failures() as recorded:+ try:+ result = search_and_enrich(+ topic, from_date, to_date, depth=depth, token=token,+ subreddits=subreddits,+ )+ outcome = (True, result)+ except Exception as exc:+ outcome = (False, exc)+ entry = (*outcome, list(recorded))+ with _SC_MEMO_LOCK:+ _SC_MEMO[key] = entry+ finally:+ with _SC_MEMO_LOCK:+ _SC_INFLIGHT.pop(key, None)+ gate.set()+ # The owner's failures already reached its own sink through tee_failures.+ return _sc_memo_outcome(entry, replay_failures=False)++def parse_reddit_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:"""Parse ScrapeCreators response to item list.diff --git a/skills/last30days/scripts/lib/reddit_arctic.py b/skills/last30days/scripts/lib/reddit_arctic.pyindex 9c2904c3..84837e30 100644--- a/skills/last30days/scripts/lib/reddit_arctic.py+++ b/skills/last30days/scripts/lib/reddit_arctic.py@@ -1,9 +1,9 @@"""Arctic-shift score resolver — post upvote counts by id, keyless and free.-``search.json`` and ``/comments/{id}.json`` are 403 keyless, and ``search.rss``-(used for discovery) carries titles but NO score; the shreddit listing partials-score only posts that appear in a pulled listing. For a thread found only via-global RSS search in a broad sub, the free score comes from arctic-shift+``search.json`` and ``/comments/{id}.json`` are 403 keyless. Site search and the+shreddit listing partials usually carry a score, but some posts still arrive+unscored. For a thread that reaches the merge with score 0, the free score+comes from arctic-shift(https://arctic-shift.photon-reddit.com), a public Reddit archive whose``/api/posts/ids`` returns the post object (score, num_comments, title) for abatch of base36 post ids. Scores are point-in-time snapshots — slightly stale vsdiff --git a/skills/last30days/scripts/lib/reddit_keyless.py b/skills/last30days/scripts/lib/reddit_keyless.pyindex 9b6f75af..7f0a5f9d 100644--- a/skills/last30days/scripts/lib/reddit_keyless.py+++ b/skills/last30days/scripts/lib/reddit_keyless.py@@ -6,9 +6,11 @@ on whatever was discovered:Dedicated lane entity-home subreddits (e.g. r/Kanye) pulled in full via theshreddit listing partials (top+hot+new, real scores), kept- whole — floor-exempt — because the sub IS the topic.- RSS lane reddit_rss breadth (incl. global keyword search) + broad-sub- listing partials for real upvote scores. Relevance-floored.+ whole (floor-exempt) because the sub IS the topic.+ Search lane Reddit's site search fragment (reddit_search): global keyword+ search plus per-sub search for targeted subreddits. Results+ arrive dated and scored. Targeted runs also merge the+ subreddits' listing partials. Relevance-floored.Enrichment shreddit comment + count enrichment (reddit_shreddit) for thetop-ranked posts (author + score + text + permalink).@@ -22,20 +24,17 @@ import sysfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Dict, List, Optional-from collections import Counter-from . import http-from . import reddit_rss, reddit_shreddit, reddit_listing, reddit_arctic-# Scores are backfilled from popular derived subreddits, so an engagement-first-# final sort buries on-topic RSS hits under viral off-topic posts. A relevance-# floor + relevance-first final ranking keeps the section on-topic. Thresholds-# are shared with the keyed path (reddit.py) via relevance.py.+from . import reddit_search, reddit_shreddit, reddit_listing, reddit_arctic+# High-upvote posts from targeted-sub listings can bury on-topic search hits+# under an engagement-first final sort. A relevance floor + relevance-first+# final ranking keeps the section on-topic. Thresholds are shared with the+# keyed path (reddit.py) via relevance.py.from .relevance import RELEVANCE_FLOOR, MIN_ON_TOPICENRICH_LIMITS = reddit_shreddit.ENRICH_LIMITSENRICH_BUDGET = 45 # seconds total across all enrichment threadsMAX_ENRICH_WORKERS = 4-MAX_DERIVED_SUBS = 5 # subreddits derived from RSS results for score backfill# Dedicated subreddits (the entity's home, e.g. r/Kanye for "Kanye West") are# wholly on-topic, so pull top+hot+new — the top-of-month listing alone misses# fresh threads — and keep every item (floor-exempt).@@ -59,12 +58,6 @@ def _log(msg: str) -> None:sys.stderr.flush()-def _top_subreddits(posts: List[Dict[str, Any]], limit: int = MAX_DERIVED_SUBS) -> List[str]:- """Most frequent subreddits across discovered posts (for score backfill)."""- counts = Counter(p.get("subreddit", "") for p in posts if p.get("subreddit"))- return [sub for sub, _ in counts.most_common(limit)]--def _apply_scores(post: Dict[str, Any], scored: Dict[str, int]) -> None:post["score"] = scored["score"]post["num_comments"] = scored["num_comments"]@@ -122,6 +115,8 @@ def _discover(depth: str,subreddits: Optional[List[str]],dedicated_subreddits: Optional[List[str]] = None,+ from_date: Optional[str] = None,+ to_date: Optional[str] = None,) -> List[Dict[str, Any]]:# Dedicated lane: the entity's home subs are wholly on-topic. Pull# top+hot+new (real scores from the listing) and mark them floor-exempt so@@ -135,48 +130,42 @@ def _discover(p["dedicated"] = True_log(f"Dedicated lane: {len(dedicated_posts)} posts from {dedicated_subreddits}")- # search.json is permanently 403/429 keyless (no Tier 0). Discovery is RSS- # breadth (incl. global keyword search) + broad-sub listing partials for- # real upvote scores.- rss_posts = reddit_rss.search_rss(topic, depth=depth, subreddits=subreddits)+ # search.json is permanently 403/429 keyless (no Tier 0). Discovery is+ # Reddit's site search: global, plus per-sub for targeted subreddits. The+ # dedicated subs keep their full-listing lane above and are not searched.+ search_posts = reddit_search.search(+ topic, depth=depth, subreddits=subreddits, from_date=from_date, to_date=to_date+ )- if subreddits:- # Targeted run: the caller chose these subreddits, so their listing cards- # are on-topic — include them as scored discovery AND as a score source.- listing_posts = _scored_listings(subreddits, depth=depth, query=topic)- score_source = listing_posts- else:- # Bare global run: subreddits derived from noisy RSS results are NOT- # reliably on-topic, so their listings are used ONLY to backfill scores- # onto the keyword-matched RSS posts — never merged as discovery, which- # would flood results with high-upvote but irrelevant posts.- listing_posts = []- derived = _top_subreddits(rss_posts)- score_source = _scored_listings(derived, depth=depth, query=topic)+ # Targeted run: the caller chose these subreddits, so their listing cards+ # are on-topic; include them as scored discovery. A bare run fetches no+ # listings, so high-upvote off-topic posts cannot flood the results.+ listing_posts = (+ _scored_listings(subreddits, depth=depth, query=topic) if subreddits else []+ )_log(- f"Tier 1 (RSS) {len(rss_posts)} posts; "- f"{'listing discovery ' + str(len(listing_posts)) if subreddits else 'score-only'}; "- f"{len(score_source)} scored cards"+ f"Tier 1 (site search) {len(search_posts)} posts; "+ f"{'listing discovery ' + str(len(listing_posts)) if subreddits else 'no listings'}")# Score lookup by post id, from the scored listing cards.score_map: Dict[str, Dict[str, int]] = {}- for p in score_source:+ for p in listing_posts:pid = p.get("metadata", {}).get("post_id", "")if pid:score_map[pid] = {"score": p["score"], "num_comments": p["num_comments"]}- # Merge: dedicated-sub posts first (floor-exempt), then scored broad listing- # posts (targeted only), then RSS breadth backfilled with real scores where- # the post appears in a listing. First writer wins the dedupe, so a thread- # in both the dedicated lane and a listing keeps its floor-exempt status.+ # Merge: dedicated-sub posts first (floor-exempt), then scored listing posts+ # (targeted only), then search results, taking a listing's live score where+ # the post also appears there. First writer wins the dedupe, so a thread in+ # both the dedicated lane and a listing keeps its floor-exempt status.merged: List[Dict[str, Any]] = []seen: set = set()for p in dedicated_posts + listing_posts:if p["url"] not in seen:seen.add(p["url"])merged.append(p)- for p in rss_posts:+ for p in search_posts:if p["url"] in seen:continuepid = reddit_listing._post_id(p["url"])@@ -185,9 +174,9 @@ def _discover(seen.add(p["url"])merged.append(p)- # Backfill scores for RSS-only posts (no listing card scored them) from the- # free arctic-shift archive. Posts already scored by a listing keep that- # live score; arctic only fills the gap, and is best-effort (never raises).+ # Backfill posts still at score 0 from the free arctic-shift archive. Posts+ # already scored by search or a listing keep that live score; arctic only+ # fills the gap, and is best-effort (never raises).need = [pid for p in mergedif not (p.get("engagement", {}).get("score"))for pid in [reddit_listing._post_id(p["url"])] if pid]@@ -343,7 +332,9 @@ def search_and_enrich(with top_comments/comment_insights attached on enriched posts.Empty list when all keyless tiers fail (so SC backup can engage)."""- posts = _discover(topic, depth, subreddits, dedicated_subreddits)+ posts = _discover(+ topic, depth, subreddits, dedicated_subreddits, from_date=from_date, to_date=to_date+ )if not posts:return []@@ -355,7 +346,7 @@ def search_and_enrich(# Relevance floor: strip zero-overlap posts (relevance exactly 0 = no# title/body token match at all) when anything relevant remains, so- # backfilled high-upvote posts from popular subs can't bury on-topic RSS+ # high-upvote listing posts can't bury on-topic search# hits. Keep all only when nothing scored above zero.before = len(posts)# Dedicated-sub posts are floor-exempt: their whole subreddit is the topic,diff --git a/skills/last30days/scripts/lib/reddit_listing.py b/skills/last30days/scripts/lib/reddit_listing.pyindex c0f61b97..bc79f1f5 100644--- a/skills/last30days/scripts/lib/reddit_listing.py+++ b/skills/last30days/scripts/lib/reddit_listing.py@@ -3,14 +3,14 @@The subreddit listing partial``/svc/shreddit/community-more-posts/{sort}/?name={sub}[&t={range}]`` servesHTTP 200 with no API key and **server-renders each post's upvote score**, which-neither RSS nor the comments endpoint provides. Each post is a+the comments endpoint does not provide. Each post is a``<shreddit-post>`` element whose start-tag attributes carry ``score``,``comment-count``, ``post-title``, ``permalink``, ``author``, ``subreddit-name``and ``created-timestamp``.This is the keyless source of post-level upvotes. It works for normal users onordinary connections (verified), so reddit_keyless uses it both as a scored-discovery source and to backfill scores onto RSS-discovered posts.+discovery source and to backfill scores onto posts discovered elsewhere."""import html as _html@@ -351,7 +351,7 @@ def fetch_discovery_listings(def score_index(subreddits: List[str], depth: str = "default") -> Dict[str, Dict[str, int]]:"""Build a {post_id: {score, num_comments}} map from subreddit listings.- Used to backfill real scores onto posts discovered via RSS, which carries+ Used to backfill real scores onto posts discovered by a lane that carriesno engagement numbers."""index: Dict[str, Dict[str, int]] = {}diff --git a/skills/last30days/scripts/lib/reddit_public.py b/skills/last30days/scripts/lib/reddit_public.pyindex f4298c4e..48751c2c 100644--- a/skills/last30days/scripts/lib/reddit_public.py+++ b/skills/last30days/scripts/lib/reddit_public.py@@ -4,8 +4,8 @@ Reddit's public ``.json`` endpoints now return HTTP 403 from most contexts(shreddit anti-bot), so this is no longer the primary free path. The keylesspipeline (see reddit_keyless.py) still calls ``search`` as a cheap one-shotTier 0 attempt — a residential machine may occasionally get a 200 — before-falling through to RSS discovery (reddit_rss.py) and shreddit comment-enrichment (reddit_shreddit.py).+falling through to site search discovery (reddit_search.py) and shreddit+comment enrichment (reddit_shreddit.py).``search_reddit_public`` is retained as a compatibility shim that delegates tothe keyless pipeline, so existing callers (pipeline.py) need no change.@@ -247,8 +247,8 @@ def search_reddit_public(Thin compatibility shim over the keyless pipeline: the legacy ``.json``search/enrichment endpoints now return HTTP 403, so this delegates to- ``reddit_keyless.search_and_enrich`` (dedicated-sub listings + RSS discovery- → shreddit comment enrichment; no ``.json`` search). The name and signature+ ``reddit_keyless.search_and_enrich`` (dedicated-sub listings + site search+ discovery → shreddit comment enrichment; no ``.json`` search). The name and signatureare preserved so ``pipeline.py`` and other callers need no change and theScrapeCreators backup still engages when this returns empty.diff --git a/skills/last30days/scripts/lib/reddit_rss.py b/skills/last30days/scripts/lib/reddit_rss.pydeleted file mode 100644index d3876312..00000000--- a/skills/last30days/scripts/lib/reddit_rss.py+++ /dev/null@@ -1,238 +0,0 @@-"""Keyless Reddit discovery via public RSS/Atom feeds.--Reddit's ``.json`` search endpoints now return HTTP 403 (shreddit anti-bot).-RSS feeds still serve HTTP 200 with no API key, so this module uses them for-post discovery, replacing ``reddit_public.search`` as the free search path.--Two feed families are combined and deduped:-- search: /search.rss?q=... and /r/{sub}/search.rss?q=...&restrict_sr=on-- listing: /r/{sub}/{top,hot}.rss?t=month--RSS entries carry no engagement score, so ``score``/``num_comments`` start at 0-and are backfilled during shreddit enrichment (see reddit_shreddit.py). Output-dicts match the normalized shape emitted by ``reddit_public._parse_posts`` so-downstream code (pipeline, renderer) is unaffected.-"""--import sys-import xml.etree.ElementTree as ET-from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError-from datetime import datetime, timezone-from typing import Any, Dict, List, Optional-from urllib.parse import quote_plus--from . import http-from .relevance import token_overlap_relevance--ATOM = "{http://www.w3.org/2005/Atom}"--# Mirror reddit_public depth-aware limits so the two free paths behave alike.-DEPTH_LIMITS = {- "quick": 10,- "default": 25,- "deep": 50,-}--# Listing sorts pulled per subreddit (in addition to search), for volume.-LISTING_SORTS = {- "quick": ["top"],- "default": ["top", "hot"],- "deep": ["top", "hot", "new"],-}--MAX_WORKERS = 4-FEED_TIMEOUT = 15---def _log(msg: str) -> None:- sys.stderr.write(f"[RedditRSS] {msg}\n")- sys.stderr.flush()---def _iso_to_date(value: Optional[str]) -> Optional[str]:- """Parse an ISO-8601 timestamp (e.g. 2026-05-20T18:48:31+00:00) to YYYY-MM-DD."""- if not value:- return None- try:- dt = datetime.fromisoformat(value.strip())- return dt.date().isoformat()- except (ValueError, TypeError):- return None---def _iso_to_epoch(value: Optional[str]) -> Optional[float]:- if not value:- return None- try:- dt = datetime.fromisoformat(value.strip())- if dt.tzinfo is None:- dt = dt.replace(tzinfo=timezone.utc)- return dt.timestamp()- except (ValueError, TypeError):- return None---def _subreddit_from(category: str, url: str) -> str:- """Derive subreddit name from the entry category or, failing that, the URL."""- if category:- return category- # URL form: https://www.reddit.com/r/{sub}/comments/{id}/...- parts = url.split("/r/", 1)- if len(parts) == 2:- return parts[1].split("/", 1)[0]- return ""---def _parse_feed(xml_text: str, query: str = "") -> List[Dict[str, Any]]:- """Parse an Atom feed string into normalized post dicts. Never raises."""- if not xml_text:- return []- try:- root = ET.fromstring(xml_text)- except ET.ParseError as e:- _log(f"feed parse error: {e}")- return []-- posts: List[Dict[str, Any]] = []- for entry in root.iter(f"{ATOM}entry"):- link_el = entry.find(f"{ATOM}link")- url = link_el.get("href", "").strip() if link_el is not None else ""- if not url or "/comments/" not in url:- continue-- title_el = entry.find(f"{ATOM}title")- title = (title_el.text or "").strip() if title_el is not None else ""-- author = ""- author_el = entry.find(f"{ATOM}author/{ATOM}name")- if author_el is not None and author_el.text:- author = author_el.text.strip().removeprefix("/u/").removeprefix("u/")- if author in ("[deleted]", "[removed]", ""):- author = "[deleted]"-- cat_el = entry.find(f"{ATOM}category")- category = cat_el.get("term", "").strip() if cat_el is not None else ""- subreddit = _subreddit_from(category, url)-- updated_el = entry.find(f"{ATOM}updated")- updated = (updated_el.text or "").strip() if updated_el is not None else ""-- content_el = entry.find(f"{ATOM}content")- selftext = ""- if content_el is not None and content_el.text:- # Strip the simplest HTML; renderer only needs an excerpt.- import re as _re- selftext = _re.sub(r"<[^>]+>", " ", content_el.text)- selftext = _re.sub(r"\s+", " ", selftext).strip()[:500]-- relevance = round(token_overlap_relevance(query, title), 3) if query else 0.0-- posts.append({- "id": "", # assigned after dedup- "title": title,- "url": url,- "score": 0, # backfilled by shreddit enrichment- "num_comments": 0, # backfilled by shreddit enrichment- "subreddit": subreddit,- "created_utc": _iso_to_epoch(updated),- "author": author,- "selftext": selftext,- "date": _iso_to_date(updated),- "engagement": {- "score": 0,- "num_comments": 0,- "upvote_ratio": None,- },- "relevance": relevance,- "why_relevant": "Reddit RSS",- "metadata": {},- })-- return posts---def _build_urls(query: str, depth: str, subreddits: Optional[List[str]]) -> List[str]:- """Build the keyless RSS feed URLs to fan out across."""- q = quote_plus(query)- urls: List[str] = [- f"https://www.reddit.com/search.rss?q={q}&sort=relevance&t=month"- ]- for raw_sub in (subreddits or []):- sub = raw_sub.removeprefix("r/").strip()- if not sub:- continue- urls.append(- f"https://www.reddit.com/r/{sub}/search.rss"- f"?q={q}&restrict_sr=on&sort=relevance&t=month"- )- for sort in LISTING_SORTS.get(depth, LISTING_SORTS["default"]):- urls.append(f"https://www.reddit.com/r/{sub}/{sort}.rss?t=month")- return urls---def _fetch_feed(url: str, query: str) -> List[Dict[str, Any]]:- """Fetch and parse one feed. Never raises. One limiter-respecting 429 retry."""- try:- text, _error = http.reddit_keyless_get_text_retry_429(- url, timeout=FEED_TIMEOUT, accept="application/atom+xml"- )- return _parse_feed(text, query) if text else []- except Exception as e: # defensive: a single bad feed must not sink the run- _log(f"feed fetch failed for {url}: {e}")- return []---def _result_timeout(batch_size: int) -> float:- """Per-future wait: the fetch's own timeout plus the bucket's queue depth."""- return FEED_TIMEOUT + 5 + http.reddit_keyless_wait_allowance(batch_size)---def search_rss(- query: str,- depth: str = "default",- subreddits: Optional[List[str]] = None,-) -> List[Dict[str, Any]]:- """Discover Reddit posts for a query via keyless RSS feeds.-- Args:- query: Search query string- depth: 'quick', 'default', or 'deep' — controls result limit and feeds- subreddits: Optional pre-resolved subreddit names (without r/) to target-- Returns:- List of normalized post dicts (deduped by URL, capped by depth),- with placeholder scores to be backfilled during enrichment.- Empty list on any failure.- """- limit = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"])- urls = _build_urls(query, depth, subreddits)-- all_posts: List[Dict[str, Any]] = []- workers = min(MAX_WORKERS, len(urls)) or 1- with ThreadPoolExecutor(max_workers=workers) as executor:- # submit_with_context, not executor.submit: a plain submit starts the- # worker with an empty context, dropping the pipeline's- # capture_failures() sink so a feed's 429/403 is silently discarded and- # the source reports a clean no-results (issue #899).- futures = {- http.submit_with_context(executor, _fetch_feed, url, query): url- for url in urls- }- for future in futures:- try:- all_posts.extend(future.result(timeout=_result_timeout(len(urls))))- except (Exception, FuturesTimeoutError) as e:- _log(f"feed future failed: {e}")-- # Dedupe by URL (first occurrence wins).- seen: set = set()- unique: List[Dict[str, Any]] = []- for post in all_posts:- if post["url"] not in seen:- seen.add(post["url"])- unique.append(post)-- for i, post in enumerate(unique):- post["id"] = f"R{i + 1}"-- return unique[:limit]diff --git a/skills/last30days/scripts/lib/reddit_search.py b/skills/last30days/scripts/lib/reddit_search.pynew file mode 100644index 00000000..fb08aade--- /dev/null+++ b/skills/last30days/scripts/lib/reddit_search.py@@ -0,0 +1,304 @@+"""Keyless Reddit discovery via Reddit's own site search fragment.++``/svc/shreddit/search/?q=...&type=posts`` is the server-rendered HTML the+reddit.com search page loads. It serves HTTP 200 with no API key, and+``/svc/shreddit/r/{sub}/search/`` restricts the same search to one subreddit.+Each post result unit carries:++- a ``<search-telemetry-tracker>`` whose JSON tracking context has+ ``action_info.type == "post"``, the post id, title, and subreddit,+- the post-title link (the canonical permalink),+- a ``<faceplate-timeago ts=...>`` post date,+- a counter row of ``<faceplate-number>`` votes and comments.++So every discovered post arrives dated and scored, with no extra listing fetch.+The next page is a lazy ``<faceplate-partial>`` whose ``src`` carries a+``cursor``. Output dicts match ``reddit_listing.parse_cards`` so downstream+code is unaffected.+"""++import html as _html+import json+import re+import sys+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError+from typing import Any, Dict, List, Optional, Tuple+from urllib.parse import parse_qs, quote, urlencode, urlsplit++from . import http, reddit_listing+from .relevance import token_overlap_relevance++BASE = "https://www.reddit.com"++# Post caps per run by depth.+DEPTH_LIMITS = {"quick": 10, "default": 25, "deep": 50}+# Global search pages per depth (about 7 posts per page).+GLOBAL_PAGE_CAPS = {"quick": 2, "default": 4, "deep": 8}+# Targeted subreddits get one page each.+SUB_PAGE_CAP = 1+MAX_WORKERS = 4+SEARCH_TIMEOUT = 15++# A recognizable page has post result units or Reddit's explicit no-results+# unit. Anything else (challenge page, changed markup) is a lane failure.+RESULTS_MARKER = 'view-events="search/view/post"'+NO_RESULTS_MARKER = 'view-events="search/view/no_results"'++_TRACKER = re.compile(+ r'<search-telemetry-tracker\b[^>]*?\bdata-faceplate-tracking-context="([^"]*)"'+)+_TITLE_HREF = re.compile(+ r'<a\b[^>]*?data-testid="post-title"[^>]*?\bhref="([^"]*)"'+ r'|<a\b[^>]*?\bhref="([^"]*)"[^>]*?data-testid="post-title"'+)+_TIMEAGO = re.compile(r'<faceplate-timeago\b[^>]*?\bts="([^"]+)"')+_COUNTER = re.compile(+ r'<faceplate-number\b[^>]*?\bnumber="(\d+)"[^>]*>\s*</faceplate-number>\s*(vote|comment)'+)+_NEXT_PAGE = re.compile(+ r'<faceplate-partial\b[^>]*?\bsrc="([^"]*/svc/shreddit/[^"]*search/[^"]*)"'+)+++def _log(msg: str) -> None:+ sys.stderr.write(f"[RedditSearch] {msg}\n")+ sys.stderr.flush()+++def unrecognized_body(text: str) -> Optional[str]:+ """Validator for the fetch hook: None for a search page, else a reason."""+ if NO_RESULTS_MARKER in text:+ return None+ if RESULTS_MARKER in text:+ # Marker kept but tracking context changed shape: a clean zero-result+ # parse would hide the drift, so treat it as a lane failure.+ if _post_units(text):+ return None+ return "Reddit search result units no longer parse"+ return "not a Reddit search results page"+++def search_url(+ query: str,+ time_filter: str = "month",+ subreddit: Optional[str] = None,+ cursor: Optional[str] = None,+) -> str:+ """Build a deterministic search URL so concurrent streams share the memo."""+ if subreddit:+ sub = subreddit.strip().removeprefix("r/").strip("/")+ path = f"/svc/shreddit/r/{quote(sub, safe='')}/search/"+ else:+ path = "/svc/shreddit/search/"+ params = [("q", query), ("type", "posts"), ("t", time_filter), ("sort", "relevance")]+ if cursor:+ params.append(("cursor", cursor))+ return f"{BASE}{path}?{urlencode(params)}"+++def _post_units(html_text: str) -> List[Tuple[int, Dict[str, Any]]]:+ """(offset, tracking context) for each post-title tracker, in page order."""+ units = []+ for m in _TRACKER.finditer(html_text):+ try:+ ctx = json.loads(_html.unescape(m.group(1)))+ except (ValueError, TypeError):+ continue+ if not isinstance(ctx, dict):+ continue+ action = ctx.get("action_info")+ post = ctx.get("post")+ # A field that is no longer an object is drift: skip the unit, and a+ # page left with none is flagged by unrecognized_body.+ if not isinstance(action, dict) or not isinstance(post, dict):+ continue+ if action.get("type") == "post" and post.get("id"):+ units.append((m.start(), ctx))+ return units+++def _next_cursor(html_text: str) -> Optional[str]:+ for m in _NEXT_PAGE.finditer(html_text):+ query = urlsplit(_html.unescape(m.group(1))).query+ cursor = (parse_qs(query).get("cursor") or [None])[0]+ if cursor:+ return cursor+ return None+++def parse_page(html_text: str, query: str = "") -> Tuple[List[Dict[str, Any]], Optional[str]]:+ """Parse one search fragment into (normalized posts, next-page cursor)."""+ html_text = html_text or ""+ units = _post_units(html_text)+ posts: List[Dict[str, Any]] = []+ seen: set = set()+ for i, (start, ctx) in enumerate(units):+ post_id = str(ctx["post"]["id"]).removeprefix("t3_")+ if post_id in seen:+ continue+ seen.add(post_id)+ end = units[i + 1][0] if i + 1 < len(units) else len(html_text)+ chunk = html_text[start:end]++ sub_ctx = ctx.get("subreddit")+ subreddit = str(sub_ctx.get("name") or "") if isinstance(sub_ctx, dict) else ""+ title = str(ctx["post"].get("title") or "")+ href_match = _TITLE_HREF.search(chunk)+ href = _html.unescape((href_match.group(1) or href_match.group(2))) if href_match else ""+ href = href.split("?", 1)[0]+ if f"/comments/{post_id}/" in href and href.startswith("/r/"):+ url = f"{BASE}{href}"+ else:+ url = f"{BASE}/r/{subreddit}/comments/{post_id}/"++ ts_match = _TIMEAGO.search(chunk)+ ts = ts_match.group(1) if ts_match else None+ # First counter of each kind wins: this post's own counters precede any+ # that belong to a skipped (malformed) neighbour sharing the chunk.+ counts: Dict[str, int] = {}+ for number, label in _COUNTER.findall(chunk):+ counts.setdefault(label, int(number))+ score, num_comments = counts.get("vote", 0), counts.get("comment", 0)++ posts.append({+ "id": "",+ "title": title,+ "url": url,+ "score": score,+ "num_comments": num_comments,+ "subreddit": subreddit,+ "created_utc": reddit_listing._to_epoch(ts),+ "author": "",+ "selftext": "",+ "date": reddit_listing._to_date(ts),+ "engagement": {+ "score": score,+ "num_comments": num_comments,+ "upvote_ratio": None,+ },+ "relevance": round(token_overlap_relevance(query, title), 3) if query else 0.0,+ "why_relevant": "Reddit search",+ "metadata": {"post_id": post_id},+ })+ return posts, _next_cursor(html_text)+++def _fetch_page(url: str) -> Tuple[Optional[str], Optional[str]]:+ """(body, error). Shared limiter, run memo, one 429 retry, failure sink."""+ try:+ return http.reddit_keyless_get_text_retry_429(+ url,+ timeout=SEARCH_TIMEOUT,+ accept="text/html",+ validate=unrecognized_body,+ )+ except Exception as e: # defensive: one bad page must not sink the run+ _log(f"search fetch failed for {url}: {e}")+ return None, str(e)+++def _search_stream(+ query: str,+ time_filter: str,+ max_pages: int,+ subreddit: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """Page one search sequentially. Keeps earlier pages when a later one fails."""+ label = f"r/{subreddit}" if subreddit else "global"+ posts: List[Dict[str, Any]] = []+ seen_ids: set = set()+ used_cursors: set = set()+ cursor: Optional[str] = None+ for page in range(1, max_pages + 1):+ text, error = _fetch_page(search_url(query, time_filter, subreddit, cursor))+ if text is None:+ _log(f"{label} page {page} failed: {error or 'no response'}")+ break+ page_posts, next_cursor = parse_page(text, query)+ new = [p for p in page_posts if p["metadata"]["post_id"] not in seen_ids]+ for p in new:+ seen_ids.add(p["metadata"]["post_id"])+ posts.extend(new)+ if not new or not next_cursor or next_cursor in used_cursors:+ break+ used_cursors.add(next_cursor)+ cursor = next_cursor+ return posts+++def _result_timeout(batch_size: int, pages: int = 1) -> float:+ """Per-future wait: each sequential page's own timeout plus the bucket's queue."""+ return pages * (SEARCH_TIMEOUT + 5) + http.reddit_keyless_wait_allowance(batch_size)+++def _time_filter(from_date: Optional[str], to_date: Optional[str]) -> str:+ # Same mapping as the ScrapeCreators path; falls back to "month".+ from .reddit import _window_to_time_filter+ return _window_to_time_filter(from_date or "", to_date or "")+++def search(+ query: str,+ depth: str = "default",+ subreddits: Optional[List[str]] = None,+ from_date: Optional[str] = None,+ to_date: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """Discover Reddit posts for a query via the site search fragment.++ Runs a paged global search plus one page of per-subreddit search for each+ targeted subreddit. Returns normalized, dated, scored posts, deduped by URL+ and capped by depth. Streams are interleaved round-robin before the cap so+ neither the targeted subreddits nor the global search crowds out the other. Returns ``[]`` on total failure and never raises; failures+ land in the pipeline's failure sink.+ """+ try:+ limit = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"])+ global_pages = GLOBAL_PAGE_CAPS.get(depth, GLOBAL_PAGE_CAPS["default"])+ time_filter = _time_filter(from_date, to_date)+ subs = []+ for raw in subreddits or []:+ sub = (raw or "").strip().removeprefix("r/").strip("/")+ if sub and sub.lower() not in {s.lower() for s in subs}:+ subs.append(sub)++ jobs = [(sub, SUB_PAGE_CAP) for sub in subs] + [(None, global_pages)]+ batch = sum(pages for _sub, pages in jobs)+ streams: List[List[Dict[str, Any]]] = []+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs))) as executor:+ # submit_with_context, not executor.submit: a plain submit starts the+ # worker with an empty context, dropping the pipeline's+ # capture_failures() sink so a 429/403 or a challenge page is+ # silently discarded (issue #899).+ futures = [+ (http.submit_with_context(executor, _search_stream, query, time_filter, pages, sub), sub, pages)+ for sub, pages in jobs+ ]+ for future, sub, pages in futures:+ try:+ streams.append(future.result(timeout=_result_timeout(batch, pages)))+ except (Exception, FuturesTimeoutError) as e:+ _log(f"{'r/' + sub if sub else 'global'} search future failed: {e}")++ # Round-robin across streams, each in its own relevance order, so the+ # depth cap keeps a share of every stream.+ results = [+ stream[i]+ for i in range(max((len(s) for s in streams), default=0))+ for stream in streams+ if i < len(stream)+ ]+ seen: set = set()+ unique: List[Dict[str, Any]] = []+ for post in results:+ if post["url"] not in seen:+ seen.add(post["url"])+ unique.append(post)+ unique = unique[:limit]+ for i, post in enumerate(unique):+ post["id"] = f"R{i + 1}"+ _log(f"{len(unique)} posts (t={time_filter}, {len(subs)} targeted subs)")+ return unique+ except Exception as e: # defensive: discovery must never raise into the pipeline+ _log(f"search failed: {e}")+ return []diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 5c889613..7ea0b4a1 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -36,7 +36,7 @@ _WELCOME_TEXT = """Welcome to /last30days! I research any topic across Reddit, XI synthesize what people are actually saying right now across social, news, and market sources.Auto setup gives you the core sources free in about 30 seconds:-- Reddit with comments - free keyless discovery (RSS + shreddit), no API key needed.+- Reddit with comments - free keyless discovery (Reddit search + shreddit), no API key needed.- YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars).- Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI.- arXiv (papers) + Techmeme (tech-news) - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics).diff --git a/tests/conftest.py b/tests/conftest.pyindex b9bfba11..35143b44 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -50,12 +50,15 @@ def _reset_probe_caches():@pytest.fixture(autouse=True)def _reset_reddit_keyless_memo():- """The keyless Reddit memo lives for one command; tests are their own commands."""+ """The Reddit run memos (keyless and ScrapeCreators) live for one command; tests are their own commands."""from lib import http as _http+ from lib import reddit as _reddit_http.reset_reddit_keyless_memo()+ _reddit.reset_scrapecreators_memo()yield_http.reset_reddit_keyless_memo()+ _reddit.reset_scrapecreators_memo()@pytest.fixture(autouse=True)diff --git a/tests/test_backend_descriptors.py b/tests/test_backend_descriptors.pyindex acd0a472..65fc1502 100644--- a/tests/test_backend_descriptors.py+++ b/tests/test_backend_descriptors.py@@ -206,7 +206,7 @@ class TestDescriptorRegistry:assert d.mode == backends.MODE_CONDITIONALnames = [s.name for s in d.backends]# Internal keyless lanes are sub-probe detail, never chain entries.- for lane in ("rss", "listing", "arctic", "shreddit"):+ for lane in ("search", "listing", "arctic", "shreddit", "rss"):assert lane not in namesassert names == ["public", "scrapecreators"]@@ -630,16 +630,37 @@ class TestRedditConditional:assert "5" in res.conditionalassert "floor" in res.conditional.lower()- def test_default_floor_zero_means_empty_only_wording(self):+ def test_default_floor_names_five_item_floor(self):res = backends.resolve("reddit", {"SCRAPECREATORS_API_KEY": "dummy-key"})- assert "nothing" in res.conditional.lower()+ low = res.conditional.lower()+ assert "5-item floor" in low+ assert "nothing" not in low++ def test_empty_floor_treated_as_default(self):+ res = backends.resolve(+ "reddit",+ {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_REDDIT_SC_MIN_ITEMS": ""},+ )+ assert "5-item floor" in res.conditional.lower()- def test_malformed_floor_treated_as_default(self):+ def test_explicit_zero_floor_means_empty_only_wording(self):+ res = backends.resolve(+ "reddit",+ {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "0"},+ )+ low = res.conditional.lower()+ assert "nothing" in low+ assert "floor" not in low++ def test_malformed_floor_spends_nothing_extra(self):+ # Malformed parses to 0 (empty-only), matching the pipeline.res = backends.resolve("reddit",{"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "lots"},)- assert "nothing" in res.conditional.lower()+ low = res.conditional.lower()+ assert "nothing" in low+ assert "floor" not in lowdef test_pinned_scrapecreators_renders_pin(self):res = backends.resolve(@@ -674,8 +695,8 @@ class TestRedditConditional:def test_keyless_lanes_are_sub_probe_detail(self):res = backends.resolve("reddit", {})public = next(f for f in res.findings if f.name == "public")- for lane in ("rss", "listing", "arctic", "shreddit"):- assert lane in public.detail+ assert public.detail.endswith("(lanes: search, listing, arctic, shreddit)")+ assert "rss" not in public.detail# ---------------------------------------------------------------------------diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex 768312e4..882b626d 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -71,9 +71,14 @@ def test_reddit_backend_env_var_is_documented_for_users_and_runtime_skill():assert "LAST30DAYS_REDDIT_SC_MIN_ITEMS" in skill_text# Security copy must not claim transport/rate-limit escalation for Reddit search.assert "when public Reddit is unavailable" not in skill_text- assert "backup when the free path returns no items" in skill_text or (- "returns **no items**" in skill_text- )+ # Keyed default: ScrapeCreators backfills below a 5-item floor; 0 opts out.+ assert "fewer than 5 items" in skill_text+ assert "LAST30DAYS_REDDIT_SC_MIN_ITEMS=0" in skill_text+ assert "LAST30DAYS_REDDIT_SC_MIN_ITEMS=0" in config_text+ for text in (skill_text, config_text):+ assert "empty-only" not in text+ assert "returns no items" not in text+ assert "returns **no items**" not in textdef test_save_is_not_documented_as_python_cli_flag():diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex 9c64f7b4..23cb27f0 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -30,7 +30,7 @@ from pathlib import Pathfrom unittest import mockimport last30days as cli-from lib import backends, doctor, env, grok_x, health, http, prescriptions+from lib import backends, doctor, env, grok_x, health, http, prescriptions, reddit_searchBIRD_STATUS_OFF = {"installed": False,@@ -999,11 +999,46 @@ class LiveProbe(unittest.TestCase):self.assertIsNone(doctor._probe_source("tiktok", {}, 5))def test_reddit_probe_targets_the_endpoint_the_engine_uses(self):- # /r/all/hot.json is permanently 403 keyless and no lane requests it;- # probing it certified an endpoint the engine had abandoned (#899).+ # Probing a hand-copied URL certified endpoints the engine had already+ # abandoned (hot.json, then the retired feed). The probe asks the lane.url = doctor._HTTP_PROBE_URLS["reddit"]- self.assertIn("search.rss", url)- self.assertNotIn("hot.json", url)+ self.assertEqual(reddit_search.search_url("test"), url)++ def _probe_reddit_with_body(self, body):+ class _Resp:+ status = 200++ def read(self, *args):+ return body.encode("utf-8")++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ with mock.patch("lib.doctor.urllib.request.urlopen", return_value=_Resp()):+ return doctor._probe_source("reddit", {}, 5)++ def test_reddit_probe_200_with_results_passes(self):+ body = (Path(__file__).resolve().parent.parent / "fixtures" / "reddit_search_page1.html").read_text()+ res = self._probe_reddit_with_body(body)+ self.assertTrue(res["ok"])+ self.assertEqual("HTTP 200", res["detail"])++ def test_reddit_probe_200_no_results_page_passes(self):+ # Reddit's explicit empty page is still the search endpoint answering.+ res = self._probe_reddit_with_body(f"<div {reddit_search.NO_RESULTS_MARKER}></div>")+ self.assertTrue(res["ok"])++ def test_reddit_probe_200_challenge_page_is_blocked(self):+ # A 200 challenge page is the failure the lane hits: status alone+ # would report a blocked Reddit as working.+ res = self._probe_reddit_with_body("<html><title>Please wait for verification</title></html>")+ self.assertFalse(res["ok"])+ self.assertIn("HTTP 200", res["detail"])+ self.assertIn("blocked", res["detail"])+ self.assertFalse(res.get("transient", False))def _probe_reddit_with_status(self, code):error = urllib.error.HTTPError(@@ -1100,11 +1135,13 @@ class LiveProbe(unittest.TestCase):def capture(req, timeout=None):seen["ua"] = req.get_header("User-agent")+ seen["accept"] = req.get_header("Accept")raise urllib.error.HTTPError(req.full_url, 500, "boom", {}, None)with mock.patch("lib.doctor.urllib.request.urlopen", capture):doctor._probe_source("reddit", {}, 5)self.assertEqual(http.BROWSER_USER_AGENT, seen["ua"])+ self.assertIn("text/html", seen["accept"])def test_probe_failure_is_isolated(self):def flaky(name, config, timeout):@@ -1238,6 +1275,19 @@ class BackupAndCommentLanes(unittest.TestCase):text = doctor.render_text(report)self.assertIn("backup: ScrapeCreators transcript/search backstop — armed", text)+ def test_reddit_backup_note_names_the_floor(self):+ report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"})+ note = report["sources"]["reddit"]["backups"][0]["note"]+ self.assertIn("below the 5-item floor", note)++ def test_reddit_backup_note_floor_off_means_empty_only(self):+ report = _build({+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ env.REDDIT_SC_MIN_ITEMS_VAR: "0",+ })+ note = report["sources"]["reddit"]["backups"][0]["note"]+ self.assertIn("returns nothing", note)+def test_backups_off_without_sc_key(self):report = _build({})self.assertFalse(report["sources"]["reddit"]["backups"][0]["armed"])diff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.pyindex 1f57fa95..1ae7ef55 100644--- a/tests/test_onboarding_contract.py+++ b/tests/test_onboarding_contract.py@@ -281,16 +281,20 @@ class TestOnboardingContract(unittest.TestCase):def test_offer_copy_names_comments_and_auto_enrichment(self):"""The Step 4 offer states comments are part of the default value and- describes the key's real Reddit/YouTube roles (empty-path Reddit- search backfill + yt-dlp transcript backstop) — not rate-limit+ describes the key's real Reddit/YouTube roles (Reddit search backfill+ below the 5-item floor + yt-dlp transcript backstop), not rate-limitescalation or SC Reddit comment enrichment on the free path."""before = self._modal_before_step5()self.assertIn("comments", before.lower())self.assertIn("Reddit", before)self.assertIn("YouTube", before)self.assertIn("10,000 free calls", before)- # Empty-only search backup (not transport/rate-limit escalation).- self.assertIn("returns no items", before)+ # Floor-triggered search backfill with the 0 opt-out (not+ # transport/rate-limit escalation, and no longer empty-only).+ self.assertIn("fewer than 5 items", before)+ self.assertIn("LAST30DAYS_REDDIT_SC_MIN_ITEMS=0", before)+ self.assertNotIn("returns no items", before)+ self.assertNotIn("empty-only", before)self.assertNotIn("when they hit rate limits", before)# Free-path comments are shreddit; do not claim SC comment preference.self.assertNotIn("prefers ScrapeCreators for Reddit", before)@@ -301,7 +305,8 @@ class TestOnboardingContract(unittest.TestCase):step5 = self._modal_step5()self.assertNotIn("public + ScrapeCreators", step5)self.assertNotIn("Reddit auto-enrichment", step5)- self.assertIn("empty-only", step5)+ self.assertIn("fewer than 5 items", step5)+ self.assertNotIn("empty-only", step5)def test_recommended_tier_writes_comments_by_default(self):"""Comments are the DEFAULT: the recommended option enables YouTube +diff --git a/tests/test_reddit_dedicated.py b/tests/test_reddit_dedicated.pyindex b649ff7c..d62556d9 100644--- a/tests/test_reddit_dedicated.py+++ b/tests/test_reddit_dedicated.py@@ -16,7 +16,7 @@ def _post(i, date="2026-05-20", rel=0.0):"id": "", "title": f"Post {i}", "url": url, "score": 0, "num_comments": 0,"subreddit": "test", "created_utc": None, "author": "u", "selftext": "","date": date, "engagement": {"score": 0, "num_comments": 0, "upvote_ratio": None},- "relevance": rel, "why_relevant": "Reddit RSS", "metadata": {},+ "relevance": rel, "why_relevant": "Reddit search", "metadata": {},}@@ -54,9 +54,12 @@ class TestDedicatedLane:side_effect=fake_fetch), \mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings",return_value=[]), \- mock.patch.object(reddit_keyless.reddit_rss, "search_rss", return_value=[]):+ mock.patch.object(reddit_keyless.reddit_search, "search",+ return_value=[]) as search:out = reddit_keyless._discover("Kanye West", "default", None,dedicated_subreddits=["Kanye"])+ # Dedicated subs keep their full-listing lane; no per-sub search for them.+ assert search.call_args.kwargs["subreddits"] is Noneassert captured["sorts"] == ["top", "hot", "new"]assert captured["subs"] == ["Kanye"]assert len(out) == 1@@ -88,7 +91,7 @@ class TestDedicatedLane:with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",side_effect=fake_fetch), \- mock.patch.object(reddit_keyless.reddit_rss, "search_rss", return_value=[]):+ mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]):out = reddit_keyless._discover("Kanye West", "default", ["hiphopheads"],dedicated_subreddits=["Kanye"])same = [p for p in out if p["url"] == shared_ded["url"]]@@ -96,7 +99,7 @@ class TestDedicatedLane:assert same[0].get("dedicated") is Truedef test_no_dedicated_subs_is_noop(self):- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss",+ with mock.patch.object(reddit_keyless.reddit_search, "search",return_value=[_post(1)]), \mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",return_value=[]):diff --git a/tests/test_reddit_dispatch.py b/tests/test_reddit_dispatch.pyindex 50522ca1..8e6f674a 100644--- a/tests/test_reddit_dispatch.py+++ b/tests/test_reddit_dispatch.py@@ -5,7 +5,7 @@ from unittest import mockfrom pathlib import Path-from lib import env, pipeline, reddit_keyless, schema+from lib import env, health, http, pipeline, reddit_keyless, schemadef _subquery():@@ -28,71 +28,205 @@ def _ids(items):class TestThinnessFloor:KEY = {"SCRAPECREATORS_API_KEY": "k"}+ FLOOR = env.REDDIT_SC_MIN_ITEMS_VARdef _run(self, config, public, sc_parsed):with mock.patch("lib.reddit_public.search_reddit_public", return_value=public), \mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}) as sc, \mock.patch("lib.reddit.parse_reddit_response", return_value=sc_parsed):- items, _ = pipeline._retrieve_stream(- topic="kanye", subquery=_subquery(), source="reddit", config=config,- depth="quick", date_range=("2026-05-26", "2026-06-25"),- runtime=_runtime(), mock=False,- )+ items, _ = _stream(config)return items, sc- def test_default_zero_does_not_call_sc_when_free_has_items(self):- # min_items unset (0): today's empty-only behavior — free wins, no SC.- items, sc = self._run(self.KEY, [_item("a"), _item("b"), _item("c")], [_item("z")])- assert len(items) == 3+ def test_unset_floor_backfills_thin_free_run_free_first(self):+ # Default floor is 5: 3 free items < 5 -> one SC call, free first.+ free = [_item("a"), _item("b"), _item("c")]+ items, sc = self._run(self.KEY, free, [_item("b"), _item("z")])+ sc.assert_called_once()+ assert _ids(items) == ["a", "b", "c", "z"]++ def test_unset_floor_six_free_items_spends_nothing(self):+ free = [_item(c) for c in "abcdef"]+ items, sc = self._run(self.KEY, free, [_item("z")])sc.assert_not_called()+ assert len(items) == 6- def test_default_empty_free_falls_to_sc(self):- items, sc = self._run(self.KEY, [], [_item("z")])- assert _ids(items) == ["z"]- sc.assert_called_once()+ def test_exactly_default_floor_is_acceptable(self):+ free = [_item(c) for c in "abcde"]+ items, sc = self._run(self.KEY, free, [_item("z")])+ sc.assert_not_called()+ assert len(items) == 5- def test_threshold_fires_on_thin_run_and_merges_deduped(self):- cfg = {**self.KEY, "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "5"}- free = [_item("a"), _item("b")] # 2 < 5 -> backfill- sc_parsed = [_item("b"), _item("c")] # overlaps "b"- items, sc = self._run(cfg, free, sc_parsed)+ def test_empty_string_floor_behaves_as_unset(self):+ cfg = {**self.KEY, self.FLOOR: ""}+ items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")])sc.assert_called_once()- assert _ids(items) == ["a", "b", "c"] # free first, dedup b, append c+ assert _ids(items) == ["a", "b", "c", "z"]- def test_threshold_not_fired_when_free_above_floor(self):- cfg = {**self.KEY, "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "2"}+ def test_explicit_zero_is_empty_only(self):+ cfg = {**self.KEY, self.FLOOR: "0"}items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")])sc.assert_not_called()assert len(items) == 3- def test_exactly_floor_is_acceptable_no_backfill(self):- # MIN_ITEMS=N means N results are acceptable; only fewer than N backfills.- cfg = {**self.KEY, "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "3"}+ def test_explicit_zero_still_backfills_empty_free_run(self):+ cfg = {**self.KEY, self.FLOOR: "0"}+ items, sc = self._run(cfg, [], [_item("z")])+ sc.assert_called_once()+ assert _ids(items) == ["z"]++ def test_threshold_not_fired_when_free_above_floor(self):+ cfg = {**self.KEY, self.FLOOR: "2"}items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")])sc.assert_not_called()assert len(items) == 3def test_no_key_never_calls_sc(self):- items, sc = self._run({"LAST30DAYS_REDDIT_SC_MIN_ITEMS": "5"}, [_item("a")], [_item("z")])+ for floor in (None, "", "0", "5", "junk"):+ cfg = {} if floor is None else {self.FLOOR: floor}+ items, sc = self._run(cfg, [_item("a")], [_item("z")])+ sc.assert_not_called()+ assert len(items) == 1++ def test_malformed_floor_spends_nothing(self):+ # Malformed means 0 (empty-only): 3 free items -> no SC call.+ cfg = {**self.KEY, self.FLOOR: "not-an-int"}+ items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")])sc.assert_not_called()- assert len(items) == 1+ assert len(items) == 3- def test_bad_threshold_value_defaults_to_empty_only(self):- cfg = {**self.KEY, "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "not-an-int"}- items, sc = self._run(cfg, [_item("a")], [_item("z")])- sc.assert_not_called() # falls back to 0 -> free (1 item) wins- assert len(items) == 1- def test_sc_failure_degrades_to_free(self):- cfg = {**self.KEY, "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "5"}- with mock.patch("lib.reddit_public.search_reddit_public", return_value=[_item("a")]), \+def _stream(config):+ return pipeline._retrieve_stream(+ topic="kanye", subquery=_subquery(), source="reddit", config=config,+ depth="quick", date_range=("2026-05-26", "2026-06-25"),+ runtime=_runtime(), mock=False,+ )+++def _sc_402(*_args, **_kwargs):+ # Mirrors the real transport: http records the failure in the run's+ # capture sink, then raises.+ http._raise(http.HTTPError("HTTP 402: Payment Required", status_code=402))+++class TestBackfillOutcome:+ KEY = {"SCRAPECREATORS_API_KEY": "k"}++ def test_backfill_402_after_free_items_keeps_source_working(self):+ free = [_item("a"), _item("b"), _item("c")]+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \+ mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_402):+ items, artifact = _stream(self.KEY)+ assert _ids(items) == ["a", "b", "c"]+ assert not artifact.get("_source_outcome") # not branded failed+ detail = artifact.get("_source_outcome_detail") or ""+ assert "402" in detail+ assert "ScrapeCreators backfill failed" in detail+ assert artifact.get("_source_outcome_detail_state") == health.PAYMENT_REQUIRED++ def test_backfill_generic_failure_after_free_items_is_detail(self):+ free = [_item("a")]+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \mock.patch("lib.reddit.search_and_enrich", side_effect=Exception("down")):- items, _ = pipeline._retrieve_stream(- topic="kanye", subquery=_subquery(), source="reddit", config=cfg,- depth="quick", date_range=("2026-05-26", "2026-06-25"),- runtime=_runtime(), mock=False,- )- assert _ids(items) == ["a"] # backup failed -> keep the free items+ items, artifact = _stream(self.KEY)+ assert _ids(items) == ["a"]+ assert not artifact.get("_source_outcome")+ assert "down" in (artifact.get("_source_outcome_detail") or "")++ def test_backfill_failure_with_no_free_items_keeps_explicit_failure(self):+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]), \+ mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_402):+ items, artifact = _stream(self.KEY)+ assert items == []+ outcome = artifact.get("_source_outcome") or {}+ assert outcome.get("state") == health.PAYMENT_REQUIRED++ def test_backfill_note_and_swallowed_keyless_403_both_survive(self):+ free = [_item("a"), _item("b"), _item("c")]++ def _public(*_args, **_kwargs):+ # A keyless lane swallowed a 403 but the source still delivered.+ http._record_failure(http.HTTPError("HTTP 403: Blocked", status_code=403))+ return free++ with mock.patch("lib.reddit_public.search_reddit_public", side_effect=_public), \+ mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}), \+ mock.patch("lib.reddit.parse_reddit_response", return_value=[_item("z")]):+ items, artifact = _stream(self.KEY)+ assert _ids(items) == ["a", "b", "c", "z"]+ assert not artifact.get("_source_outcome")+ detail = artifact.get("_source_outcome_detail") or ""+ assert "ScrapeCreators backfill ran" in detail+ assert "1 sub-request blocked (HTTP 403)" in detail++ def test_backfill_that_ran_is_noted(self):+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=[_item("a")]), \+ mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}), \+ mock.patch("lib.reddit.parse_reddit_response",+ return_value=[_item("a"), _item("z")]):+ items, artifact = _stream(self.KEY)+ assert _ids(items) == ["a", "z"]+ assert not artifact.get("_source_outcome")+ detail = artifact.get("_source_outcome_detail") or ""+ assert "ScrapeCreators backfill ran" in detail+ assert "added 1" in detail++ def test_swallowed_sc_429_after_free_items_does_not_rate_limit_reddit(self):+ # ScrapeCreators 429s inside the backfill are swallowed by lib.reddit+ # (recorded in the capture sink, then []). reddit.com was never+ # rate-limited, so the stream must not carry RATE_LIMITED: the fan-out+ # would add 'reddit' to rate_limited_sources and skip later Reddit+ # streams and the thin-source retry.+ free = [_item("a"), _item("b"), _item("c")]++ def _sc_http_429(*_args, **_kwargs):+ http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429))++ with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \+ mock.patch("lib.http.get", side_effect=_sc_http_429) as sc_get:+ items, artifact = _stream(self.KEY)+ assert sc_get.called+ assert _ids(items) == ["a", "b", "c"]+ assert not artifact.get("_source_outcome")+ assert artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED+ detail = artifact.get("_source_outcome_detail") or ""+ assert "ScrapeCreators backfill" in detail+ assert "HTTP 429" in detail++ def test_raised_sc_429_after_free_items_does_not_rate_limit_reddit(self):+ free = [_item("a"), _item("b"), _item("c")]++ def _sc_raise_429(*_args, **_kwargs):+ http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429))++ with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \+ mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_raise_429):+ items, artifact = _stream(self.KEY)+ assert _ids(items) == ["a", "b", "c"]+ assert not artifact.get("_source_outcome")+ assert artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED+ detail = artifact.get("_source_outcome_detail") or ""+ assert "ScrapeCreators backfill failed" in detail+ assert "429" in detail++ def test_sc_429_with_no_free_items_keeps_explicit_rate_limited_outcome(self):+ def _sc_raise_429(*_args, **_kwargs):+ http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429))++ with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]), \+ mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_raise_429):+ items, artifact = _stream(self.KEY)+ assert items == []+ outcome = artifact.get("_source_outcome") or {}+ assert outcome.get("state") == health.RATE_LIMITED++ def test_no_backfill_no_note(self):+ free = [_item(c) for c in "abcdef"]+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \+ mock.patch("lib.reddit.search_and_enrich") as sc:+ _items, artifact = _stream(self.KEY)+ sc.assert_not_called()+ assert not artifact.get("_source_outcome_detail")class TestMergeHelper:@@ -105,7 +239,7 @@ class TestNoSearchJson:def test_keyless_discovery_never_calls_searchjson(self):# reddit_public.search (the .json caller) must never run in the keyless flow.with mock.patch("lib.reddit_public.search") as json_search, \- mock.patch("lib.reddit_keyless.reddit_rss.search_rss", return_value=[]), \+ mock.patch("lib.reddit_keyless.reddit_search.search", return_value=[]), \mock.patch("lib.reddit_keyless.reddit_listing.fetch_listings", return_value=[]):reddit_keyless._discover("topic", "default", ["test"])json_search.assert_not_called()diff --git a/tests/test_reddit_keyless.py b/tests/test_reddit_keyless.pyindex 2ba1446b..1b6e8068 100644--- a/tests/test_reddit_keyless.py+++ b/tests/test_reddit_keyless.py@@ -1,4 +1,4 @@-"""Tests for scripts/lib/reddit_keyless.py — tiered keyless Reddit pipeline."""+"""Tests for scripts/lib/reddit_keyless.py: tiered keyless Reddit pipeline."""from unittest import mock@@ -11,7 +11,7 @@ def _post(i, date="2026-05-20", rel=0.0):"id": "", "title": f"Post {i}", "url": url, "score": 0, "num_comments": 0,"subreddit": "test", "created_utc": None, "author": "u", "selftext": "","date": date, "engagement": {"score": 0, "num_comments": 0, "upvote_ratio": None},- "relevance": rel, "why_relevant": "Reddit RSS", "metadata": {},+ "relevance": rel, "why_relevant": "Reddit search", "metadata": {},}@@ -26,72 +26,122 @@ def _scored(i, score, ncmt=0):return p-class TestDiscovery:- """RSS breadth + scored listings are the keyless discovery path (no .json)."""+def _searched(i, score, ncmt=0, rel=0.5):+ """A site-search result: dated and scored straight from the search page."""+ p = _scored(i, score, ncmt)+ p["relevance"] = rel+ p["why_relevant"] = "Reddit search"+ return p+++def _lanes(search=(), listing=(), arctic_listing=(), arctic_scores=None):+ """Patch every discovery lane at its module boundary; return the mocks."""+ return (+ mock.patch.object(reddit_keyless.reddit_search, "search", return_value=list(search)),+ mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",+ return_value=list(listing)),+ mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings",+ return_value=list(arctic_listing)),+ mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores",+ return_value=dict(arctic_scores or {})),+ )- def test_keyless_path_runs_rss_and_listings(self):- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss",- return_value=[_post(1), _post(2)]) as rss, \- mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",- return_value=[]), \- mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings",- return_value=[]):- out = reddit_keyless._discover("topic", "default", ["test"])- assert len(out) == 2- rss.assert_called_once()- def test_listing_scores_backfill_rss_posts(self):- # RSS finds post 1 (no score); listing card for post 1 carries the score.- rss_post = _post(1)+class TestDiscovery:+ """Reddit site search + scored listings are the keyless discovery path."""++ def test_bare_run_returns_search_posts_without_listing_requests(self):+ hits = [_searched(1, score=412, ncmt=38), _searched(2, score=77, ncmt=5)]+ p_search, p_listing, p_arctic_listing, p_scores = _lanes(search=hits)+ with p_search as search, p_listing as listing, \+ p_arctic_listing as arctic_listing, p_scores as scores:+ out = reddit_keyless._discover("topic", "default", None)+ search.assert_called_once()+ assert search.call_args.kwargs["subreddits"] is None+ listing.assert_not_called()+ arctic_listing.assert_not_called()+ scores.assert_not_called() # real scores, nothing to backfill+ assert [p["url"] for p in out] == [h["url"] for h in hits]+ assert [p["engagement"]["score"] for p in out] == [412, 77]+ assert [p["num_comments"] for p in out] == [38, 5]++ def test_targeted_run_merges_search_and_listing_first_writer_wins(self):listing_post = _scored(1, score=52692, ncmt=1743)- listing_post["subreddit"] = "test" # Match the requested subreddit.- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss",- return_value=[rss_post]), \- mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",- return_value=[listing_post]), \- mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings",- return_value=[]): # No arctic supplement.+ listing_only = _scored(2, score=10)+ search_dup = _searched(1, score=50000, ncmt=1700) # same url as listing_post+ search_only = _searched(3, score=9)+ p_search, p_listing, p_arctic_listing, p_scores = _lanes(+ search=[search_dup, search_only], listing=[listing_post, listing_only])+ with p_search as search, p_listing as listing, p_arctic_listing, p_scores:out = reddit_keyless._discover("topic", "default", ["test"])- # listing post (scored) is kept; RSS dup of same url is dropped- assert len(out) == 1+ assert search.call_args.kwargs["subreddits"] == ["test"]+ assert listing.call_args.args[0] == ["test"]+ urls = [p["url"] for p in out]+ assert urls == [listing_post["url"], listing_only["url"], search_only["url"]]+ assert out[0]["why_relevant"] == "Reddit listing" # one copy, listing keptassert out[0]["engagement"]["score"] == 52692- assert out[0]["num_comments"] == 1743- def test_scores_flow_to_distinct_rss_posts(self):- # Distinct RSS post whose id matches a listing card gets backfilled.- rss_post = _post(7) # url .../000007/...+ def test_targeted_listing_score_fills_distinct_search_post(self):+ # A search post whose id matches a listing card under another url takes+ # the listing's live score.+ search_post = _searched(7, score=0)listing_post = _scored(7, score=999)listing_post["url"] = "https://www.reddit.com/r/test/comments/zzzzzz/other/"- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss",- return_value=[rss_post]), \- mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",- return_value=[listing_post]):+ p_search, p_listing, p_arctic_listing, p_scores = _lanes(+ search=[search_post], listing=[listing_post])+ with p_search, p_listing, p_arctic_listing, p_scores:out = reddit_keyless._discover("topic", "default", ["test"])- backfilled = [p for p in out if p["url"] == rss_post["url"]][0]- assert backfilled["engagement"]["score"] == 999+ filled = [p for p in out if p["url"] == search_post["url"]][0]+ assert filled["engagement"]["score"] == 999++ def test_zero_score_search_post_gets_arctic_fill(self):+ unscored = _searched(4, score=0)+ scored = _searched(5, score=120, ncmt=3)+ p_search, p_listing, p_arctic_listing, p_scores = _lanes(+ search=[unscored, scored],+ arctic_scores={"000004": {"score": 31, "num_comments": 6}})+ with p_search, p_listing, p_arctic_listing, p_scores as scores:+ out = reddit_keyless._discover("topic", "default", None)+ scores.assert_called_once_with(["000004"])+ by_url = {p["url"]: p for p in out}+ assert by_url[unscored["url"]]["engagement"]["score"] == 31+ assert by_url[unscored["url"]]["num_comments"] == 6+ assert by_url[scored["url"]]["engagement"]["score"] == 120def test_bare_query_does_not_merge_listing_discovery(self):- # No subreddits provided: derived-subreddit listings must NOT be added as- # results (avoids flooding with off-topic high-upvote posts) — only used- # to backfill scores onto the keyword-matched RSS posts.- rss_post = _post(1) # on-topic keyword match- offtopic_listing = _scored(99, score=88888) # high score, unrelated sub+ # No subreddits provided: no listing is fetched, so high-upvote+ # off-topic listing posts can never flood the keyword-matched results.+ on_topic = _searched(1, score=15)+ offtopic_listing = _scored(99, score=88888)offtopic_listing["url"] = "https://www.reddit.com/r/random/comments/zzz999/x/"- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss",- return_value=[rss_post]), \- mock.patch.object(reddit_keyless, "_top_subreddits", return_value=["random"]), \- mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",- return_value=[offtopic_listing]):+ p_search, p_listing, p_arctic_listing, p_scores = _lanes(+ search=[on_topic], listing=[offtopic_listing], arctic_listing=[offtopic_listing])+ with p_search, p_listing as listing, p_arctic_listing as arctic_listing, p_scores:out = reddit_keyless._discover("topic", "default", None)urls = [p["url"] for p in out]- assert rss_post["url"] in urls- assert offtopic_listing["url"] not in urls # not merged as discovery+ assert urls == [on_topic["url"]]+ listing.assert_not_called()+ arctic_listing.assert_not_called()def test_discover_never_raises_returns_empty(self):- with mock.patch.object(reddit_keyless.reddit_rss, "search_rss", return_value=[]), \- mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=[]):+ p_search, p_listing, p_arctic_listing, p_scores = _lanes()+ with p_search, p_listing, p_arctic_listing, p_scores:assert reddit_keyless._discover("t", "default", None) == []+ def test_empty_search_makes_keyless_path_return_empty(self):+ p_search, p_listing, p_arctic_listing, p_scores = _lanes()+ with p_search, p_listing, p_arctic_listing, p_scores:+ assert reddit_keyless.search_and_enrich("t", "2026-05-01", "2026-05-31") == []++ def test_search_window_follows_lookback(self):+ p_search, p_listing, p_arctic_listing, p_scores = _lanes()+ with p_search as search, p_listing, p_arctic_listing, p_scores:+ reddit_keyless.search_and_enrich("t", "2026-05-24", "2026-05-31", depth="quick")+ kwargs = search.call_args.kwargs+ assert kwargs["from_date"] == "2026-05-24"+ assert kwargs["to_date"] == "2026-05-31"+ assert kwargs["depth"] == "quick"+class TestSearchAndEnrich:"""Full pipeline: discover -> date filter -> rank -> enrich -> reindex."""diff --git a/tests/test_reddit_keyless_backoff.py b/tests/test_reddit_keyless_backoff.pyindex a8006da1..a41fc9cb 100644--- a/tests/test_reddit_keyless_backoff.py+++ b/tests/test_reddit_keyless_backoff.py@@ -3,7 +3,7 @@import osfrom unittest import mock-from lib import http, reddit_listing, reddit_rss, render, schema+from lib import http, reddit_listing, render, schemaclass TestRateLimiter:@@ -44,17 +44,11 @@ class TestRedditKeylessGetText:def test_acquires_limiter_then_delegates(self):with mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire") as acq, \mock.patch.object(http, "get_text", return_value="body") as gt:- out = http.reddit_keyless_get_text("https://www.reddit.com/x.rss", accept="application/atom+xml")+ out = http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=x", accept="text/html")assert out == "body"acq.assert_called_once()gt.assert_called_once()- def test_reddit_rss_routes_through_throttle(self):- # The RSS tier must use the throttled helper, not raw get_text.- with mock.patch.object(reddit_rss.http, "reddit_keyless_get_text", return_value=None) as throttled:- reddit_rss.search_rss("test query")- assert throttled.called-class TestRedditKeylessRateKnob:def test_default_rate_is_one_per_sec_small_burst(self):@@ -81,7 +75,7 @@ class TestRedditKeylessRateKnob:monkeypatch.setenv(http.REDDIT_KEYLESS_RATE_ENV, "0.5")with mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \mock.patch.object(http, "get_text", return_value="ok"):- http.reddit_keyless_get_text("https://www.reddit.com/x.rss")+ http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=x")assert http.REDDIT_KEYLESS_LIMITER.rate == 0.5def test_env_file_value_is_exported_for_limiter(self, tmp_path, monkeypatch):@@ -111,7 +105,7 @@ def _record_status(code: int, reason: str) -> None:class TestRedditKeyless429Retry:def test_429_then_200_recovers_via_single_retry(self):- bodies = [None, "<feed xmlns='http://www.w3.org/2005/Atom'/>"]+ bodies = [None, "<html>ok</html>"]def fake_get(*_args, **_kwargs):val = bodies.pop(0)@@ -124,9 +118,9 @@ class TestRedditKeyless429Retry:mock.patch.object(http.time, "sleep") as slept, \mock.patch.object(http.random, "uniform", return_value=0.0):text, err = http.reddit_keyless_get_text_retry_429(- "https://www.reddit.com/search.rss"+ "https://www.reddit.com/svc/shreddit/search/?q=x")- assert text.startswith("<feed")+ assert text.startswith("<html")assert err is Noneassert acq.call_count == 2slept.assert_called_once()@@ -143,7 +137,7 @@ class TestRedditKeyless429Retry:mock.patch.object(http.random, "uniform", return_value=0.0), \http.capture_failures() as failures:text, err = http.reddit_keyless_get_text_retry_429(- "https://www.reddit.com/search.rss"+ "https://www.reddit.com/svc/shreddit/search/?q=x")assert text is Noneassert err is not None and "429" in err@@ -160,7 +154,7 @@ class TestRedditKeyless429Retry:mock.patch.object(http.time, "sleep") as slept, \http.capture_failures() as failures:text, err = http.reddit_keyless_get_text_retry_429(- "https://www.reddit.com/search.rss"+ "https://www.reddit.com/svc/shreddit/search/?q=x")assert text is Noneassert "403" in (err or "")@@ -168,30 +162,6 @@ class TestRedditKeyless429Retry:slept.assert_not_called()assert any(f.status_code == 403 for f in failures)- def test_rss_fetch_feed_recovers_after_one_429(self):- feed = (- '<feed xmlns="http://www.w3.org/2005/Atom"><entry>'- "<title>Recovered</title>"- '<link href="https://www.reddit.com/r/test/comments/abc/x/" />'- "<updated>2026-05-20T00:00:00+00:00</updated></entry></feed>"- )- bodies = [None, feed]-- def fake_get(*_args, **_kwargs):- val = bodies.pop(0)- if val is None:- _record_status(429, "Too Many Requests")- return val-- with mock.patch.object(http, "get_text", side_effect=fake_get), \- mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \- mock.patch.object(http.time, "sleep"):- posts = reddit_rss._fetch_feed(- "https://www.reddit.com/search.rss", "Recovered"- )- assert len(posts) == 1- assert posts[0]["title"] == "Recovered"-def test_listing_fetch_recovers_after_one_429(self):from pathlib import Pathdiff --git a/tests/test_reddit_keyless_memo.py b/tests/test_reddit_keyless_memo.pyindex f941adf7..2006e2f1 100644--- a/tests/test_reddit_keyless_memo.py+++ b/tests/test_reddit_keyless_memo.py@@ -1,6 +1,6 @@"""Run-scoped memo for keyless Reddit GETs.-Subreddit listings, listing RSS feeds, arctic supplements, and shreddit comment+Subreddit listings, site search pages, arctic supplements, and shreddit commentpages are byte-identical across subqueries (the lane is dispatched with the rawtopic every time), so a four-subquery run fetched each of them four times."""@@ -21,40 +21,40 @@ def _fresh_memo():def test_second_call_for_same_url_is_served_from_memo():- with mock.patch.object(http, "get_text", return_value="<feed/>") as get_text, \+ with mock.patch.object(http, "get_text", return_value="<html/>") as get_text, \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire") as acquire:- first = http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/top.rss?t=month")- second = http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/top.rss?t=month")- assert first == second == "<feed/>"+ first = http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye&t=month")+ second = http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye&t=month")+ assert first == second == "<html/>"assert get_text.call_count == 1assert acquire.call_count == 1, "a memo hit must not spend a limiter token"def test_failed_fetch_is_not_memoized():- with mock.patch.object(http, "get_text", side_effect=[None, "<feed/>"]) as get_text, \+ with mock.patch.object(http, "get_text", side_effect=[None, "<html/>"]) as get_text, \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):- assert http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/hot.rss") is None- assert http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/hot.rss") == "<feed/>"+ assert http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye+hot") is None+ assert http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye+hot") == "<html/>"assert get_text.call_count == 2def test_reset_clears_the_memo():- with mock.patch.object(http, "get_text", return_value="<feed/>") as get_text, \+ with mock.patch.object(http, "get_text", return_value="<html/>") as get_text, \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):- http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/new.rss")+ http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye+new")http.reset_reddit_keyless_memo()- http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/new.rss")+ http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=Kanye+new")assert get_text.call_count == 2def test_memo_is_bounded():- with mock.patch.object(http, "get_text", return_value="<feed/>") as get_text, \+ with mock.patch.object(http, "get_text", return_value="<html/>") as get_text, \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):for i in range(http.REDDIT_KEYLESS_MEMO_MAX + 1):- http.reddit_keyless_get_text(f"https://www.reddit.com/r/s{i}/top.rss")+ http.reddit_keyless_get_text(f"https://www.reddit.com/svc/shreddit/search/?q=s{i}")# The very first URL was evicted; the most recent one is still cached.- http.reddit_keyless_get_text("https://www.reddit.com/r/s0/top.rss")- http.reddit_keyless_get_text(f"https://www.reddit.com/r/s{http.REDDIT_KEYLESS_MEMO_MAX}/top.rss")+ http.reddit_keyless_get_text("https://www.reddit.com/svc/shreddit/search/?q=s0")+ http.reddit_keyless_get_text(f"https://www.reddit.com/svc/shreddit/search/?q=s{http.REDDIT_KEYLESS_MEMO_MAX}")assert get_text.call_count == http.REDDIT_KEYLESS_MEMO_MAX + 2@@ -65,7 +65,7 @@ def test_concurrent_requesters_share_one_in_flight_fetch():def slow_get_text(url, **kwargs):calls.append(url)release.wait(timeout=5)- return "<feed/>"+ return "<html/>"results = []with mock.patch.object(http, "get_text", side_effect=slow_get_text), \@@ -80,16 +80,16 @@ def test_concurrent_requesters_share_one_in_flight_fetch():release.set()for t in threads:t.join(timeout=5)- assert results == ["<feed/>"] * 4+ assert results == ["<html/>"] * 4assert calls == [url], "four concurrent requesters must share one fetch"def test_retry_helper_goes_through_the_memo():- with mock.patch.object(http, "get_text", return_value="<feed/>") as get_text, \+ with mock.patch.object(http, "get_text", return_value="<html/>") as get_text, \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):- body, err = http.reddit_keyless_get_text_retry_429("https://www.reddit.com/r/Kanye/top.rss")- body2, err2 = http.reddit_keyless_get_text_retry_429("https://www.reddit.com/r/Kanye/top.rss")- assert (body, err) == ("<feed/>", None) == (body2, err2)+ body, err = http.reddit_keyless_get_text_retry_429("https://www.reddit.com/svc/shreddit/search/?q=Kanye")+ body2, err2 = http.reddit_keyless_get_text_retry_429("https://www.reddit.com/svc/shreddit/search/?q=Kanye")+ assert (body, err) == ("<html/>", None) == (body2, err2)assert get_text.call_count == 1@@ -105,12 +105,12 @@ def test_waiters_do_not_stampede_when_the_owner_fails():calls.append(url)n = len(calls)release.wait(timeout=5)- return None if n == 1 else "<feed/>"+ return None if n == 1 else "<html/>"results = []with mock.patch.object(http, "get_text", side_effect=get_text), \mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):- url = "https://www.reddit.com/r/Kanye/top.rss?t=month"+ url = "https://www.reddit.com/svc/shreddit/search/?q=Kanye&t=month"threads = [threading.Thread(target=lambda: results.append(http.reddit_keyless_get_text(url))) for _ in range(4)]for t in threads:t.start()@@ -118,5 +118,5 @@ def test_waiters_do_not_stampede_when_the_owner_fails():release.set()for t in threads:t.join(timeout=10)- assert sorted(results, key=str) == [None, "<feed/>", "<feed/>", "<feed/>"] or results.count("<feed/>") >= 3+ assert sorted(results, key=str) == [None, "<html/>", "<html/>", "<html/>"] or results.count("<html/>") >= 3assert len(calls) <= 2, f"expected the owner's fetch plus one retry, got {len(calls)}"diff --git a/tests/test_reddit_keyless_wait_allowance.py b/tests/test_reddit_keyless_wait_allowance.pyindex 8ab3c0ae..19ddfe28 100644--- a/tests/test_reddit_keyless_wait_allowance.py+++ b/tests/test_reddit_keyless_wait_allowance.py@@ -1,17 +1,17 @@"""Per-future result timeouts must cover the keyless bucket's queue.-At 1 req/s, a batch of thirteen feed URLs on four workers queues about+At 1 req/s, a batch of thirteen keyless URLs on four workers queues aboutthirteen seconds of token waits before the last fetch even starts, and foursubquery streams share the same bucket. A fixed 20-second future timeout then-expires while the fetch is still waiting for a token, and the feed is dropped-(`[RedditRSS] feed future failed:` with an empty message on the 2026-08-31-smoke run).+expires while the fetch is still waiting for a token, and the result is+dropped with an empty future-failure message (seen on the 2026-08-31 smoke+run). The site search lane's timeout is covered in test_reddit_search.py."""import threadingfrom unittest import mock-from lib import http, reddit_listing, reddit_rss+from lib import http, reddit_listingdef test_limiter_reports_waiting_threads():@@ -47,12 +47,11 @@ def test_wait_allowance_scales_with_batch_and_queue(monkeypatch):assert http.reddit_keyless_wait_allowance(13) == 9.0 + pad-def test_rss_and_listing_result_timeouts_include_the_allowance(monkeypatch):+def test_listing_result_timeout_includes_the_allowance(monkeypatch):limiter = http.RateLimiter(rate_per_sec=1.0, burst=2)monkeypatch.delenv(http.REDDIT_KEYLESS_RATE_ENV, raising=False)with mock.patch.object(http, "REDDIT_KEYLESS_LIMITER", limiter):pad = http.REDDIT_KEYLESS_CONTENTION_SECONDS- assert reddit_rss._result_timeout(13) == reddit_rss.FEED_TIMEOUT + 5 + 13.0 + padassert reddit_listing._result_timeout(20) == reddit_listing.LISTING_TIMEOUT + 5 + 20.0 + paddiff --git a/tests/test_reddit_ratelimit_reset.py b/tests/test_reddit_ratelimit_reset.pyindex dc5eb0bf..2f400671 100644--- a/tests/test_reddit_ratelimit_reset.py+++ b/tests/test_reddit_ratelimit_reset.py@@ -13,7 +13,7 @@ class TestRetryDelayFromHeaders:assert http.retry_delay_from_headers({"Retry-After": "17"}, 3.0) == 17.0def test_falls_back_to_x_ratelimit_reset(self):- # The header Reddit actually sends on search/RSS 429s.+ # The header Reddit actually sends on anonymous search 429s.assert http.retry_delay_from_headers({"x-ratelimit-reset": "42"}, 3.0) == 42.0def test_retry_after_wins_over_ratelimit_reset(self):@@ -21,8 +21,8 @@ class TestRetryDelayFromHeaders:assert http.retry_delay_from_headers(headers, 3.0) == 5.0def test_real_reddit_429_headers(self):- # Captured verbatim from an anonymous GET to- # https://www.reddit.com/search.rss?q=... on 2026-08-23.+ # Captured verbatim from an anonymous keyless Reddit search GET+ # on 2026-08-23.headers = {"x-ratelimit-used": "1","x-ratelimit-remaining": "0.0",diff --git a/tests/test_reddit_relevance_ranking.py b/tests/test_reddit_relevance_ranking.pyindex 7d2c2f5b..80ba693e 100644--- a/tests/test_reddit_relevance_ranking.py+++ b/tests/test_reddit_relevance_ranking.py@@ -2,7 +2,7 @@Reddit's highest-upvote content (relationship drama, AITA, viral news) oftenhas near-zero topic overlap. Before this change both the keyed (ScrapeCreators)-and keyless (RSS) paths ranked the final list engagement-first, so a viral+and keyless paths ranked the final list engagement-first, so a viraloff-topic post outranked on-topic posts. These tests pin the new behavior:on-topic posts rank first and pure zero-overlap posts are dropped when anythingrelevant remains.@@ -105,7 +105,7 @@ def _kpost(rid, rel, score, date="2026-05-20"):"score": score, "num_comments": score, "subreddit": "t", "created_utc": None,"author": "u", "selftext": "", "date": date,"engagement": {"score": score, "num_comments": score, "upvote_ratio": None},- "relevance": rel, "why_relevant": "Reddit RSS", "metadata": {},+ "relevance": rel, "why_relevant": "Reddit search", "metadata": {},}diff --git a/tests/test_reddit_rss.py b/tests/test_reddit_rss.pydeleted file mode 100644index 04b4f519..00000000--- a/tests/test_reddit_rss.py+++ /dev/null@@ -1,104 +0,0 @@-"""Tests for scripts/lib/reddit_rss.py — keyless Reddit RSS discovery."""--from pathlib import Path-from unittest import mock--import pytest--from lib import reddit_rss--[email protected](autouse=True)-def _no_keyless_throttle():- with mock.patch.object(reddit_rss.http.REDDIT_KEYLESS_LIMITER, "acquire"):- yield--FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "reddit_search_rss_sample.xml"---def _feed_text():- return FIXTURE.read_text(encoding="utf-8")---class TestParseFeed:- """_parse_feed turns Atom entries into normalized post dicts."""-- def test_parses_entries(self):- posts = reddit_rss._parse_feed(_feed_text(), query="lifelock")- assert len(posts) == 5- for p in posts:- assert p["title"]- assert "/comments/" in p["url"]- assert p["url"].startswith("https://www.reddit.com/")-- def test_normalized_shape_matches_scrapecreators(self):- post = reddit_rss._parse_feed(_feed_text(), query="x")[0]- required = {"id", "title", "url", "score", "num_comments", "subreddit",- "created_utc", "author", "selftext", "date",- "engagement", "relevance", "why_relevant", "metadata"}- assert required.issubset(set(post.keys()))- assert set(post["engagement"].keys()) == {"score", "num_comments", "upvote_ratio"}- assert post["why_relevant"] == "Reddit RSS"-- def test_score_is_placeholder_zero(self):- # RSS carries no engagement score; it is backfilled during enrichment.- for p in reddit_rss._parse_feed(_feed_text(), query="x"):- assert p["score"] == 0- assert p["engagement"]["score"] == 0-- def test_subreddit_derivation(self):- post = reddit_rss._parse_feed(_feed_text(), query="x")[0]- assert post["subreddit"] == "Rakuten"-- def test_date_parsed_to_iso(self):- post = reddit_rss._parse_feed(_feed_text(), query="x")[0]- assert post["date"] and len(post["date"]) == 10 # YYYY-MM-DD- assert isinstance(post["created_utc"], float)-- def test_author_strips_u_prefix(self):- authors = [p["author"] for p in reddit_rss._parse_feed(_feed_text(), query="x")]- assert all(not a.startswith("/u/") and not a.startswith("u/") for a in authors)-- def test_empty_and_malformed_feed_never_raises(self):- assert reddit_rss._parse_feed("", query="x") == []- assert reddit_rss._parse_feed("<not xml", query="x") == []- assert reddit_rss._parse_feed("<feed></feed>", query="x") == []-- def test_entry_without_comments_link_skipped(self):- feed = (- '<feed xmlns="http://www.w3.org/2005/Atom"><entry>'- '<title>Subreddit itself</title>'- '<link href="https://www.reddit.com/r/test/" />'- '<updated>2026-05-20T00:00:00+00:00</updated></entry></feed>'- )- assert reddit_rss._parse_feed(feed, query="x") == []---class TestSearchRss:- """search_rss fans out, dedupes, assigns IDs, and honors depth limits."""-- def test_dedupe_and_ids(self):- # Same feed returned for every URL -> deduped to 5 unique posts.- with mock.patch.object(reddit_rss.http, "get_text", return_value=_feed_text()):- posts = reddit_rss.search_rss("lifelock", depth="default",- subreddits=["Rakuten", "ConsumerAdvice"])- urls = [p["url"] for p in posts]- assert len(urls) == len(set(urls)) # no duplicates- assert [p["id"] for p in posts] == [f"R{i+1}" for i in range(len(posts))]-- def test_depth_limit_quick(self):- with mock.patch.object(reddit_rss.http, "get_text", return_value=_feed_text()):- posts = reddit_rss.search_rss("lifelock", depth="quick")- assert len(posts) <= reddit_rss.DEPTH_LIMITS["quick"]-- def test_all_feeds_fail_returns_empty(self):- with mock.patch.object(reddit_rss.http, "get_text", return_value=None):- posts = reddit_rss.search_rss("lifelock", subreddits=["Rakuten"])- assert posts == []-- def test_builds_keyless_rss_urls(self):- urls = reddit_rss._build_urls("life lock", "default", ["Rakuten"])- assert any("search.rss?q=life+lock" in u and "/r/" not in u.split("?")[0] for u in urls)- assert any("/r/Rakuten/search.rss" in u and "restrict_sr=on" in u for u in urls)- assert any("/r/Rakuten/top.rss" in u for u in urls)- assert all(".json" not in u for u in urls) # never the dead endpointdiff --git a/tests/test_reddit_sc_memo.py b/tests/test_reddit_sc_memo.pynew file mode 100644index 00000000..cdb44440--- /dev/null+++ b/tests/test_reddit_sc_memo.py@@ -0,0 +1,183 @@+"""Run-scoped ScrapeCreators Reddit memo (U5, R9): one run never pays for the+same Reddit query twice, across concurrent streams, the thin-source retry, and+the pinned-backend path. A failed call is not retried within the run."""++import threading+from concurrent.futures import ThreadPoolExecutor+from unittest import mock++import pytest++from lib import env, http, pipeline, reddit, schema++FROM, TO = "2026-05-26", "2026-06-25"+++def _memo(query="kanye", depth="default", subreddits=None, token="k"):+ return reddit.search_and_enrich_memo(+ query, FROM, TO, depth=depth, token=token, subreddits=subreddits,+ )+++class TestMemo:+ def test_sequential_same_key_calls_once_and_returns_equal_results(self):+ with mock.patch("lib.reddit.search_and_enrich",+ return_value={"items": [{"id": "a"}]}) as sc:+ first = _memo()+ second = _memo()+ assert sc.call_count == 1+ assert first == second == {"items": [{"id": "a"}]}++ def test_concurrent_same_key_calls_once(self):+ release = threading.Event()+ calls = []++ def _slow(*args, **kwargs):+ calls.append(args)+ release.wait(timeout=5)+ return {"items": [{"id": "a"}]}++ with mock.patch("lib.reddit.search_and_enrich", side_effect=_slow):+ with ThreadPoolExecutor(max_workers=4) as pool:+ futures = [pool.submit(_memo) for _ in range(4)]+ # Let every caller reach the memo before the owner finishes.+ threading.Timer(0.2, release.set).start()+ results = [f.result(timeout=10) for f in futures]+ assert len(calls) == 1+ assert all(r == {"items": [{"id": "a"}]} for r in results)++ def test_failure_is_cached_and_not_retried(self):+ boom = RuntimeError("HTTP 402: Payment Required")+ with mock.patch("lib.reddit.search_and_enrich", side_effect=boom) as sc:+ with pytest.raises(RuntimeError) as first:+ _memo()+ with pytest.raises(RuntimeError) as second:+ _memo()+ assert sc.call_count == 1+ assert str(first.value) == str(second.value) == "HTTP 402: Payment Required"++ def test_swallowed_failure_is_replayed_to_every_caller(self):+ # search_and_enrich swallows a ScrapeCreators HTTP error into the+ # caller's failure sink and returns no posts. A memo hit must replay+ # that failure, or a later stream reads it as a clean empty result.+ def _swallow_429(*_args, **_kwargs):+ http._record_failure(http.HTTPError("HTTP 429: Too Many Requests", status_code=429))+ return {"items": []}++ with mock.patch("lib.reddit.search_and_enrich", side_effect=_swallow_429) as sc:+ with http.capture_failures() as first_sink:+ first = _memo()+ with http.capture_failures() as second_sink:+ second = _memo()+ assert sc.call_count == 1+ assert first == second == {"items": []}+ assert [f.status_code for f in first_sink] == [429]+ assert [f.status_code for f in second_sink] == [429]++ def test_depth_and_subreddits_are_part_of_the_key(self):+ with mock.patch("lib.reddit.search_and_enrich",+ return_value={"items": []}) as sc:+ _memo(depth="default")+ _memo(depth="deep")+ _memo(subreddits=["a", "b"])+ _memo(subreddits=["b", "a"]) # same set, different order: same key+ _memo(subreddits=["a"])+ assert sc.call_count == 4++ def test_reset_calls_again(self):+ with mock.patch("lib.reddit.search_and_enrich",+ return_value={"items": []}) as sc:+ _memo()+ reddit.reset_scrapecreators_memo()+ _memo()+ assert sc.call_count == 2++ def test_callers_get_independent_copies(self):+ with mock.patch("lib.reddit.search_and_enrich",+ return_value={"items": [{"id": "a"}]}):+ first = _memo()+ first["items"][0]["id"] = "mutated"+ second = _memo()+ assert second["items"][0]["id"] == "a"+++def _runtime():+ return schema.ProviderRuntime(reasoning_provider="mock", planner_model="mock",+ rerank_model="mock")+++def _post(pid):+ return {+ "id": pid,+ "title": f"kanye post {pid}",+ "url": f"https://www.reddit.com/r/x/comments/{pid}/t/",+ "subreddit": "x",+ "date": "2026-06-01",+ "score": 10,+ "num_comments": 1,+ "relevance": 0.9,+ }+++def _run_four_streams(config, depth="default"):+ subqueries = [+ schema.SubQuery(label=f"q{i}", search_query=f"kanye angle {i}",+ ranking_query="kanye", sources=["reddit"])+ for i in range(4)+ ]++ def _one(sq):+ return pipeline._retrieve_stream(+ topic="kanye", subquery=sq, source="reddit", config=config,+ depth=depth, date_range=(FROM, TO), runtime=_runtime(), mock=False,+ raw_topic="kanye",+ )++ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(_one, subqueries))+ return subqueries, results+++class TestPipelineIntegration:+ KEY = {"SCRAPECREATORS_API_KEY": "k"}++ def test_four_thin_streams_plus_thin_retry_make_one_sc_call(self):+ # Free lane returns 1 item (below the default floor of 5), so every+ # stream and the thin retry want a backfill. Only the underlying+ # ScrapeCreators search may run, once.+ with mock.patch("lib.reddit_public.search_reddit_public",+ return_value=[_post("free1")]), \+ mock.patch("lib.reddit.search_reddit",+ return_value={"items": [_post("sc1")]}) as sc_search, \+ mock.patch("lib.reddit.enrich_with_comments",+ side_effect=lambda items, *_a, **_k: items):+ subqueries, results = _run_four_streams(self.KEY)+ assert all(items for items, _ in results)++ plan = schema.QueryPlan(+ intent="breaking_news", freshness_mode="balanced_recent",+ cluster_mode="none", raw_topic="kanye", subqueries=subqueries,+ source_weights={"reddit": 1.0},+ )+ bundle = schema.RetrievalBundle() # reddit thin -> retried+ pipeline._retry_thin_sources(+ topic="kanye", bundle=bundle, plan=plan, config=self.KEY,+ depth="default", date_range=(FROM, TO), runtime=_runtime(),+ mock=False, rate_limited_sources=set(),+ rate_limit_lock=threading.Lock(),+ settings={"per_stream_limit": 20},+ )+ assert sc_search.call_count == 1++ def test_pinned_path_four_streams_share_one_call(self):+ cfg = {**self.KEY, env.REDDIT_BACKEND_PIN_VAR: "scrapecreators"}+ with mock.patch("lib.reddit_public.search_reddit_public",+ return_value=[]) as public, \+ mock.patch("lib.reddit.search_reddit",+ return_value={"items": [_post("sc1")]}) as sc_search, \+ mock.patch("lib.reddit.enrich_with_comments",+ side_effect=lambda items, *_a, **_k: items):+ _subqueries, results = _run_four_streams(cfg)+ assert sc_search.call_count == 1+ public.assert_not_called()+ assert all(items for items, _ in results)diff --git a/tests/test_reddit_search.py b/tests/test_reddit_search.pynew file mode 100644index 00000000..359614fb--- /dev/null+++ b/tests/test_reddit_search.py@@ -0,0 +1,396 @@+"""Keyless Reddit discovery via Reddit's site search fragment (reddit_search).++Fixtures under fixtures/reddit_search_*.html are trimmed live captures of+/svc/shreddit/search/ and /svc/shreddit/r/{sub}/search/, except the challenge+page, which is synthetic (see its provenance line).+"""++import itertools+import json+import re+import urllib.error+from datetime import datetime, timezone+from pathlib import Path+from unittest import mock+from urllib.parse import parse_qs, urlsplit++import pytest++from lib import dates, health, http, reddit, reddit_search, schema++FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"++PAGE1_URL = (+ "https://www.reddit.com/svc/shreddit/search/"+ "?q=ButcherBox&type=posts&t=month&sort=relevance"+)+PAGE1_CURSOR = (+ "eyJjYW5kaWRhdGVzX3JldHVybmVkIjoie1wic2VjdGlvbl8xX3BpcGVsaW5lXzBfZ2xvYmFsX21vZGlmaWVyc1wiOlwiMVwiLFwic2VjdGlvbl8xX3BpcGVsaW5lXzFfbG9jYWxfbW9kaWZpZXJzXCI6XCIyXCIsXCJzZWN0aW9uXzJfcGlwZWxpbmVfMTBfdXh0c191bml0XCI6XCIwXCIsXCJzZWN0aW9uXzJfcGlwZWxpbmVfMTFfcXVlcnlfc3VnZ2VzdGlvbnNcIjpcIjZcIixcInNlY3Rpb25fMl9waXBlbGluZV84X3Bvc3Rfc2VhcmNoXCI6XCI3XCIsXCJzZWN0aW9uXzNfcGlwZWxpbmVfMF9zdWJyZWRkaXRfc2VhcmNoXCI6XCI1XCIsXCJzZWN0aW9uXzNfcGlwZWxpbmVfMV9hdXRob3Jfc2VhcmNoXCI6XCI1XCJ9IiwiZXhwZXJpZW5jZV9zZWxlY3Rpb24iOiJwb3N0X3dpdGhfc2lkZWJhciIsImV4cGVyaWVuY2VfdmVyc2lvbiI6ImRlZmF1bHQiLCJzZWN0aW9uXzJfcGlwZWxpbmVfOF9wb3N0X3NlYXJjaCI6IjcifQ=="+)+PAGE2_URL = PAGE1_URL + "&cursor=" + PAGE1_CURSOR.replace("=", "%3D")++PAGE1_POSTS = [+ # (post id, subreddit, title, date, score, comments)+ ("1w6swt2", "referralcodes", "Looking for a ButcherBox referral code", "2026-09-04", 1, 27),+ ("1wkybur", "TimDillon", "Today’s Ad Read for ButcherBox", "2026-09-19", 144, 26),+ ("1w9s403", "Netherlands", "Best online butchers in the Netherlands?\U0001f969", "2026-09-07", 0, 62),+ ("1wbvi5s", "findareferralcode", "Anyone has a butcher box referral code?", "2026-09-09", 1, 1),+ ("1w7w7k3", "ButcherHero_HooknChew", "Found the free gems", "2026-09-05", 7, 8),+ ("1wmumud", "rawprimal", "What! Butcher’s website", "2026-09-22", 3, 7),+ ("1w4tbqb", "findareferralcode", "Anybody have a referral code or link for Butcher Box?", "2026-09-01", 1, 2),+]+LAST_PAGE_IDS = ["1wtoesn", "1wns3fq"]+++def _fixture(name: str) -> str:+ return (FIXTURES / name).read_text(encoding="utf-8")+++def _post_ids(posts):+ return [p["metadata"]["post_id"] for p in posts]+++def _synthetic_page(post_ids, cursor=None, sub="example"):+ """A minimal search fragment with the live markup's result-unit shape."""+ units = []+ for pid in post_ids:+ ctx = json.dumps({+ "action_info": {"type": "post"},+ "post": {"id": f"t3_{pid}", "title": f"Topic post {pid}"},+ "subreddit": {"name": sub},+ }).replace('"', """)+ units.append(+ f'<search-telemetry-tracker data-faceplate-tracking-context="{ctx}" '+ f'view-events="search/view/post"><h2><a data-testid="post-title" '+ f'href="/r/{sub}/comments/{pid}/topic_post/">Topic post {pid}</a></h2>'+ f'</search-telemetry-tracker>'+ f'<faceplate-timeago ts="2026-09-20T10:00:00.000000+0000"></faceplate-timeago>'+ f'<div data-testid="search-counter-row"><span><faceplate-number number="5" pretty>'+ f'</faceplate-number> votes</span><span><faceplate-number number="2" pretty>'+ f'</faceplate-number> comments</span></div>'+ )+ if cursor:+ units.append(+ f'<faceplate-partial loading="lazy" src="/svc/shreddit/search/?q=x&'+ f'type=posts&cursor={cursor}"></faceplate-partial>'+ )+ return "<html><body>" + "".join(units) + "</body></html>"+++class FakeReddit:+ """Stands in for get_text: serves bodies by URL and records every request."""++ def __init__(self, routes=None, default=None):+ self.routes = dict(routes or {})+ self.default = default+ self.requests = []++ def __call__(self, url, **_kwargs):+ self.requests.append(url)+ body = self.routes.get(url, self.default)+ if callable(body):+ return body(url)+ return body+++def fake_reddit():+ fake = FakeReddit()+ with mock.patch.object(http, "get_text", side_effect=fake), \+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \+ mock.patch.object(http.time, "sleep"):+ yield fake+++def _status(code, reason):+ def _respond(_url):+ http._record_failure(http.HTTPError(f"HTTP {code}: {reason}", code))+ return None+ return _respond+++class TestParse:+ def test_page1_yields_post_units_with_dates_scores_and_comments(self):+ posts, _cursor = reddit_search.parse_page(_fixture("reddit_search_page1.html"), "ButcherBox")+ got = [+ (p["metadata"]["post_id"], p["subreddit"], p["title"], p["date"], p["score"], p["num_comments"])+ for p in posts+ ]+ # Seven post units; the page's community links and six "People also+ # search for" suggestions are not posts.+ assert got == PAGE1_POSTS+ first = posts[0]+ assert first["engagement"] == {"score": 1, "num_comments": 27, "upvote_ratio": None}+ assert first["created_utc"] == datetime(2026, 9, 4, 3, 26, 52, 161000, tzinfo=timezone.utc).timestamp()+ assert first["author"] == ""+ assert first["selftext"] == ""+ assert first["why_relevant"] == "Reddit search"+ assert first["relevance"] > 0+ assert posts[4]["relevance"] == 0.0 # "Found the free gems" shares no query token++ def test_url_is_canonical_permalink_matching_post_id(self):+ posts, _ = reddit_search.parse_page(_fixture("reddit_search_page1.html"), "ButcherBox")+ assert posts[1]["url"] == (+ "https://www.reddit.com/r/TimDillon/comments/1wkybur/todays_ad_read_for_butcherbox/"+ )+ for p in posts:+ assert p["url"].startswith(f"https://www.reddit.com/r/{p['subreddit']}/comments/")+ assert p["url"].split("/comments/")[1].split("/")[0] == p["metadata"]["post_id"]++ def test_cursor_read_from_next_page_partial(self):+ _, cursor = reddit_search.parse_page(_fixture("reddit_search_page1.html"))+ assert cursor == PAGE1_CURSOR+ _, last_cursor = reddit_search.parse_page(_fixture("reddit_search_last_page.html"))+ assert last_cursor is None+++class TestPartialDrift:+ def test_skipped_post_does_not_leak_counts_into_its_neighbour(self):+ body = _fixture("reddit_search_page1.html")+ clean, _ = reddit_search.parse_page(body)+ assert len(clean) >= 3+ # Corrupt only the second post's tracker (post field no longer an object).+ victim = clean[1]["metadata"]["post_id"]+ tracker = next(+ m for m in reddit_search._TRACKER.finditer(body)+ if "t3_" + victim in m.group(0) and ""type":"post"" in m.group(0)+ )+ start = body.index(""post":{", tracker.start(), tracker.end())+ corrupted = body[:start] + ""post":"x","old_post":{" + body[start + len(""post":{"):]+ parsed, _ = reddit_search.parse_page(corrupted)+ by_id = {p["metadata"]["post_id"]: p for p in parsed}+ assert victim not in by_id+ for post in clean:+ pid = post["metadata"]["post_id"]+ if pid == victim:+ continue+ assert (by_id[pid]["score"], by_id[pid]["num_comments"]) == (post["score"], post["num_comments"])+++class TestUrls:+ def test_global_and_cursor_urls(self):+ assert reddit_search.search_url("ButcherBox", "month") == PAGE1_URL+ assert reddit_search.search_url("ButcherBox", "month", cursor=PAGE1_CURSOR) == PAGE2_URL++ def test_per_sub_url_uses_sub_search_path(self):+ assert reddit_search.search_url("Tubi TV", "week", subreddit="r/TubiTV") == (+ "https://www.reddit.com/svc/shreddit/r/TubiTV/search/"+ "?q=Tubi+TV&type=posts&t=week&sort=relevance"+ )++ @pytest.mark.parametrize("days,expected", [(7, "month"), (90, "year")])+ def test_window_sets_time_filter_like_scrapecreators_path(self, fake_reddit, days, expected):+ fake_reddit.default = _fixture("reddit_search_no_results.html")+ from_date, to_date = dates.get_date_range(days)+ reddit_search.search("Tubi", depth="quick", from_date=from_date, to_date=to_date)+ sent = parse_qs(urlsplit(fake_reddit.requests[0]).query)["t"]+ assert sent == [expected]+ assert sent == [reddit._window_to_time_filter(from_date, to_date)]+++class TestPaging:+ def test_follows_cursor_to_last_page_and_stops(self, fake_reddit):+ fake_reddit.routes = {+ PAGE1_URL: _fixture("reddit_search_page1.html"),+ PAGE2_URL: _fixture("reddit_search_last_page.html"),+ }+ posts = reddit_search.search("ButcherBox", depth="default")+ assert fake_reddit.requests == [PAGE1_URL, PAGE2_URL]+ assert _post_ids(posts) == [row[0] for row in PAGE1_POSTS] + LAST_PAGE_IDS+ assert [p["id"] for p in posts] == [f"R{i}" for i in range(1, 10)]++ def test_stops_on_repeated_cursor(self, fake_reddit):+ fake_reddit.routes = {+ PAGE1_URL: _fixture("reddit_search_page1.html"),+ # New posts, but the page points back at the cursor already used.+ PAGE2_URL: _synthetic_page(["aaa111", "bbb222"], cursor=PAGE1_CURSOR),+ }+ posts = reddit_search.search("ButcherBox", depth="deep")+ assert fake_reddit.requests == [PAGE1_URL, PAGE2_URL]+ assert _post_ids(posts)[-2:] == ["aaa111", "bbb222"]++ def test_stops_on_page_with_no_new_ids(self, fake_reddit):+ repeat = _fixture("reddit_search_page1.html").replace(PAGE1_CURSOR.replace("=", "%3D"), "freshcursor")+ fake_reddit.routes = {+ PAGE1_URL: _fixture("reddit_search_page1.html"),+ PAGE2_URL: repeat,+ }+ posts = reddit_search.search("ButcherBox", depth="deep")+ assert fake_reddit.requests == [PAGE1_URL, PAGE2_URL]+ assert _post_ids(posts) == [row[0] for row in PAGE1_POSTS]++ @pytest.mark.parametrize("depth,pages", [("quick", 2), ("default", 4), ("deep", 8)])+ def test_global_page_cap_by_depth(self, fake_reddit, depth, pages):+ served = []++ def endless(_url):+ n = len(served)+ served.append(n)+ return _synthetic_page([f"p{n}x{i}" for i in range(7)], cursor=f"c{n}")++ fake_reddit.default = endless+ posts = reddit_search.search("topic", depth=depth)+ assert len(fake_reddit.requests) == pages+ assert len(set(fake_reddit.requests)) == pages+ # Existing depth post caps still apply on top of the page cap.+ assert len(posts) == {"quick": 10, "default": 25, "deep": 50}[depth]++ def test_failed_second_page_keeps_first_page_and_records_failure(self, fake_reddit):+ fake_reddit.routes = {+ PAGE1_URL: _fixture("reddit_search_page1.html"),+ PAGE2_URL: _status(500, "Internal Server Error"),+ }+ with http.capture_failures() as failures:+ posts = reddit_search.search("ButcherBox", depth="default")+ assert _post_ids(posts) == [row[0] for row in PAGE1_POSTS]+ assert [f.status_code for f in failures] == [500]+++class TestTargetedSubs:+ def test_targeted_sub_gets_one_page_of_sub_search(self, fake_reddit):+ sub_url = (+ "https://www.reddit.com/svc/shreddit/r/TubiTV/search/"+ "?q=Tubi&type=posts&t=month&sort=relevance"+ )+ global_url = (+ "https://www.reddit.com/svc/shreddit/search/"+ "?q=Tubi&type=posts&t=month&sort=relevance"+ )+ fake_reddit.routes = {+ global_url: _fixture("reddit_search_no_results.html"),+ sub_url: _synthetic_page(["s1", "s2"], cursor="more", sub="TubiTV"),+ }+ posts = reddit_search.search("Tubi", depth="deep", subreddits=["r/TubiTV"])+ assert sorted(fake_reddit.requests) == sorted([global_url, sub_url])+ assert _post_ids(posts) == ["s1", "s2"]+ assert {p["subreddit"] for p in posts} == {"TubiTV"}++ def test_targeted_sub_posts_survive_the_depth_cap(self, fake_reddit):+ sub_url = (+ "https://www.reddit.com/svc/shreddit/r/TubiTV/search/"+ "?q=Tubi&type=posts&t=month&sort=relevance"+ )+ pages = itertools.count()++ def endless(_url):+ n = next(pages)+ return _synthetic_page([f"g{n}x{i}" for i in range(7)], cursor=f"c{n}")++ fake_reddit.default = endless+ fake_reddit.routes = {sub_url: _synthetic_page(["s1", "s2"], sub="TubiTV")}+ posts = reddit_search.search("Tubi", depth="quick", subreddits=["TubiTV"])+ assert len(posts) == 10+ assert {"s1", "s2"} <= set(_post_ids(posts))++ def test_full_targeted_pages_do_not_crowd_out_global_results(self, fake_reddit):+ subs = ["SubA", "SubB", "SubC", "SubD"]+ fake_reddit.routes = {+ "https://www.reddit.com/svc/shreddit/r/" + sub + "/search/"+ "?q=Tubi&type=posts&t=month&sort=relevance": _synthetic_page(+ [f"{sub}{i}" for i in range(7)], sub=sub+ )+ for sub in subs+ }+ fake_reddit.default = _synthetic_page([f"g{i}" for i in range(7)])+ posts = reddit_search.search("Tubi", depth="default", subreddits=subs)+ ids = _post_ids(posts)+ assert len(ids) == 25+ # 28 targeted posts alone would fill all 25 slots; global keeps a share.+ assert {f"g{i}" for i in range(5)} <= set(ids)+ assert all(any(i.startswith(sub) for i in ids) for sub in subs)+++class TestOutcomes:+ def test_challenge_page_records_failure_and_is_not_memoized(self, fake_reddit):+ fake_reddit.default = _fixture("reddit_search_challenge.html")+ with http.capture_failures() as failures:+ first = reddit_search.search("ButcherBox", depth="quick")+ second = reddit_search.search("ButcherBox", depth="quick")+ assert first == [] and second == []+ assert fake_reddit.requests == [PAGE1_URL, PAGE1_URL]+ assert len(failures) == 2+ assert all(f.outcome_state == health.SCHEMA_DRIFT for f in failures)++ @pytest.mark.parametrize("drift", [+ # Tracking context attribute gone entirely.+ lambda body: re.sub(r'\sdata-faceplate-tracking-context="[^"]*"', "", body),+ # Attribute kept, JSON shape changed (action_info renamed).+ lambda body: body.replace(""action_info"", ""action""),+ # Field kept but no longer an object, so .get() on it would raise.+ lambda body: body.replace(""post":{", ""post":"x","old_post":{"),+ ], ids=["stripped", "reshaped", "post-not-object"])+ def test_results_marker_with_no_parseable_units_is_schema_drift(self, fake_reddit, drift):+ body = drift(_fixture("reddit_search_page1.html"))+ assert reddit_search.RESULTS_MARKER in body+ assert reddit_search.parse_page(body)[0] == []+ assert reddit_search.unrecognized_body(body)+ fake_reddit.default = body+ with http.capture_failures() as failures:+ first = reddit_search.search("ButcherBox", depth="quick")+ second = reddit_search.search("ButcherBox", depth="quick")+ assert first == [] and second == []+ # Not memoized: the second run fetches again.+ assert fake_reddit.requests == [PAGE1_URL, PAGE1_URL]+ assert len(failures) == 2+ assert all(f.outcome_state == health.SCHEMA_DRIFT for f in failures)++ def test_recognized_page_is_memoized(self, fake_reddit):+ fake_reddit.routes = {PAGE1_URL: _fixture("reddit_search_no_results.html")}+ reddit_search.search("ButcherBox", depth="quick")+ reddit_search.search("ButcherBox", depth="quick")+ assert fake_reddit.requests == [PAGE1_URL]++ def test_no_results_page_returns_empty_without_failure(self, fake_reddit):+ fake_reddit.default = _fixture("reddit_search_no_results.html")+ with http.capture_failures() as failures:+ posts = reddit_search.search("zxqvbnmplkqqwerty7731", depth="default")+ assert posts == []+ assert failures == []+ assert len(fake_reddit.requests) == 1++ def test_429_then_success_retries_once_through_limiter(self):+ bodies = [None, _fixture("reddit_search_page1.html"), _fixture("reddit_search_last_page.html")]++ def fake_get(*_args, **_kwargs):+ body = bodies.pop(0)+ if body is None:+ http._record_failure(http.HTTPError("HTTP 429: Too Many Requests", 429))+ return body++ with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire") as acq, \+ mock.patch.object(http.time, "sleep"), \+ http.capture_failures() as failures:+ posts = reddit_search.search("ButcherBox", depth="quick")+ assert _post_ids(posts)[:7] == [row[0] for row in PAGE1_POSTS]+ assert [c.args[0] for c in gt.call_args_list] == [PAGE1_URL, PAGE1_URL, PAGE2_URL]+ assert acq.call_count == 3+ assert failures == []++ @mock.patch("lib.http.time.sleep")+ @mock.patch("lib.http.urllib.request.urlopen")+ def test_fanout_429_reaches_pipeline_failure_sink(self, mock_urlopen, _sleep):+ # get_text launders the 429 into None; the sink must survive the+ # ThreadPoolExecutor hop into the search workers (issue #899).+ mock_urlopen.side_effect = urllib.error.HTTPError(+ "https://www.reddit.com/svc/shreddit/search/", 429, "Too Many Requests", {}, None+ )+ with http.capture_failures() as failures:+ posts = reddit_search.search("test topic", depth="quick", subreddits=["example"])+ assert posts == []+ assert failures[-1].outcome_state == schema.RATE_LIMITED++ def test_unexpected_error_never_raises(self):+ with mock.patch.object(http, "reddit_keyless_get_text_retry_429", side_effect=RuntimeError("boom")):+ assert reddit_search.search("ButcherBox") == []+++def test_result_timeout_includes_keyless_wait_allowance(monkeypatch):+ limiter = http.RateLimiter(rate_per_sec=1.0, burst=2)+ monkeypatch.delenv(http.REDDIT_KEYLESS_RATE_ENV, raising=False)+ with mock.patch.object(http, "REDDIT_KEYLESS_LIMITER", limiter):+ pad = http.REDDIT_KEYLESS_CONTENTION_SECONDS+ timeout = reddit_search.SEARCH_TIMEOUT+ assert reddit_search._result_timeout(13) == timeout + 5 + 13.0 + pad+ # A paging stream waits for each of its sequential pages.+ assert reddit_search._result_timeout(13, pages=4) == 4 * (timeout + 5) + 13.0 + paddiff --git a/tests/test_reddit_transport_outcomes.py b/tests/test_reddit_transport_outcomes.pyindex 411cd8f0..2b6ab60b 100644--- a/tests/test_reddit_transport_outcomes.py+++ b/tests/test_reddit_transport_outcomes.py@@ -66,7 +66,7 @@ def _postmortem_from(report):def test_reddit_rate_limit_is_not_reported_as_clean_no_results():report = _run_reddit_against(urllib.error.HTTPError(- "https://www.reddit.com/search.rss", 429, "Too Many Requests", {}, None+ "https://www.reddit.com/svc/shreddit/search/", 429, "Too Many Requests", {}, None))@@ -78,7 +78,7 @@ def test_reddit_rate_limit_is_not_reported_as_clean_no_results():def test_reddit_block_is_not_reported_as_clean_no_results():report = _run_reddit_against(urllib.error.HTTPError(- "https://www.reddit.com/search.rss", 403, "Blocked", {}, None+ "https://www.reddit.com/svc/shreddit/search/", 403, "Blocked", {}, None))@@ -90,7 +90,7 @@ def test_reddit_block_is_not_reported_as_clean_no_results():def test_postmortem_does_not_claim_success_after_a_reddit_block():report = _run_reddit_against(urllib.error.HTTPError(- "https://www.reddit.com/search.rss", 429, "Too Many Requests", {}, None+ "https://www.reddit.com/svc/shreddit/search/", 429, "Too Many Requests", {}, None))@@ -255,7 +255,7 @@ def test_postmortem_shows_lane_detail_on_succeeded_source():def test_swallowed_429s_flag_the_source_as_rate_limited_for_thin_retry():lane_error = http.HTTPError(- "https://www.reddit.com/search.rss", status_code=429, body=b"Too Many Requests"+ "https://www.reddit.com/svc/shreddit/search/", status_code=429, body=b"Too Many Requests")subquery = schema.SubQuery(label="primary", search_query="matcha", ranking_query="matcha", sources=["reddit"],diff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.pyindex 849e5ddc..24ba0c7f 100644--- a/tests/test_source_outcomes.py+++ b/tests/test_source_outcomes.py@@ -12,7 +12,6 @@ from lib import (pipeline,reddit,reddit_listing,- reddit_rss,render,schema,youtube_yt,@@ -150,24 +149,10 @@ def test_reddit_nested_worker_propagates_failure_capture(mock_urlopen, _mock_sleassert failures[-1].outcome_state == schema.RATE_LIMITED-def _reddit_429(url="https://www.reddit.com/search.rss"):+def _reddit_429(url="https://www.reddit.com/svc/shreddit/search/"):return urllib.error.HTTPError(url, 429, "Too Many Requests", {}, None)-@patch("lib.http.time.sleep")-@patch("lib.http.urllib.request.urlopen")-def test_reddit_rss_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):- # get_text launders the 429 into None; the sink is what must survive the- # ThreadPoolExecutor hop into the feed workers (issue #899).- mock_urlopen.side_effect = _reddit_429()-- with http.capture_failures() as failures:- posts = reddit_rss.search_rss("test topic", depth="quick")-- assert posts == []- assert failures[-1].outcome_state == schema.RATE_LIMITED--@patch("lib.http.time.sleep")@patch("lib.http.urllib.request.urlopen")def test_reddit_listing_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):