Skip to content

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

fix(reddit): restore the keyless Reddit lane (comments, ranking, pacing) (#1083)

Matt Van Hornb28775e45a71
diff --git a/CONCEPTS.md b/CONCEPTS.md
index 41b4f45a..2f28ad1c 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -38,7 +38,11 @@ The research flow available with no API keys: source data is gathered by scrapin
### Comment-enrichment slots
-The small, depth-dependent budget of Reddit posts whose comments get fetched in the Keyless path. Slot selection is relevance-aware: posts that pass Entity grounding claim slots first, so the budget is not spent on high-engagement posts that final ranking will demote anyway.
+The small, depth-dependent budget of Reddit posts whose comments get fetched in the Keyless path (4 / 8 / 12 per subquery at quick / default / deep). Slot selection is relevance-aware and comment-first: posts that pass Entity grounding claim slots first, and within that tier the most-commented threads go first, so the budget is not spent on high-engagement posts that final ranking will demote or on near-empty threads.
+
+### Engagement keeper
+
+A Reddit thread that clears the relevance floor, passes Entity grounding, and ranks in the top three of its stream by upvotes plus comments. Keepers survive per-stream truncation regardless of their local rank score, and the fused candidate pool reserves a few slots (2 / 3 / 4 by depth) for the same class of thread, so the month's most-discussed on-topic threads reach the ranked output even when their title overlap with the query is weak. When the Primary entity's head token is generic ("ai", "new"), the floor rises so viral off-topic threads cannot claim the slots.
## Discovery
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 8f196b97..381bec5d 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -135,7 +135,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 | always on; SC knobs require `SCRAPECREATORS_API_KEY` | yes |
+| 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 |
| 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) |
@@ -166,6 +166,8 @@ 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`).
+
**YouTube transcript tuning.** `LAST30DAYS_YT_SUB_LANGS` controls the comma-separated caption-language priority passed to yt-dlp and defaults to `en,es,pt`. When `SCRAPECREATORS_API_KEY` is available, yt-dlp uses one fast attempt before the paid fallback; set `LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT` to the number of seconds allowed for that attempt when a throttled host needs longer than the 12-second default. A VTT completed before the timeout is reused rather than discarded. `LAST30DAYS_YT_SEARCH_TIMEOUT` sets the per-search yt-dlp deadline (default 120s). Comparison-mode fan-out also caps concurrent yt-dlp processes process-wide and caches identical searches within a run so redundant `ytsearch` calls do not self-throttle the same IP.
**X backend priority (bird first).** The default X backend chain is bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key). Cookies beat `XAI_API_KEY` when both are present. A leftover grok login never steals the X lane; see below.
@@ -186,6 +188,7 @@ BRAVE_API_KEY=<your-brave-key>
# Optional sources
SCRAPECREATORS_API_KEY=<your-scrapecreators-key>
INCLUDE_SOURCES=tiktok,instagram
+# LAST30DAYS_REDDIT_KEYLESS_RATE=1 # keyless reddit.com req/sec; lower = fewer 429s, slower runs
# Xiaohongshu is requested-only: run with --search xhs after starting a local
# browser-session service. Defaults probe localhost, then host.docker.internal.
# XIAOHONGSHU_API_BASE=http://localhost:18060
diff --git a/changelog.d/+fusion-keeps-enriched-copy.fixed.md b/changelog.d/+fusion-keeps-enriched-copy.fixed.md
new file mode 100644
index 00000000..2b3f3640
--- /dev/null
+++ b/changelog.d/+fusion-keeps-enriched-copy.fixed.md
@@ -0,0 +1 @@
+Fusion and report finalize now identify a thread by its normalized URL, not its per-stream item id. When the same Reddit thread arrives from two subquery streams (both labelled `R1`), the candidate keeps the copy that carries `top_comments`, `comment_insights`, and the verified counts instead of discarding it as a duplicate, and `items_by_source` holds one entry per thread. This is what silently emptied `## Top Community Comments` on multi-subquery runs.
diff --git a/changelog.d/+quiet-footer.changed.md b/changelog.d/+quiet-footer.changed.md
new file mode 100644
index 00000000..d3eede90
--- /dev/null
+++ b/changelog.d/+quiet-footer.changed.md
@@ -0,0 +1 @@
+The emoji-tree footer no longer appends `⚠ partial after N items: HTTP 429 ... (run doctor for fixes)` outcome text to any source line; source lines carry counts and engagement only. `--emit=compact` stdout also drops the `Some sources failed` / `Some sources returned partial results` warning lines and the `## Source Errors` block. The model-facing `## Partial Coverage` note stays, and the saved raw file, `--emit=json`, and `doctor --postmortem` keep full `source_status`, `warnings`, and `errors_by_source`.
diff --git a/changelog.d/+reddit-bot-comments.fixed.md b/changelog.d/+reddit-bot-comments.fixed.md
new file mode 100644
index 00000000..572011c2
--- /dev/null
+++ b/changelog.d/+reddit-bot-comments.fixed.md
@@ -0,0 +1 @@
+Keyless Reddit comment scraping now drops bot authors (RemindMeBot, AutoModerator, `WikiTextBot`-style camelCase names, and `-bot`/`_bot` suffixed accounts), so a "I will be messaging you in 3 days" reply can no longer occupy a Top Community Comments slot. Ordinary usernames ending in a lowercase "bot" (Talbot, abbot) are unaffected. Cherry-picked from [#1034](https://github.com/mvanhorn/last30days-skill/pull/1034) (rebase of [#907](https://github.com/mvanhorn/last30days-skill/pull/907)).
diff --git a/changelog.d/+reddit-engagement-floor.added.md b/changelog.d/+reddit-engagement-floor.added.md
new file mode 100644
index 00000000..baceec44
--- /dev/null
+++ b/changelog.d/+reddit-engagement-floor.added.md
@@ -0,0 +1 @@
+Reddit threads with the most upvotes and comments now keep their place: each Reddit stream holds slots for its top three on-topic threads by engagement before per-stream truncation, and the fused candidate pool reserves slots (quick 2, default 3, deep 4) for the highest-engagement entity-grounded Reddit candidates. A 16K-upvote thread with weak title overlap was previously cut behind one-upvote posts. Topics whose primary entity starts with a generic word ("ai", "new") require the higher 0.25 relevance floor for these slots.
diff --git a/changelog.d/+reddit-enrich-limits.changed.md b/changelog.d/+reddit-enrich-limits.changed.md
new file mode 100644
index 00000000..0f8aa3b1
--- /dev/null
+++ b/changelog.d/+reddit-enrich-limits.changed.md
@@ -0,0 +1 @@
+Keyless Reddit comment enrichment now covers 4 / 8 / 12 threads per subquery at quick / default / deep depth (was 3 / 5 / 8) and keeps up to 12 top comments per thread (was 10), now that repeat fetches are memoized and paced.
diff --git a/changelog.d/+reddit-ok-with-lane-detail.fixed.md b/changelog.d/+reddit-ok-with-lane-detail.fixed.md
new file mode 100644
index 00000000..06125a13
--- /dev/null
+++ b/changelog.d/+reddit-ok-with-lane-detail.fixed.md
@@ -0,0 +1 @@
+A source that delivered items but lost some sub-requests (a swallowed 429 or 403 on one lane) now records `ok` with a detail line such as `3 sub-requests rate-limited (HTTP 429)` instead of `partial`; `doctor --postmortem` shows that detail on the Succeeded line. Adapter-declared leg failures (for example a Perplexity `both` run whose agent leg failed) still brand the source partial.
diff --git a/changelog.d/+reddit-queue-aware-timeouts.fixed.md b/changelog.d/+reddit-queue-aware-timeouts.fixed.md
new file mode 100644
index 00000000..6ed618cb
--- /dev/null
+++ b/changelog.d/+reddit-queue-aware-timeouts.fixed.md
@@ -0,0 +1 @@
+Keyless Reddit RSS and listing fetches now size their per-future timeouts from the shared bucket's queue depth instead of a fixed 20 seconds. At 1 req/s with four subquery streams sharing the bucket, the fixed timeout expired while a fetch was still waiting for its token and the feed was silently dropped.
diff --git a/changelog.d/+reddit-ratelimit-reset.fixed.md b/changelog.d/+reddit-ratelimit-reset.fixed.md
new file mode 100644
index 00000000..f5fdce5b
--- /dev/null
+++ b/changelog.d/+reddit-ratelimit-reset.fixed.md
@@ -0,0 +1 @@
+Reddit 429 backoff now honours `x-ratelimit-reset`, not just `Retry-After`. Reddit's anonymous search/RSS endpoints reply to a 429 with `x-ratelimit-reset: 42` and no `Retry-After`, so the retry fell through to exponential backoff (3s, 5s, 9s) — every step shorter than the window Reddit actually requires. Each retry re-429'd, the budget drained, and Reddit was reported as a dead source when it was only being asked too early. Both `http.fetch_url` and `reddit_public` now read either header through the new `http.retry_delay_from_headers` helper.
diff --git a/changelog.d/+reddit-review-hardening.fixed.md b/changelog.d/+reddit-review-hardening.fixed.md
new file mode 100644
index 00000000..f650dc52
--- /dev/null
+++ b/changelog.d/+reddit-review-hardening.fixed.md
@@ -0,0 +1 @@
+Rate-limit retries are bounded: a `Retry-After` / `x-ratelimit-reset` wait is capped at 60 seconds and an epoch-style reset (GitHub) is converted to a delta, so a 429 can no longer park a worker or the main thread for minutes. The keyless Reddit memo elects one new owner when an in-flight fetch fails instead of letting every waiter refetch, its gate wait and the comment-enrichment budget account for the shared bucket's queue, the Reddit pool reservation survives a small pool crowded by many sources, stream keepers respect `--max-per-source`, a source whose swallowed sub-requests all 429ed is not retried against the same host and is reported as rate-limited rather than `no-results` when filtering leaves it empty.
diff --git a/changelog.d/+reddit-run-memo.fixed.md b/changelog.d/+reddit-run-memo.fixed.md
new file mode 100644
index 00000000..5d8516d1
--- /dev/null
+++ b/changelog.d/+reddit-run-memo.fixed.md
@@ -0,0 +1 @@
+Keyless Reddit GETs are memoized for the life of one command, and concurrent requesters for the same URL share the in-flight fetch. Subreddit listing partials, listing RSS feeds, arctic supplements, and shreddit comment pages were fetched once per subquery (four times on a typical run) because the Reddit lane is dispatched with the raw topic every time; a four-subquery run now issues roughly 50 reddit.com requests instead of ~184, which is what kept tripping the anonymous rate limit.
diff --git a/changelog.d/+source-outcome-swallowed-lane-failure.fixed.md b/changelog.d/+source-outcome-swallowed-lane-failure.fixed.md
new file mode 100644
index 00000000..e0f42a5b
--- /dev/null
+++ b/changelog.d/+source-outcome-swallowed-lane-failure.fixed.md
@@ -0,0 +1 @@
+Sources that return items are no longer branded `auth-failed` / `partial` when a swallowed lane-level HTTP failure (e.g. Reddit shreddit partials 403-ing on datacenter egress) is captured by the pipeline sink. The transport-failure outcome still surfaces when nothing was delivered, so `doctor` prescriptions are unaffected.
diff --git a/changelog.d/+top-comments-all-clusters.fixed.md b/changelog.d/+top-comments-all-clusters.fixed.md
new file mode 100644
index 00000000..eae07dff
--- /dev/null
+++ b/changelog.d/+top-comments-all-clusters.fixed.md
@@ -0,0 +1 @@
+`## Top Community Comments` and `## Best Takes` now draw from every cluster that clears the relevance floor, not only the eight clusters shown in `## Ranked Evidence Clusters`, so a top-voted comment on a lower-ranked thread still reaches the brief.
diff --git a/changelog.d/906.fixed.md b/changelog.d/906.fixed.md
new file mode 100644
index 00000000..b1366f54
--- /dev/null
+++ b/changelog.d/906.fixed.md
@@ -0,0 +1 @@
+Keyless Reddit comment-enrichment slots now go to the most-commented threads within each entity-priority tier, so a high-discussion thread no longer misses `## Top Community Comments` coverage while near-empty threads consume the scarce slots ([#906](https://github.com/mvanhorn/last30days-skill/issues/906)).
diff --git a/changelog.d/985.fixed.md b/changelog.d/985.fixed.md
new file mode 100644
index 00000000..2679a776
--- /dev/null
+++ b/changelog.d/985.fixed.md
@@ -0,0 +1 @@
+Keyless Reddit now paces unauthenticated reddit.com requests at 1 req/sec (configurable via `LAST30DAYS_REDDIT_KEYLESS_RATE`) and retries a 429'd RSS or listing sub-request once, so routine runs no longer drop those lanes as `partial` HTTP 429.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index ab5a395e..e21d8567 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -163,7 +163,7 @@ These LAWs dominate every other rule in this file. If you find yourself about to
**GENERAL nothing-solid floor.** If the `## Ranked Evidence Clusters` block says `Nothing solid this window`, the engine found items but every visible cluster failed the positive, non-entity-miss relevance floor. Treat that community evidence as absent: do not infer findings from its stats, quote its comments, or satisfy LAW 9 from rejected candidates. Build the `What I learned:` body only from supported Step 2 web supplements, if any, and say plainly that recent community evidence was insufficient without narrating engine mechanics. If the supplements are also insufficient, an honest short no-finding answer is the result; retain the engine footer and invitation.
-**Per-run source outcomes (doctor-aligned):** Read `## Partial Coverage` and `Report.source_status` before synthesizing. `no-results` means the source completed cleanly with zero matches. `partial`, `rate-limited`, `auth-failed`, `unreachable`, `timeout`, `schema-drift`, `skipped-unconfigured`, and `error` mean the run did not establish that the source was quiet. Never write "nothing on X/Reddit/YouTube" for those states; qualify the conclusion as partial coverage and rely only on evidence that was actually returned. The engine footer carries the user-visible outcome and `doctor` pointer, so do not invent a repair prescription in prose. Plain `doctor` predicts configuration health before a run; `source_status` reports what happened during this run, and `doctor --postmortem` reads that same `source_status` from the last run's cache to report what actually broke after the fact.
+**Per-run source outcomes (doctor-aligned):** Read `## Partial Coverage` and `Report.source_status` before synthesizing. `no-results` means the source completed cleanly with zero matches. `partial`, `rate-limited`, `auth-failed`, `unreachable`, `timeout`, `schema-drift`, `skipped-unconfigured`, and `error` mean the run did not establish that the source was quiet. Never write "nothing on X/Reddit/YouTube" for those states; qualify the conclusion as partial coverage and rely only on evidence that was actually returned. The engine footer carries counts only (no outcome text); the outcome lives in `## Partial Coverage` and in `doctor --postmortem`, so do not invent a repair prescription in prose and do not add one to the footer. Plain `doctor` predicts configuration health before a run; `source_status` reports what happened during this run, and `doctor --postmortem` reads that same `source_status` from the last run's cache to report what actually broke after the fact.
**Observed LAW 6 violation (2026-04-19, Hermes Agent Use Cases disaster):** two consecutive `/last30days Hermes Agent (Actual) Use Cases` runs returned the raw `## Ranked Evidence Clusters` block verbatim as user output, with 8 cluster entries carrying `(score N, M items, sources: ...)` tuples and `- Uncertainty: single-source` lines. Root cause: the prior canonical-boundary text said "Pass through the lines ABOVE this boundary verbatim," which the model scoped broadly to include the scratchpad. The current boundary text and this LAW 6 scope pass-through to the PASS-THROUGH FOOTER block only. A third run on the same topic framed as "Hermes Workflows" produced the correct `What I learned:` prose synthesis, which is the shape every run must produce.
@@ -2112,7 +2112,7 @@ Close with `I have all the links to the {N} {source list} I pulled from. Just as
**Before you display the synthesis to the user, verify ALL of the following. If any check fails AND the underlying data supports fixing it, regenerate the synthesis ONCE with the missing elements. If the data itself is absent (e.g., no Polymarket markets on this topic), skip that check silently.**
1. **Bold headlines present.** Every narrative paragraph in "What I learned" starts with `**Headline phrase** -` (single hyphen with spaces, NOT em-dash). If any paragraph opens with plain prose, regenerate with bold headlines.
-2. **Per-source emoji headers in the stats footer.** Every active source returned by the engine has a `├─` or `└─` line with its emoji, counts, and engagement numbers. No active source is silently dropped; no source with 0 results is displayed.
+2. **Per-source emoji headers in the stats footer.** Every active source returned by the engine has a `├─` or `└─` line with its emoji, counts, and engagement numbers. No active source is silently dropped; no source with 0 results is displayed; no `⚠` or outcome text appears on any line.
3. **Community voice woven in (LAW 9).** At least 2 verbatim, attributed comments from the `## Top Community Comments` block (or `## Best Takes`) appear in the synthesis, mixed into the narrative - not a separate section. When a comment is inline-linked on a hidden-link host, its URL is copied verbatim from the block (never reconstructed); on a visible-URL host the attribution stays plain and the URL is left to the saved raw file. If the block has comments and your draft has zero, regenerate. Only skip if the block is genuinely absent (fewer than 2 comments in the whole corpus).
3b. **No tooling meta-commentary (LAW 9).** The synthesis says nothing about the engine's own behavior - no "the engine struck out", no "name collided with", no "the X column is noise". If present, strip it and present only what is true about the subject.
4. **Polymarket block present if markets were returned.** If the engine surfaced Polymarket markets, the synthesis includes specific percentages and directional movement. If no markets were surfaced, skip.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 99510391..a0409f6d 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -2914,6 +2914,9 @@ def _main(
)
return 2
config = env.get_config(policy=_config_policy_for_args(args, topic, extra_argv))
+ # 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()
resolved_corpus_dirs = corpus.resolve_directories(
args.corpus, config.get("LAST30DAYS_CORPUS_DIRS")
)
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.py
index 75d99392..786e0fe5 100644
--- a/skills/last30days/scripts/lib/doctor.py
+++ b/skills/last30days/scripts/lib/doctor.py
@@ -1410,9 +1410,15 @@ def render_postmortem_text(pm: Dict[str, Any]) -> str:
lines.append(f" fix: {outcome['fix_hint']}")
if succeeded:
lines.append("")
- names = ", ".join(
- f"{s} ({o.get('items_returned') or 0})" for s, o in succeeded
- )
+ def _succeeded_label(source: str, outcome: Dict[str, Any]) -> str:
+ count = outcome.get("items_returned") or 0
+ detail = outcome.get("detail")
+ if detail:
+ noun = "item" if count == 1 else "items"
+ return f"{source} ({count} {noun}; {detail})"
+ return f"{source} ({count})"
+
+ names = ", ".join(_succeeded_label(s, o) for s, o in succeeded)
lines.append(f"Succeeded: {names}")
if skipped:
lines.append("")
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 9004ced2..6527bfb7 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -471,6 +471,9 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('LAST30DAYS_X_MODEL', None),
('LAST30DAYS_X_BACKEND', None),
('LAST30DAYS_REDDIT_BACKEND', None),
+ # Keyless reddit.com token-bucket rate (req/sec). http.py reads it
+ # from os.environ on each acquire, so .env values are exported below.
+ ('LAST30DAYS_REDDIT_KEYLESS_RATE', None),
# Doctor cache freshness window in seconds (doctor --cached).
('LAST30DAYS_DOCTOR_TTL', None),
# Per-source deadline (seconds) for doctor --probe live checks.
@@ -599,6 +602,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
'LAST30DAYS_YT_SUB_LANGS',
'LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT',
'LAST30DAYS_YT_SEARCH_TIMEOUT',
+ 'LAST30DAYS_REDDIT_KEYLESS_RATE',
):
if config.get(key):
os.environ.setdefault(key, config[key])
diff --git a/skills/last30days/scripts/lib/fusion.py b/skills/last30days/scripts/lib/fusion.py
index 04a8f3b2..29c8c593 100644
--- a/skills/last30days/scripts/lib/fusion.py
+++ b/skills/last30days/scripts/lib/fusion.py
@@ -47,8 +47,140 @@ def candidate_key(item: schema.SourceItem) -> str:
return f"{item.source}:{item.item_id}"
+# Enrichment that one copy of a thread may carry and another may lack. When
+# the same URL arrives from two subquery streams (each stream enriches its own
+# top-N), the copy that won a comment slot must survive de-duplication.
+_ENRICHMENT_KEYS = (
+ "top_comments",
+ "comment_insights",
+ "transcript_highlights",
+ "transcript_snippet",
+ "transcript",
+)
+
+
+def merge_source_items(existing: schema.SourceItem, incoming: schema.SourceItem) -> schema.SourceItem:
+ """Fold ``incoming``'s enrichment and counts into ``existing`` (same thread).
+
+ Keeps the richer value per field: an enrichment list the existing copy
+ lacks (or a longer one), the larger numeric engagement counters, and the
+ longer body/snippet. Mutates and returns ``existing``.
+ """
+ for key in _ENRICHMENT_KEYS:
+ theirs = incoming.metadata.get(key)
+ if not theirs:
+ continue
+ mine = existing.metadata.get(key)
+ if not mine or (isinstance(theirs, list) and isinstance(mine, list) and len(theirs) > len(mine)):
+ existing.metadata[key] = theirs
+ for field_name, value in (incoming.engagement or {}).items():
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ if existing.engagement.get(field_name) is None and value is not None:
+ existing.engagement[field_name] = value
+ continue
+ current = existing.engagement.get(field_name)
+ if not isinstance(current, (int, float)) or isinstance(current, bool) or value > current:
+ existing.engagement[field_name] = value
+ if len(incoming.body or "") > len(existing.body or ""):
+ existing.body = incoming.body
+ if len(incoming.snippet or "") > len(existing.snippet or ""):
+ existing.snippet = incoming.snippet
+ return existing
+
+
+def collapse_duplicate_urls(items: list[schema.SourceItem]) -> list[schema.SourceItem]:
+ """Collapse same-source, same-URL copies, keeping order and merging enrichment.
+
+ Per-stream item ids (``R1``, ``X1``) collide across subqueries, so identity
+ is the normalized URL, not the id. The first occurrence stays in place and
+ absorbs later copies via :func:`merge_source_items`.
+ """
+ first_by_key: dict[tuple[str, str], schema.SourceItem] = {}
+ kept: list[schema.SourceItem] = []
+ for item in items:
+ key = (item.source, candidate_key(item))
+ existing = first_by_key.get(key)
+ if existing is None:
+ first_by_key[key] = item
+ kept.append(item)
+ else:
+ merge_source_items(existing, item)
+ return kept
+
+
_DIVERSITY_RELEVANCE_THRESHOLD = 0.25
+# Reddit engagement reservation: pool slots held for the highest-engagement
+# entity-grounded in-window Reddit candidates, scaled by pool size (quick 15
+# -> 2, default 40 -> 3, deep 60 -> 4). The fused order is RRF-first and each
+# stream is relevance-first, so the month's most-discussed on-topic thread can
+# otherwise lose its slot to a one-upvote post with better title overlap.
+_REDDIT_RESERVE_BY_POOL = ((15, 2), (40, 3))
+_REDDIT_RESERVE_MAX = 4
+
+
+def _reddit_reserve_for(pool_limit: int) -> int:
+ for ceiling, reserve in _REDDIT_RESERVE_BY_POOL:
+ if pool_limit <= ceiling:
+ return reserve
+ return _REDDIT_RESERVE_MAX
+
+
+def relevance_floor_for_entity(entity: str) -> float:
+ """Relevance a Reddit thread must clear to earn a reservation or keeper slot.
+
+ Grounding keys on the entity's head token (see ``rerank._entity_grounded``).
+ A generic head ("ai", "x", "new") matches almost anything, so the floor
+ rises to the diversity threshold; a distinctive head keeps the shared
+ ``RELEVANCE_FLOOR``.
+ """
+ from . import relevance
+
+ head = (entity or "").lower().split()[:1]
+ if not head:
+ return relevance.RELEVANCE_FLOOR
+ token = head[0]
+ generic = (
+ len(token) <= 2
+ or token in relevance.STOPWORDS
+ or token in relevance.LOW_SIGNAL_QUERY_TOKENS
+ )
+ return _DIVERSITY_RELEVANCE_THRESHOLD if generic else relevance.RELEVANCE_FLOOR
+
+
+def raw_engagement(item: schema.SourceItem) -> float:
+ """Upvotes plus comments as a plain number, for engagement-first ordering."""
+ eng = item.engagement or {}
+ total = 0.0
+ for key in ("score", "num_comments"):
+ value = eng.get(key)
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ total += float(value)
+ return total
+
+
+def reddit_thread_qualifies(
+ item: schema.SourceItem,
+ entity: str,
+ floor: float,
+ relevance: float | None = None,
+) -> bool:
+ """On-topic enough for an engagement slot: clears the floor and names the entity.
+
+ ``relevance`` overrides the item's own ``local_relevance`` (a fused
+ candidate carries the max across its copies).
+ """
+ from . import rerank
+
+ score = relevance if relevance is not None else (item.local_relevance or 0.0)
+ if score < floor:
+ return False
+ if raw_engagement(item) <= 0:
+ return False
+ if not entity:
+ return True
+ return rerank._entity_grounded(f"{item.title or ''} {item.body or ''}", entity)
+
# Per-author cap: no single author/handle should dominate the pool.
_MAX_ITEMS_PER_AUTHOR = 3
@@ -109,15 +241,44 @@ def _apply_per_author_cap(
return result
+def _reddit_engagement_reservation(
+ fused: list[schema.Candidate],
+ reserve: int,
+ entity: str,
+) -> list[schema.Candidate]:
+ """The *reserve* highest-engagement Reddit candidates that are in-window
+ and on-topic, in engagement order."""
+ if reserve <= 0:
+ return []
+ floor = relevance_floor_for_entity(entity)
+ eligible = []
+ for c in fused:
+ if c.source != "reddit" or schema.candidate_out_of_window(c):
+ continue
+ reddit_items = [it for it in c.source_items if it.source == "reddit"]
+ if not reddit_items:
+ continue
+ best = max(reddit_items, key=raw_engagement)
+ relevance = max(c.local_relevance or 0.0, best.local_relevance or 0.0)
+ if not reddit_thread_qualifies(best, entity, floor, relevance=relevance):
+ continue
+ eligible.append((raw_engagement(best), c))
+ eligible.sort(key=lambda pair: -pair[0])
+ return [c for _, c in eligible[:reserve]]
+
+
def _diversify_pool(
fused: list[schema.Candidate],
pool_limit: int,
min_per_source: int = 2,
+ entity: str = "",
) -> list[schema.Candidate]:
"""Ensure at least *min_per_source* items per qualifying source survive truncation.
Sources only qualify for reserved slots if their best item exceeds
the relevance threshold. Low-relevance sources compete on merit only.
+ Reddit additionally gets an engagement reservation (see
+ ``_reddit_reserve_for``) for its most-discussed on-topic threads.
"""
max_relevance: dict[str, float] = {}
for c in fused:
@@ -125,16 +286,22 @@ def _diversify_pool(
if c.local_relevance > current:
max_relevance[c.source] = c.local_relevance
+ protected = _reddit_engagement_reservation(fused, _reddit_reserve_for(pool_limit), entity)
+ protected_ids = {c.candidate_id for c in protected}
+ pool: list[schema.Candidate] = list(protected)
+ seen = set(protected_ids)
reserved: dict[str, list[schema.Candidate]] = {}
remainder: list[schema.Candidate] = []
for c in fused:
+ if c.candidate_id in seen:
+ continue
qualifies = max_relevance.get(c.source, 0.0) >= _DIVERSITY_RELEVANCE_THRESHOLD
bucket = reserved.setdefault(c.source, [])
if qualifies and len(bucket) < min_per_source:
bucket.append(c)
else:
remainder.append(c)
- pool = [c for per_source in reserved.values() for c in per_source]
+ pool.extend(c for per_source in reserved.values() for c in per_source)
seen = {c.candidate_id for c in pool}
for c in remainder:
if len(pool) >= pool_limit:
@@ -142,6 +309,20 @@ def _diversify_pool(
if c.candidate_id not in seen:
pool.append(c)
pool.sort(key=_candidate_sort_key)
+ if len(pool) > pool_limit:
+ # The per-source buckets can overfill a small pool. The Reddit
+ # reservation is low-RRF by construction, so a plain slice would cut
+ # exactly the threads it exists to keep: trim unprotected candidates
+ # from the sorted tail instead.
+ keep_unprotected = pool_limit - len(protected_ids)
+ trimmed: list[schema.Candidate] = []
+ for c in pool:
+ if c.candidate_id in protected_ids:
+ trimmed.append(c)
+ elif keep_unprotected > 0:
+ trimmed.append(c)
+ keep_unprotected -= 1
+ pool = trimmed
return pool[:pool_limit]
@@ -165,8 +346,10 @@ def weighted_rrf(
"""
subqueries = {subquery.label: subquery for subquery in plan.subqueries}
candidates: dict[str, schema.Candidate] = {}
- # Track (source, item_id) pairs already attached to each candidate for O(1) dedup.
- seen_source_items: dict[str, set[tuple[str, str]]] = {}
+ # Track source items already attached to each candidate, keyed by
+ # (source, normalized URL): per-stream ids collide across subqueries, and
+ # a repeat copy may carry enrichment the first one lacks.
+ seen_source_items: dict[str, dict[tuple[str, str], schema.SourceItem]] = {}
for (label, source), items in streams.items():
subquery = subqueries[label]
@@ -210,7 +393,7 @@ def weighted_rrf(
source_items=[item],
metadata=candidate_metadata,
)
- seen_source_items[key] = {(item.source, item.item_id)}
+ seen_source_items[key] = {(item.source, candidate_key(item)): item}
continue
candidate = candidates[key]
@@ -236,10 +419,13 @@ def weighted_rrf(
candidate.subquery_labels.append(label)
if item.source not in candidate.sources:
candidate.sources.append(item.source)
- source_item_key = (item.source, item.item_id)
- if source_item_key not in seen_source_items[key]:
- seen_source_items[key].add(source_item_key)
+ source_item_key = (item.source, candidate_key(item))
+ existing_item = seen_source_items[key].get(source_item_key)
+ if existing_item is None:
+ seen_source_items[key][source_item_key] = item
candidate.source_items.append(item)
+ else:
+ merge_source_items(existing_item, item)
candidate.metadata.setdefault("provenance", []).append(
{
"source": source,
@@ -258,4 +444,7 @@ def weighted_rrf(
fused = sorted(candidates.values(), key=_candidate_sort_key)
fused = _apply_per_author_cap(fused, first_party_handles=first_party_handles)
- return _diversify_pool(fused, pool_limit)
+ from . import rerank
+
+ entity = rerank._primary_entity(plan.raw_topic or "") if plan.raw_topic else ""
+ return _diversify_pool(fused, pool_limit, entity=entity)
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index 7f1e21c0..c419a874 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -1,7 +1,10 @@
"""HTTP utilities for last30days skill (stdlib only)."""
import json
+from collections import OrderedDict
+import math
import os
+import random
import re
import socket
import sys
@@ -30,6 +33,54 @@ def log(msg: str):
MAX_RETRIES = 5
MAX_429_RETRIES = 2
RETRY_DELAY = 2.0
+
+
+# Longest a 429 retry may sleep on any host. Reddit's x-ratelimit-reset can say
+# 540s and GitHub's is an epoch timestamp; neither is worth parking a worker
+# (or the main thread) for. Past this bound the retry is not worth taking, so
+# the caller's own fallback backoff applies and the request fails fast.
+MAX_RETRY_DELAY_SECONDS = 60.0
+# A reset value this large is an absolute epoch timestamp, not delta-seconds.
+_EPOCH_RESET_THRESHOLD = 100_000_000.0
+
+
+def 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
+ anonymous 429 with ``x-ratelimit-reset`` (seconds until the window rolls) and
+ no ``Retry-After`` at all::
+
+ HTTP/2 429
+ x-ratelimit-used: 1
+ x-ratelimit-remaining: 0.0
+ x-ratelimit-reset: 42
+
+ Reading only ``Retry-After`` means the caller falls back to exponential
+ backoff -- 3s, 5s, 9s -- every one of which is shorter than the ~42s Reddit
+ actually requires. Each retry re-429s, the budget drains, and the source is
+ reported dead when it was merely early. Honouring the reset header turns a
+ guaranteed zero into a result at the cost of one wait.
+
+ Returns ``fallback`` when neither header is present or parseable.
+ """
+ if not headers:
+ return fallback
+ for name in ("Retry-After", "x-ratelimit-reset"):
+ raw = headers.get(name)
+ if raw is None:
+ continue
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ continue
+ if value >= _EPOCH_RESET_THRESHOLD:
+ # GitHub-style absolute reset time.
+ value = value - time.time()
+ if value > 0:
+ return min(value, MAX_RETRY_DELAY_SECONDS)
+ return fallback
+
# DNS resolution failures (gaierror) are transient — typically resolved by a
# brief backoff and retry. Use a dedicated minimum attempt count + exponential
# delays (1s, 2s, 4s) so callers that pass a small `retries` value still get a
@@ -737,15 +788,12 @@ def request(
# failures get the widened `effective_retries` budget.
if attempt < retries - 1:
if e.code == 429:
- # Respect Retry-After header, fall back to exponential backoff
- retry_after = e.headers.get("Retry-After") if hasattr(e, 'headers') else None
- if retry_after:
- try:
- delay = float(retry_after)
- except ValueError:
- delay = RETRY_DELAY * (2 ** attempt) + 1
- else:
- delay = RETRY_DELAY * (2 ** attempt) + 1 # 3s, 5s, 9s...
+ # Respect Retry-After or x-ratelimit-reset (Reddit sends the
+ # latter), falling back to exponential backoff: 3s, 5s, 9s...
+ delay = retry_delay_from_headers(
+ getattr(e, "headers", None),
+ RETRY_DELAY * (2 ** attempt) + 1,
+ )
log(f"Rate limited (429). Waiting {delay:.1f}s before retry {attempt + 2}/{retries}")
else:
delay = RETRY_DELAY * (2 ** attempt)
@@ -913,28 +961,161 @@ class RateLimiter:
self._tokens = float(self.capacity)
self._last = time.monotonic()
self._lock = threading.Lock()
+ # Threads currently blocked in acquire(). Callers that wait on a batch
+ # of throttled futures size their timeouts from this queue depth.
+ self._waiting = 0
+
+ @property
+ def waiting(self) -> int:
+ """Threads currently blocked in :meth:`acquire`."""
+ with self._lock:
+ return self._waiting
def acquire(self) -> None:
"""Consume one token, blocking only when the bucket is empty."""
- while True:
- with self._lock:
- now = time.monotonic()
- # Clamp elapsed to >= 0: a backward clock reading must never
- # drive tokens negative (which would spin this loop forever).
- elapsed = max(0.0, now - self._last)
- self._tokens = min(self.capacity, self._tokens + elapsed * self.rate)
- self._last = now
- if self._tokens >= 1.0:
- self._tokens -= 1.0
- return
- wait = (1.0 - self._tokens) / self.rate
- time.sleep(wait)
+ queued = False
+ try:
+ while True:
+ with self._lock:
+ now = time.monotonic()
+ # Clamp elapsed to >= 0: a backward clock reading must never
+ # drive tokens negative (which would spin this loop forever).
+ elapsed = max(0.0, now - self._last)
+ self._tokens = min(self.capacity, self._tokens + elapsed * self.rate)
+ self._last = now
+ if self._tokens >= 1.0:
+ self._tokens -= 1.0
+ return
+ if not queued:
+ self._waiting += 1
+ queued = True
+ wait = (1.0 - self._tokens) / self.rate
+ time.sleep(wait)
+ finally:
+ if queued:
+ with self._lock:
+ self._waiting -= 1
# Shared across all keyless Reddit tiers (RSS, listing, shreddit) so their
# combined fan-out is throttled as one family. Burst lets the parallel
# enrichment workers proceed; sustained rate caps the stampede.
-REDDIT_KEYLESS_LIMITER = RateLimiter(rate_per_sec=5.0, burst=5)
+# 1 req/sec is slow enough that home IPs survive RSS + 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
+DEFAULT_REDDIT_KEYLESS_BURST = 2
+_REDDIT_429_RETRY_SLEEP_SEC = 1.0
+_REDDIT_429_RETRY_JITTER_SEC = 0.5
+
+
+def parse_reddit_keyless_rate(raw: Optional[str]) -> float:
+ """Parse LAST30DAYS_REDDIT_KEYLESS_RATE; invalid/non-positive -> default."""
+ text = (raw or "").strip()
+ if not text:
+ return DEFAULT_REDDIT_KEYLESS_RATE
+ try:
+ rate = float(text)
+ except (TypeError, ValueError):
+ return DEFAULT_REDDIT_KEYLESS_RATE
+ if not math.isfinite(rate) or rate <= 0:
+ return DEFAULT_REDDIT_KEYLESS_RATE
+ return rate
+
+
+def make_reddit_keyless_limiter(
+ environ: Optional[Dict[str, str]] = None,
+) -> RateLimiter:
+ envmap = os.environ if environ is None else environ
+ return RateLimiter(
+ rate_per_sec=parse_reddit_keyless_rate(envmap.get(REDDIT_KEYLESS_RATE_ENV)),
+ burst=DEFAULT_REDDIT_KEYLESS_BURST,
+ )
+
+
+REDDIT_KEYLESS_LIMITER = make_reddit_keyless_limiter()
+
+
+def _sync_reddit_keyless_rate() -> None:
+ """Apply a process-env override without resetting in-flight tokens."""
+ rate = parse_reddit_keyless_rate(os.environ.get(REDDIT_KEYLESS_RATE_ENV))
+ if REDDIT_KEYLESS_LIMITER.rate != rate:
+ REDDIT_KEYLESS_LIMITER.rate = rate
+
+
+def _failures_are_429(failures: list[HTTPError]) -> bool:
+ if not failures:
+ return False
+ last = failures[-1]
+ return last.status_code == 429 or last.outcome_state == health.RATE_LIMITED
+
+
+def _sleep_reddit_429_retry() -> None:
+ """Short jittered pause before the single in-lane 429 retry."""
+ time.sleep(
+ _REDDIT_429_RETRY_SLEEP_SEC
+ + random.uniform(0.0, _REDDIT_429_RETRY_JITTER_SEC)
+ )
+
+
+# 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.
+# 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
+# subquery streams start at once, so a result-only cache would miss).
+REDDIT_KEYLESS_MEMO_MAX = 512
+_REDDIT_KEYLESS_MEMO: "OrderedDict[str, str]" = OrderedDict()
+_REDDIT_KEYLESS_INFLIGHT: Dict[str, threading.Event] = {}
+_REDDIT_KEYLESS_MEMO_LOCK = threading.Lock()
+
+
+# Queue depth only counts threads already blocked in acquire(). The other
+# lanes' workers submit their requests as they go, so a batch's last fetch can
+# start well after the depth seen at wait time. This flat allowance covers
+# that (the 2026-08-31 smoke lost three feeds at ~35s with the depth term
+# alone; a full run's ~50 distinct keyless requests take ~50s at 1 req/s).
+REDDIT_KEYLESS_CONTENTION_SECONDS = 45.0
+
+
+def reddit_keyless_wait_allowance(batch_size: int) -> float:
+ """Seconds a batch of *batch_size* throttled fetches may spend waiting for tokens.
+
+ Every keyless Reddit lane in a run shares one bucket, so a lane's futures
+ can sit behind other lanes' requests before their own fetch starts. Size
+ per-future result timeouts as ``base + this`` instead of a fixed number;
+ at 1 req/s a fixed 20-second timeout expired on real runs while the fetch
+ was still queued (issue #985 follow-up).
+ """
+ _sync_reddit_keyless_rate()
+ limiter = REDDIT_KEYLESS_LIMITER
+ rate = limiter.rate if limiter.rate > 0 else 1.0
+ return (limiter.waiting + max(0, batch_size)) / rate + REDDIT_KEYLESS_CONTENTION_SECONDS
+
+
+def reset_reddit_keyless_memo() -> None:
+ """Forget memoized keyless Reddit bodies. Called once per command, and by tests."""
+ with _REDDIT_KEYLESS_MEMO_LOCK:
+ _REDDIT_KEYLESS_MEMO.clear()
+ _REDDIT_KEYLESS_INFLIGHT.clear()
+
+
+def _reddit_memo_get(url: str) -> Optional[str]:
+ with _REDDIT_KEYLESS_MEMO_LOCK:
+ text = _REDDIT_KEYLESS_MEMO.get(url)
+ if text is not None:
+ _REDDIT_KEYLESS_MEMO.move_to_end(url)
+ return text
+
+
+def _reddit_memo_put(url: str, text: str) -> None:
+ with _REDDIT_KEYLESS_MEMO_LOCK:
+ _REDDIT_KEYLESS_MEMO[url] = text
+ _REDDIT_KEYLESS_MEMO.move_to_end(url)
+ while len(_REDDIT_KEYLESS_MEMO) > REDDIT_KEYLESS_MEMO_MAX:
+ _REDDIT_KEYLESS_MEMO.popitem(last=False)
def reddit_keyless_get_text(
@@ -944,14 +1125,98 @@ def reddit_keyless_get_text(
accept: str = "*/*",
headers: Optional[Dict[str, str]] = None,
) -> Optional[str]:
- """get_text for the keyless Reddit tiers, throttled by a shared limiter.
+ """get_text for the keyless Reddit tiers, memoized per run and throttled.
- Same contract as :func:`get_text` (returns None on any failure) but spaces
- requests via :data:`REDDIT_KEYLESS_LIMITER` so a broad multi-query run does
- not stampede Reddit's keyless endpoints and trip blocks.
+ Same contract as :func:`get_text` (returns None on any failure) but a URL
+ already fetched this command is served from the run memo without spending
+ a limiter token, concurrent requesters for one URL share the in-flight
+ fetch, and cold fetches are spaced via :data:`REDDIT_KEYLESS_LIMITER` so a
+ broad multi-query run does not stampede Reddit's keyless endpoints.
"""
- REDDIT_KEYLESS_LIMITER.acquire()
- return get_text(url, timeout=timeout, retries=retries, accept=accept, headers=headers)
+ cached = _reddit_memo_get(url)
+ if cached is not None:
+ return cached
+ # Elect one owner per URL. A waiter whose owner failed re-enters the
+ # election rather than fetching un-gated, so a failed fetch costs one
+ # retry for the whole group, not one per waiter.
+ for _round in range(3):
+ with _REDDIT_KEYLESS_MEMO_LOCK:
+ cached = _REDDIT_KEYLESS_MEMO.get(url)
+ if cached is not None:
+ return cached
+ gate = _REDDIT_KEYLESS_INFLIGHT.get(url)
+ owner = gate is None
+ if owner:
+ gate = threading.Event()
+ _REDDIT_KEYLESS_INFLIGHT[url] = gate
+ if owner:
+ break
+ # The owner may itself be queued in the shared bucket; wait for that
+ # queue, not just for one socket timeout.
+ gate.wait(
+ timeout=timeout * max(1, retries) + reddit_keyless_wait_allowance(1)
+ )
+ cached = _reddit_memo_get(url)
+ if cached is not None:
+ return cached
+ else:
+ # Three failed owners in a row: give up quietly rather than pile on.
+ return None
+ try:
+ _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:
+ _reddit_memo_put(url, text)
+ return text
+ finally:
+ with _REDDIT_KEYLESS_MEMO_LOCK:
+ _REDDIT_KEYLESS_INFLIGHT.pop(url, None)
+ gate.set()
+
+
+def reddit_keyless_get_text_retry_429(
+ url: str,
+ timeout: int = DEFAULT_TIMEOUT,
+ accept: str = "*/*",
+ headers: Optional[Dict[str, str]] = None,
+) -> tuple[Optional[str], Optional[str]]:
+ """Limiter-throttled GET with one extra limiter-respecting retry on 429.
+
+ Returns ``(body, error)``. The first attempt is captured locally so a
+ recovered 429 is not left in the pipeline sink. A second 429, or any
+ non-429 miss, is recorded as before. Internal ``get_text`` retries are
+ skipped (``retries=1``) so the in-lane retry is the one that re-acquires
+ the bucket.
+ """
+ # retries=1 on purpose: letting request() sleep out a 42-60s
+ # x-ratelimit-reset inside a lane worker starves the whole batch (the
+ # 2026-08-31 smoke lost 14 feeds to future timeouts with retries=2 versus
+ # 6 with 1). A keyless 429 fails fast, the lane retries once after a short
+ # jittered pause through the bucket, and the memo keeps the other streams
+ # from re-requesting the same URL.
+ kwargs: Dict[str, Any] = {
+ "timeout": timeout,
+ "retries": 1,
+ "accept": accept,
+ "headers": headers,
+ }
+ with capture_failures() as first:
+ text = reddit_keyless_get_text(url, **kwargs)
+ if text is not None:
+ return text, None
+ if _failures_are_429(first):
+ _sleep_reddit_429_retry()
+ with tee_failures() as second:
+ text = reddit_keyless_get_text(url, **kwargs)
+ if text is not None:
+ return text, None
+ err = second[-1] if second else (first[-1] if first else None)
+ return None, str(err) if err is not None else "no response"
+ for err in first:
+ _record_failure(err)
+ err = first[-1] if first else None
+ return None, str(err) if err is not None else "no response"
def scrapecreators_headers(token: str) -> Dict[str, str]:
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 4b04f886..731da254 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -77,7 +77,8 @@ from . import (
youtube_yt,
)
from .cluster import cluster_candidates
-from .fusion import weighted_rrf
+from . import fusion
+from .fusion import collapse_duplicate_urls, weighted_rrf
DISCOVERY_SOURCES = ("reddit", "hackernews", "digg", "x")
_DISCOVERY_GENERIC_DOMAIN_TERMS = {
@@ -2465,6 +2466,16 @@ def run(
outcome_note["detail"],
attempted=outcome_note.get("attempted", True),
)
+ if isinstance(artifact, dict) and artifact.get("_source_outcome_detail"):
+ artifact = dict(artifact)
+ lane_state = artifact.pop("_source_outcome_detail_state", None)
+ bundle.record_detail(
+ source, artifact.pop("_source_outcome_detail"), state=lane_state
+ )
+ if lane_state == health.RATE_LIMITED:
+ # Do not re-fan-out against a host still inside its window.
+ with rate_limit_lock:
+ rate_limited_sources.add(source)
normalized = _normalize_score_dedupe(
source, raw_items, from_date, to_date,
freshness_mode=plan.freshness_mode,
@@ -2478,7 +2489,9 @@ def run(
# snapshot of open roles, and truncating it to the default 12 drops
# strategic postings (the whole point of hiring-signals coverage).
if source != "jobs":
- normalized = normalized[: settings["per_stream_limit"]]
+ normalized = _apply_reddit_stream_keepers(
+ source, normalized, settings["per_stream_limit"], topic
+ )
bundle.add_items(subquery.label, source, normalized)
if artifact:
bundle.artifacts.setdefault("grounding", []).append(artifact)
@@ -2915,6 +2928,49 @@ def _batch_subject_handles(raw_items: list[dict], *, top_n: int = 2) -> set[str]
return {handle for handle, _ in counts.most_common(top_n)}
+# Reddit engagement keepers: per stream, the top-N threads by upvotes plus
+# comments that clear the relevance floor and name the primary entity survive
+# per_stream_limit truncation even when their local rank score is low. The
+# stream order is 65% title relevance, so the month's most-discussed on-topic
+# thread (16K upvotes, 0.19 relevance) was otherwise cut behind one-upvote
+# posts with better title overlap.
+REDDIT_STREAM_KEEPERS = 3
+
+
+def _apply_reddit_stream_keepers(
+ source: str,
+ items: list[schema.SourceItem],
+ limit: int,
+ topic: str,
+) -> list[schema.SourceItem]:
+ """Truncate a stream to *limit*, holding slots for Reddit engagement keepers."""
+ kept = list(items[:limit])
+ if source != "reddit" or len(items) <= limit:
+ return kept
+ entity = rerank._primary_entity(topic or "") if topic else ""
+ floor = fusion.relevance_floor_for_entity(entity)
+ keepers = [
+ item
+ for item in sorted(items, key=fusion.raw_engagement, reverse=True)
+ if fusion.reddit_thread_qualifies(item, entity, floor)
+ ][:REDDIT_STREAM_KEEPERS]
+ keeper_ids = {id(item) for item in keepers}
+ for keeper in keepers:
+ if any(item is keeper for item in kept):
+ continue
+ # Displace the lowest-ranked non-keeper so the slice stays at limit;
+ # when the slice is already all keepers there is nothing to trade.
+ displaced = False
+ for index in range(len(kept) - 1, -1, -1):
+ if id(kept[index]) not in keeper_ids:
+ del kept[index]
+ displaced = True
+ break
+ if displaced or len(kept) < limit:
+ kept.append(keeper)
+ return kept[:limit]
+
+
def _normalize_score_dedupe(
source: str,
raw_items: list[dict],
@@ -2987,6 +3043,10 @@ def _finalize_items_by_source(
finalized = {}
for source, items in items_by_source_raw.items():
items = sorted(items, key=lambda item: item.local_rank_score or 0.0, reverse=True)
+ # Same thread from two subquery streams: fold the enriched copy into
+ # the first before the text-similarity dedupe, which would otherwise
+ # keep whichever copy ranked higher and drop its comments.
+ items = collapse_duplicate_urls(items)
items = dedupe.dedupe_items(items)
enrichment_request = {
"source": source,
@@ -3375,6 +3435,35 @@ def _legacy_artifact_outcome(
return None
+def _summarize_lane_failures(failures: list[http.HTTPError]) -> str:
+ """One line naming what a source lost to swallowed sub-request failures.
+
+ ``"3 sub-requests rate-limited (HTTP 429); 1 sub-request blocked (HTTP 403)"``.
+ Used as ``SourceOutcome.detail`` on a source that still delivered items,
+ so the loss is visible to ``doctor --postmortem`` without branding the
+ source partial (issue #985 wording; PR #959 semantics).
+ """
+ counts: dict[tuple[str, int | None], int] = {}
+ for failure in failures:
+ state = getattr(failure, "outcome_state", None) or health.ERROR
+ code = getattr(failure, "status_code", None)
+ counts[(state, code)] = counts.get((state, code), 0) + 1
+ labels = {
+ health.RATE_LIMITED: "rate-limited",
+ health.AUTH_FAILED: "blocked",
+ health.TIMEOUT: "timed out",
+ health.UNREACHABLE: "unreachable",
+ health.SCHEMA_DRIFT: "returned an unexpected shape",
+ }
+ parts = []
+ for (state, code), n in sorted(counts.items(), key=lambda kv: -kv[1]):
+ noun = "sub-request" if n == 1 else "sub-requests"
+ label = labels.get(state, "failed")
+ suffix = f" (HTTP {code})" if code else ""
+ parts.append(f"{n} {noun} {label}{suffix}")
+ return "; ".join(parts)
+
+
def _resolve_stream_outcome(
source: str,
artifact: Any,
@@ -3421,7 +3510,7 @@ def _finalize_source_status(
detail = None
fix_hint = None
elif state == health.OK and not count:
- state = schema.NO_RESULTS
+ state = outcome.lane_failure_state or schema.NO_RESULTS
elif state == schema.PARTIAL and not count:
state = http.classify_failure(message=detail or "")
finalized[source] = schema.SourceOutcome(
@@ -3432,6 +3521,7 @@ def _finalize_source_status(
detail=detail,
at=outcome.at,
fix_hint=fix_hint,
+ lane_failure_state=outcome.lane_failure_state,
)
return finalized
@@ -3992,6 +4082,8 @@ def _retry_thin_sources(
skip_amazon_enrichment=True,
)
outcome_note = artifact.get("_source_outcome") if isinstance(artifact, dict) else None
+ detail_note = artifact.get("_source_outcome_detail") if isinstance(artifact, dict) else None
+ detail_state = artifact.get("_source_outcome_detail_state") if isinstance(artifact, dict) else None
normalized = _normalize_score_dedupe(
source,
raw_items,
@@ -4008,8 +4100,11 @@ def _retry_thin_sources(
defer_relevance_prune=(source == "x"),
)
if source == "jobs":
- return source, normalized, outcome_note
- return source, normalized[:settings["per_stream_limit"]], outcome_note
+ return source, normalized, outcome_note, (detail_note, detail_state)
+ normalized = _apply_reddit_stream_keepers(
+ source, normalized, settings["per_stream_limit"], topic
+ )
+ return source, normalized, outcome_note, (detail_note, detail_state)
retryable = [s for s in thin_sources if s not in rate_limited_sources]
@@ -4019,7 +4114,7 @@ def _retry_thin_sources(
for future in as_completed(futures):
source = futures[future]
try:
- source, normalized, outcome_note = future.result()
+ source, normalized, outcome_note, (detail_note, detail_state) = future.result()
if outcome_note:
bundle.record_failure(
source,
@@ -4027,6 +4122,8 @@ def _retry_thin_sources(
outcome_note["detail"],
attempted=outcome_note.get("attempted", True),
)
+ if detail_note:
+ bundle.record_detail(source, detail_note, state=detail_state)
existing_urls = {item.url for item in bundle.items_by_source.get(source, []) if item.url}
new_items = [item for item in normalized if item.url not in existing_urls]
@@ -4153,8 +4250,33 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
failures,
)
if outcome_note:
- artifact = dict(artifact or {})
- artifact["_source_outcome"] = outcome_note
+ # Lane-level HTTP failures (e.g. a blocked shreddit partial on a
+ # datacenter IP) are captured by the sink even when the source
+ # delivered items. Only attach them when the run produced nothing,
+ # or when the impl attached its own explicit outcome artifact (e.g.
+ # "primary failed; fallback returned N items"). A swallowed lane
+ # failure must not brand a successful source auth-failed/partial.
+ # An adapter-declared outcome (typed ``_source_outcome`` or a legacy
+ # ``{"error": ...}`` / per-leg artifact) is explicit and always
+ # brands the source, even with items; only failures the adapter
+ # swallowed into the capture sink are demoted to detail.
+ explicit = isinstance(artifact, dict) and (
+ bool(artifact.get("_source_outcome"))
+ or _legacy_artifact_outcome(str(kwargs.get("source") or ""), artifact) is not None
+ )
+ if explicit or not items:
+ artifact = dict(artifact or {})
+ artifact["_source_outcome"] = outcome_note
+ elif failures:
+ # The source delivered items. Keep it ``ok`` but carry what the
+ # 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.
+ artifact = dict(artifact or {})
+ artifact["_source_outcome_detail"] = _summarize_lane_failures(failures)
+ artifact["_source_outcome_detail_state"] = min(
+ failures, key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9)
+ ).outcome_state
if module_backed:
http.fixture_source_record(fixture_request, [items, artifact])
return items, artifact
diff --git a/skills/last30days/scripts/lib/reddit_keyless.py b/skills/last30days/scripts/lib/reddit_keyless.py
index 82de1042..db7ea23d 100644
--- a/skills/last30days/scripts/lib/reddit_keyless.py
+++ b/skills/last30days/scripts/lib/reddit_keyless.py
@@ -238,7 +238,12 @@ def _enrich(posts: List[Dict[str, Any]], depth: str) -> List[Dict[str, Any]]:
http.submit_with_context(executor, _enrich_one, post): i
for i, post in enumerate(to_enrich)
}
- done, not_done = concurrent.futures.wait(futures, timeout=ENRICH_BUDGET)
+ # The budget covers the fetches; the allowance covers the shared
+ # bucket's queue (other lanes, other entities in compare mode).
+ done, not_done = concurrent.futures.wait(
+ futures,
+ timeout=ENRICH_BUDGET + http.reddit_keyless_wait_allowance(len(to_enrich)),
+ )
for future in done:
idx = futures[future]
try:
@@ -256,6 +261,21 @@ def _enrich(posts: List[Dict[str, Any]], depth: str) -> List[Dict[str, Any]]:
return enriched + rest
+def _by_comments(posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Stable-sort posts by comment count descending for enrichment slots.
+
+ Ties (equal counts, including unknown counts treated as 0) preserve the
+ incoming order, which search_and_enrich's provisional score-first sort
+ establishes. Mirrors _relevance_rank_key's `or 0` guard so a present-but-
+ None count is treated as 0 rather than raising.
+ """
+ def _comment_count(post: Dict[str, Any]) -> int:
+ eng = post.get("engagement") or {}
+ return eng.get("num_comments") or post.get("num_comments") or 0
+
+ return sorted(posts, key=_comment_count, reverse=True)
+
+
def _slot_priority(topic: str, posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Order posts for enrichment slots: entity-matching posts first.
@@ -268,9 +288,11 @@ def _slot_priority(topic: str, posts: List[Dict[str, Any]]) -> List[Dict[str, An
post text) so slots go to posts likely to survive final ranking — keying
on the same head token keeps the two paths from diverging. Falls back to
token-overlap relevance when the topic yields no usable primary entity.
- Within each tier the incoming
- (score-first) order is preserved. Never raises; on any failure the
- incoming order is returned unchanged.
+ Within each tier posts are ordered by comment count descending (stable:
+ equal or unknown counts preserve the incoming score-first order), so the
+ scarce slots go to the threads with the most discussion rather than to
+ near-empty threads that merely ranked higher by score. Never raises; on
+ any failure the incoming order is returned unchanged.
"""
try:
from . import relevance, rerank
@@ -292,7 +314,7 @@ def _slot_priority(topic: str, posts: List[Dict[str, Any]]) -> List[Dict[str, An
misses: List[Dict[str, Any]] = []
for post in posts:
(matches if _matches(post) else misses).append(post)
- return matches + misses
+ return _by_comments(matches) + _by_comments(misses)
except Exception:
return posts
@@ -349,7 +371,8 @@ def search_and_enrich(
_log(f"Relevance floor dropped {before - len(posts)} off-topic posts")
# Provisional score-first order so enrichment-slot selection has a stable
- # within-tier order to preserve.
+ # within-tier tiebreak order to preserve: within each entity tier, slots go
+ # to the most-commented threads first, and equal counts keep score order.
posts.sort(
key=lambda p: (
p.get("engagement", {}).get("score", 0) or 0,
@@ -359,9 +382,10 @@ def search_and_enrich(
reverse=True,
)
- # Enrichment slot selection is relevance-aware: entity-matching posts
- # claim the scarce comment slots first (score order preserved within
- # each tier).
+ # Enrichment slot selection is comment-aware within entity tiers:
+ # entity-matching posts claim the scarce comment slots first, and within
+ # each tier the most-commented threads get slots first (score order is the
+ # stable tiebreak for equal counts).
posts = _enrich(_slot_priority(topic, posts), depth)
# Final display order ranks relevance-first with a bounded engagement bonus,
diff --git a/skills/last30days/scripts/lib/reddit_listing.py b/skills/last30days/scripts/lib/reddit_listing.py
index 81db2204..c0f61b97 100644
--- a/skills/last30days/scripts/lib/reddit_listing.py
+++ b/skills/last30days/scripts/lib/reddit_listing.py
@@ -189,22 +189,27 @@ def _fetch_one_with_status(
timeframe: str = TIMEFRAME,
) -> tuple[List[Dict[str, Any]], Optional[str]]:
try:
- # tee_failures, not capture_failures: the latter would replace the
- # pipeline's sink and hide this failure from it. get_text launders a
- # terminal HTTP failure into None, so the tee is how this lane recovers
- # the status code it needs to report (issue #899).
- with http.tee_failures() as swallowed:
- text = http.reddit_keyless_get_text(_listing_url(subreddit, sort, timeframe), timeout=LISTING_TIMEOUT,
- accept="text/html")
+ # retry_429 records a terminal miss into the pipeline sink (issue #899)
+ # and retries a 429 once through the limiter (issue #985). An empty
+ # body ("") is a real empty listing; None never is.
+ text, error = http.reddit_keyless_get_text_retry_429(
+ _listing_url(subreddit, sort, timeframe),
+ timeout=LISTING_TIMEOUT,
+ accept="text/html",
+ )
if text is None:
- # An empty body ("") is a real empty listing; None never is.
- return [], (str(swallowed[-1]) if swallowed else "no response")
+ return [], (error or "no response")
return parse_cards(text, query), None
except Exception as e:
_log(f"listing fetch failed r/{subreddit} {sort}: {e}")
return [], str(e)
+def _result_timeout(batch_size: int) -> float:
+ """Per-future wait: the fetch's own timeout plus the bucket's queue depth."""
+ return LISTING_TIMEOUT + 5 + http.reddit_keyless_wait_allowance(batch_size)
+
+
def fetch_listings(
subreddits: List[str],
depth: str = "default",
@@ -233,7 +238,7 @@ def fetch_listings(
for sub, sort in jobs}
for future in futures:
try:
- all_posts.extend(future.result(timeout=LISTING_TIMEOUT + 5))
+ all_posts.extend(future.result(timeout=_result_timeout(len(jobs))))
except (Exception, FuturesTimeoutError) as e:
_log(f"listing future failed: {e}")
@@ -281,7 +286,7 @@ def fetch_discovery_listings(
}
for future, (subreddit, sort) in futures.items():
try:
- fetched, error = future.result(timeout=LISTING_TIMEOUT + 5)
+ fetched, error = future.result(timeout=_result_timeout(len(jobs)))
except (Exception, FuturesTimeoutError) as exc:
errors.append(f"r/{subreddit} {sort}: {exc}")
continue
diff --git a/skills/last30days/scripts/lib/reddit_public.py b/skills/last30days/scripts/lib/reddit_public.py
index ec8b1db2..f4298c4e 100644
--- a/skills/last30days/scripts/lib/reddit_public.py
+++ b/skills/last30days/scripts/lib/reddit_public.py
@@ -27,6 +27,8 @@ import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional
+from lib import http
+
USER_AGENT = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
@@ -86,15 +88,12 @@ def _fetch_json(url: str, timeout: int = 15) -> Optional[Dict[str, Any]]:
except urllib.error.HTTPError as e:
if e.code == 429:
- delay = BASE_BACKOFF * (2 ** attempt)
- retry_after = None
- if hasattr(e, "headers"):
- retry_after = e.headers.get("Retry-After")
- if retry_after:
- try:
- delay = float(retry_after)
- except ValueError:
- pass
+ # Reddit answers an anonymous 429 with x-ratelimit-reset and no
+ # Retry-After; honour either. See http.retry_delay_from_headers.
+ delay = http.retry_delay_from_headers(
+ getattr(e, "headers", None),
+ BASE_BACKOFF * (2 ** attempt),
+ )
_log(f"429 rate limited, retry {attempt + 1}/{MAX_RETRIES} after {delay:.1f}s")
if attempt < MAX_RETRIES - 1:
time.sleep(delay)
diff --git a/skills/last30days/scripts/lib/reddit_rss.py b/skills/last30days/scripts/lib/reddit_rss.py
index 0a91e99b..d3876312 100644
--- a/skills/last30days/scripts/lib/reddit_rss.py
+++ b/skills/last30days/scripts/lib/reddit_rss.py
@@ -171,15 +171,22 @@ def _build_urls(query: str, depth: str, subreddits: Optional[List[str]]) -> List
def _fetch_feed(url: str, query: str) -> List[Dict[str, Any]]:
- """Fetch and parse one feed. Never raises."""
+ """Fetch and parse one feed. Never raises. One limiter-respecting 429 retry."""
try:
- text = http.reddit_keyless_get_text(url, timeout=FEED_TIMEOUT, accept="application/atom+xml")
+ 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",
@@ -213,7 +220,7 @@ def search_rss(
}
for future in futures:
try:
- all_posts.extend(future.result(timeout=FEED_TIMEOUT + 5))
+ all_posts.extend(future.result(timeout=_result_timeout(len(urls))))
except (Exception, FuturesTimeoutError) as e:
_log(f"feed future failed: {e}")
diff --git a/skills/last30days/scripts/lib/reddit_shreddit.py b/skills/last30days/scripts/lib/reddit_shreddit.py
index b0546397..32822fc0 100644
--- a/skills/last30days/scripts/lib/reddit_shreddit.py
+++ b/skills/last30days/scripts/lib/reddit_shreddit.py
@@ -23,18 +23,47 @@ from typing import Any, Dict, List, Optional
from . import http
from . import reddit_enrich
-# Up to N posts enriched per run, by depth (mirrors reddit_public.ENRICH_LIMITS).
+# Up to N posts enriched per subquery, by depth. Raised from 3/5/8 once the
+# per-command memo (http.reddit_keyless_get_text) collapsed repeat shreddit
+# fetches across subqueries and the 1 req/s bucket stopped the 429s: eight
+# fetches fit inside ENRICH_BUDGET at four workers, and the comments are the
+# lane's headline value.
ENRICH_LIMITS = {
- "quick": 3,
- "default": 5,
- "deep": 8,
+ "quick": 4,
+ "default": 8,
+ "deep": 12,
}
# Max comments returned per post (independent of how many posts get enriched).
-MAX_COMMENTS = 10
+# Twelve so a thousand-comment thread feeds more than ten candidates into the
+# cross-platform Top Community Comments block.
+MAX_COMMENTS = 12
SVC_TIMEOUT = 12
+# Known bots whose comments carry no community signal.
+BOT_AUTHORS = frozenset({
+ "automoderator",
+ "remindmebot",
+ "repostsleuthbot",
+ "sneakpeekbot",
+ "savevideo",
+ "videodownloadbot",
+ "totesmessenger",
+ "b0trank",
+ "amputatorbot",
+ "stabbot",
+ "gifreversingbot",
+ "haikubotinaction",
+ "imagesofnetwork",
+ "botdefense",
+})
+
+_BOT_SUFFIXES = ("-bot", "_bot")
+
+# CamelCase catches WikiTextBot without swallowing names such as Talbot.
+_CAMEL_BOT = re.compile(r"[a-z0-9]Bot\d*$")
+
# Match the exact <shreddit-comment> element start tag, not <shreddit-comment-tree>
# or <shreddit-comment-tree-stats> (lookahead requires whitespace or '>').
_COMMENT_START = re.compile(r"<shreddit-comment(?=[\s>])[^>]*>")
@@ -106,13 +135,28 @@ def _body_for(html_text: str, thing_id: str) -> str:
return _WS.sub(" ", _html.unescape(text)).strip()
+def _is_bot_author(author: str) -> bool:
+ """Whether an author is a bot whose comments carry no community signal."""
+ raw = (author or "").strip()
+ if not raw:
+ return False
+ name = raw.lower()
+ return (name in BOT_AUTHORS
+ or name.endswith(_BOT_SUFFIXES)
+ or bool(_CAMEL_BOT.search(raw)))
+
+
def parse_comments(html_text: str, limit: int = MAX_COMMENTS) -> List[Dict[str, Any]]:
- """Parse <shreddit-comment> elements into scored comment dicts (sorted desc)."""
+ """Parse <shreddit-comment> elements into scored comment dicts (sorted desc).
+
+ Deleted, removed, and bot authors are dropped: they occupy top-comment slots
+ on high-traffic threads without saying anything about the topic.
+ """
comments: List[Dict[str, Any]] = []
for m in _COMMENT_START.finditer(html_text or ""):
tag = m.group(0)
author = _attr(tag, "author") or "[deleted]"
- if author in ("[deleted]", "[removed]"):
+ if author in ("[deleted]", "[removed]") or _is_bot_author(author):
continue
thing_id = _attr(tag, "thingId")
body = _body_for(html_text, thing_id)
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 085f67a2..1b6e0ce3 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -432,6 +432,26 @@ def _render_ranked_clusters(
return lines
+def _auxiliary_candidate_pool(
+ report: schema.Report,
+ visible_clusters: list[schema.Cluster],
+ solid_clusters: list[schema.Cluster],
+) -> list[schema.Candidate]:
+ """Candidates for Best Takes and Top Community Comments.
+
+ Those sections are cross-cutting evidence surfaces, so they read every
+ cluster that clears the relevance floor, not only the ``cluster_limit``
+ clusters shown in ``## Ranked Evidence Clusters``: a 3,000-vote comment on
+ the thread in cluster eleven is exactly what the brief is for. The
+ nothing-solid gate is unchanged: when the visible set has clusters but
+ none clear the floor, the pool is empty.
+ """
+ if visible_clusters and not solid_clusters:
+ return []
+ all_solid = _clusters_clearing_relevance_floor(report, report.clusters)
+ return _candidates_for_auxiliary_sections(report, report.clusters, all_solid)
+
+
def _clusters_clearing_relevance_floor(
report: schema.Report,
clusters: list[schema.Cluster],
@@ -646,12 +666,13 @@ def _render_registered_sections(
solid_clusters,
)
no_solid_evidence = bool(visible_clusters) and not solid_clusters
+ aux_candidates = _auxiliary_candidate_pool(report, visible_clusters, solid_clusters)
if no_solid_evidence:
best_takes: list[str] = []
top_comments: list[str] = []
else:
best_takes = _render_best_takes(
- visible_candidates,
+ aux_candidates,
limit=audience.budget_for("best_takes", int(fun_params["limit"])),
threshold=float(fun_params["threshold"]),
vote_weight=float(fun_params.get("vote_weight", 18.0)),
@@ -672,7 +693,7 @@ def _render_registered_sections(
top_comments = _render_top_comments(
report,
limit=audience.budget_for("top_comments", 8),
- candidates=visible_candidates,
+ candidates=aux_candidates,
)
if not top_comments:
top_comments = [
@@ -698,7 +719,7 @@ def _render_registered_sections(
"best_takes": best_takes,
"top_comments": top_comments,
"source_outcomes": _render_source_outcome_note(report),
- "source_coverage": _render_source_coverage(report),
+ "source_coverage": _render_source_coverage(report, include_errors=False),
}
lines: list[str] = []
for section_name in audience.section_order:
@@ -754,9 +775,10 @@ def render_compact(
]
)
- if report.warnings:
+ user_warnings = _warnings_without_source_failures(report.warnings)
+ if user_warnings:
lines.append("## Warnings")
- lines.extend(f"- {warning}" for warning in report.warnings)
+ lines.extend(f"- {warning}" for warning in user_warnings)
lines.append("")
# LAW 7 backstop: emit the DEGRADED RUN WARNING block BEFORE the evidence
@@ -792,6 +814,9 @@ def render_compact(
solid_clusters,
)
no_solid_evidence = bool(visible_clusters) and not solid_clusters
+ aux_candidates = _auxiliary_candidate_pool(
+ evidence_report, visible_clusters, solid_clusters
+ )
hiring_block = (
[]
if no_solid_evidence
@@ -812,7 +837,7 @@ def render_compact(
if not no_solid_evidence:
best_takes = _render_best_takes(
- visible_candidates,
+ aux_candidates,
limit=fun_params["limit"],
threshold=fun_params["threshold"],
vote_weight=fun_params.get("vote_weight", 18.0),
@@ -822,7 +847,7 @@ def render_compact(
top_comments = _render_top_comments(
evidence_report,
- candidates=visible_candidates,
+ candidates=aux_candidates,
)
if top_comments:
lines.extend([""] + top_comments)
@@ -831,7 +856,7 @@ def render_compact(
if outcome_note:
lines.extend([""] + outcome_note)
- lines.extend(_render_source_coverage(report))
+ lines.extend(_render_source_coverage(report, include_errors=False))
else:
lines.extend(
_render_registered_sections(
@@ -2481,7 +2506,29 @@ def _polymarket_top_markets(
return summaries
-def _render_source_coverage(report: schema.Report) -> list[str]:
+# Warnings that only restate a per-source outcome. The compact (model-facing)
+# stdout carries those through ## Partial Coverage, and the user-facing
+# footer carries counts only; doctor --postmortem, the saved raw file, and
+# --emit=json keep the full list.
+_SOURCE_FAILURE_WARNING_PREFIXES = (
+ "Some sources failed",
+ "Some sources returned partial results",
+)
+
+
+def _warnings_without_source_failures(warnings: list[str]) -> list[str]:
+ return [
+ warning
+ for warning in warnings
+ if not warning.startswith(_SOURCE_FAILURE_WARNING_PREFIXES)
+ ]
+
+
+def _render_source_coverage(
+ report: schema.Report,
+ *,
+ include_errors: bool = True,
+) -> list[str]:
lines = [
"## Source Coverage",
"",
@@ -2494,7 +2541,7 @@ def _render_source_coverage(report: schema.Report) -> list[str]:
if outcome and outcome.state != health.OK:
line += f" ({_format_outcome(outcome)})"
lines.append(line)
- if report.errors_by_source:
+ if include_errors and report.errors_by_source:
lines.append("")
lines.append("## Source Errors")
lines.append("")
@@ -2532,7 +2579,15 @@ def _format_outcome(outcome: schema.SourceOutcome) -> str:
state = outcome.state
if state == schema.PARTIAL:
noun = "item" if outcome.items_returned == 1 else "items"
- summary = f"partial after {outcome.items_returned} {noun}"
+ summary = f"partial — {outcome.items_returned} {noun} returned"
+ detail_l = detail.lower()
+ if (
+ "429" in detail_l
+ or "rate-limited" in detail_l
+ or "rate limit" in detail_l
+ or "too many requests" in detail_l
+ ):
+ summary += ", some requests rate-limited"
elif state == schema.NO_RESULTS:
summary = "no results"
else:
@@ -2797,9 +2852,9 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
parts.append(f"{with_transcripts}/{len(items)} with transcripts")
stats = " │ ".join(parts)
line = _footer_line_for_source(emoji, label, len(items), item_word, stats)
- outcome = report.source_status.get(source_key)
- if outcome and outcome.state != health.OK:
- line += f" │ ⚠ {_format_outcome(outcome)}"
+ # Counts only: run diagnostics live in doctor --postmortem, the saved
+ # raw file, and the model-facing ## Partial Coverage note, never on
+ # the user-facing conclusion surface.
out.append(line)
# Polymarket (special: count + odds string from existing helper)
@@ -2814,9 +2869,6 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
line = f"📊 Polymarket: {count_str} {plural} │ {odds_str}"
else:
line = f"📊 Polymarket: {count_str} {plural}"
- outcome = report.source_status.get("polymarket")
- if outcome and outcome.state != health.OK:
- line += f" │ ⚠ {_format_outcome(outcome)}"
out.append(line)
amazon_line = _amazon_footer_line(report)
@@ -2834,9 +2886,6 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
line = f"🌐 Web: {count_str} {plural} - {names}"
else:
line = f"🌐 Web: {count_str} {plural}"
- outcome = report.source_status.get("grounding")
- if outcome and outcome.state != health.OK:
- line += f" │ ⚠ {_format_outcome(outcome)}"
out.append(line)
# Only populated sources (>=1 item) get an emoji-tree line. A source that
@@ -2883,7 +2932,10 @@ def _amazon_footer_line(report: schema.Report) -> str | None:
# "no products matched" sends the user to fix the wrong thing --
# so lead with the real outcome, same as every other footer branch.
if failed:
- return f'📦 Amazon: no results for "{keyword}" │ ⚠ {_format_outcome(outcome)}'
+ # Counts-only footer: the outcome itself lives in ## Partial
+ # Coverage and doctor --postmortem, so just avoid the misleading
+ # "no products matched" wording when the search never ran.
+ return f'📦 Amazon: no results for "{keyword}"'
return f'📦 Amazon: no products matched "{keyword}"'
count = len(items)
@@ -2900,8 +2952,6 @@ def _amazon_footer_line(report: schema.Report) -> str | None:
if total_ratings:
parts.append(f"{total_ratings:,} ratings")
line = f"📦 Amazon: {' │ '.join(parts)}"
- if failed:
- line += f" │ ⚠ {_format_outcome(outcome)}"
return line
# Only the *sampled* products earn a slot. A run can carry a dozen
@@ -2937,8 +2987,6 @@ def _amazon_footer_line(report: schema.Report) -> str | None:
# still accepts a quote so a future writer can supply one.
entries = [amazon.footer_entry(s) for s in stats]
line = f"📦 Amazon: {count} {plural} │ {', '.join(entries)}"
- if failed:
- line += f" │ ⚠ {_format_outcome(outcome)}"
return line
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index 33b3d90a..f878c117 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -192,6 +192,10 @@ class SourceOutcome:
attempted: bool = True
detail: str | None = None
at: str = field(default_factory=_utc_now)
+ # Most specific state among sub-request failures the adapter swallowed
+ # while still delivering items. Stays informational while items exist;
+ # becomes the outcome state if post-retrieval filtering empties the source.
+ lane_failure_state: RunOutcomeState | None = None
fix_hint: str | None = None
def __post_init__(self) -> None:
@@ -341,6 +345,12 @@ class RetrievalBundle:
errors_by_source: dict[str, str] = field(default_factory=dict)
source_status: dict[str, SourceOutcome] = field(default_factory=dict)
artifacts: dict[str, Any] = field(default_factory=dict)
+ # Swallowed sub-request failures on a source that still delivered items.
+ # These never change the outcome state (the source succeeded); they ride
+ # along as ``SourceOutcome.detail`` so ``doctor --postmortem`` can show
+ # what a healthy-looking run lost without branding the source partial.
+ detail_by_source: dict[str, str] = field(default_factory=dict)
+ lane_state_by_source: dict[str, RunOutcomeState] = field(default_factory=dict)
def mark_attempted(self, source: str) -> None:
"""Register a planned source before its first retrieval starts."""
@@ -379,6 +389,32 @@ class RetrievalBundle:
fix_hint="doctor",
)
+ def record_detail(
+ self,
+ source: str,
+ detail: str,
+ state: RunOutcomeState | None = None,
+ ) -> None:
+ """Note a swallowed lane failure on a source that still delivered items.
+
+ Unlike :meth:`record_failure`, this never changes the outcome state and
+ sets no ``fix_hint``. The note is merged into the ``ok`` outcome on the
+ next :meth:`add_items` and survives later clean subqueries.
+ """
+ detail = " ".join((detail or "").split())
+ if not detail:
+ return
+ existing = self.detail_by_source.get(source)
+ if existing and detail not in existing:
+ detail = f"{existing}; {detail}"
+ self.detail_by_source[source] = detail
+ if state:
+ self.lane_state_by_source[source] = state
+ current = self.source_status.get(source)
+ if current and current.state in (health.OK, NO_RESULTS):
+ current.detail = detail
+ current.lane_failure_state = self.lane_state_by_source.get(source)
+
def add_items(self, label: str, source: str, items: list[SourceItem]) -> None:
"""Atomically append items to both items_by_source_and_query and items_by_source."""
self.items_by_source_and_query.setdefault((label, source), []).extend(items)
@@ -387,6 +423,18 @@ class RetrievalBundle:
state: RunOutcomeState = health.OK if items else NO_RESULTS
detail = None
fix_hint = None
+ if previous and previous.state == health.OK and not items:
+ # A later empty subquery must not downgrade a source that already
+ # delivered items to no-results.
+ state = health.OK
+ lane_state = None
+ if state in (health.OK, NO_RESULTS):
+ detail = self.detail_by_source.get(source)
+ lane_state = self.lane_state_by_source.get(source)
+ if state == NO_RESULTS and lane_state and not self.items_by_source[source]:
+ # Nothing delivered and sub-requests failed: that is the
+ # failure, not a clean empty result.
+ state = lane_state
if previous and previous.state not in (health.OK, NO_RESULTS):
# Preserve AUTH_FAILED state even when items are added: it's an
# actionable signal (re-login needed) that shouldn't be downgraded
@@ -404,6 +452,7 @@ class RetrievalBundle:
attempted=True,
detail=detail,
fix_hint=fix_hint,
+ lane_failure_state=lane_state,
)
@@ -518,6 +567,7 @@ def _source_status_from_dict(payload: dict[str, Any]) -> dict[str, "SourceOutcom
items_returned=int(outcome.get("items_returned") or 0),
attempted=bool(outcome.get("attempted", True)),
detail=outcome.get("detail"),
+ lane_failure_state=outcome.get("lane_failure_state"),
at=outcome.get("at") or _utc_now(),
fix_hint=outcome.get("fix_hint"),
)
diff --git a/tests/conftest.py b/tests/conftest.py
index bf8ab287..e94ab54a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -46,3 +46,12 @@ def _reset_probe_caches():
health.clear_dependency_probe_cache()
xurl_x.clear_availability_cache()
grok_x.clear_availability_cache()
+
[email protected](autouse=True)
+def _reset_reddit_keyless_memo():
+ """The keyless Reddit memo lives for one command; tests are their own commands."""
+ from lib import http as _http
+
+ _http.reset_reddit_keyless_memo()
+ yield
+ _http.reset_reddit_keyless_memo()
diff --git a/tests/test_fusion_v3.py b/tests/test_fusion_v3.py
index 70d4778e..5d54340c 100644
--- a/tests/test_fusion_v3.py
+++ b/tests/test_fusion_v3.py
@@ -518,3 +518,79 @@ class OutOfWindowSortTests(unittest.TestCase):
ordered = sorted([stale_with_high_confidence, fresh], key=fusion._candidate_sort_key)
self.assertEqual(["fresh", "stale_high"], [c.candidate_id for c in ordered])
+
+
+def _comments(n: int) -> list[dict]:
+ return [{"score": 100 - i, "author": f"u{i}", "excerpt": f"comment {i}"} for i in range(n)]
+
+
+class FusionEnrichedCopyTests(unittest.TestCase):
+ """Same thread, two subquery streams, per-stream ids collide (R1 / R1):
+ the candidate must keep the copy that carries the enrichment."""
+
+ def _plan(self):
+ return schema.QueryPlan(
+ intent="breaking_news",
+ freshness_mode="strict_recent",
+ cluster_mode="story",
+ raw_topic="kanye west",
+ subqueries=[
+ schema.SubQuery(label="primary", search_query="kanye west", ranking_query="kanye west", sources=["reddit"], weight=1.0),
+ schema.SubQuery(label="russia", search_query="kanye russia", ranking_query="kanye russia", sources=["reddit"], weight=0.8),
+ ],
+ source_weights={},
+ )
+
+ def test_enriched_second_copy_is_kept(self):
+ url = "https://www.reddit.com/r/Music/comments/1vy0ilk/kanye_wests_soldout_russia/"
+ bare = make_item("R1", "reddit", url, "Kanye West's Russia shows canceled", 0.6)
+ rich = make_item("R1", "reddit", url, "Kanye West's Russia shows canceled", 0.3)
+ rich.metadata["top_comments"] = _comments(10)
+ rich.metadata["comment_insights"] = ["Putin doesn't care"]
+ rich.engagement = {"score": 20859, "num_comments": 741}
+ bare.engagement = {"score": 18941, "num_comments": 713}
+ streams = {("primary", "reddit"): [bare], ("russia", "reddit"): [rich]}
+
+ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)
+
+ self.assertEqual(1, len(candidates))
+ cand = candidates[0]
+ self.assertEqual(1, len(cand.source_items))
+ self.assertEqual(10, len(cand.source_items[0].metadata["top_comments"]))
+ self.assertEqual(["Putin doesn't care"], cand.source_items[0].metadata["comment_insights"])
+ self.assertEqual(20859, cand.source_items[0].engagement["score"])
+ self.assertEqual({"primary:reddit", "russia:reddit"}, set(cand.native_ranks))
+
+ def test_enriched_first_copy_is_retained(self):
+ url = "https://www.reddit.com/r/Music/comments/1vy0ilk/kanye_wests_soldout_russia/"
+ rich = make_item("R1", "reddit", url, "Kanye West's Russia shows canceled", 0.6)
+ rich.metadata["top_comments"] = _comments(4)
+ bare = make_item("R1", "reddit", url, "Kanye West's Russia shows canceled", 0.3)
+ streams = {("primary", "reddit"): [rich], ("russia", "reddit"): [bare]}
+
+ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)
+
+ self.assertEqual(4, len(candidates[0].source_items[0].metadata["top_comments"]))
+
+ def test_distinct_urls_with_colliding_ids_stay_separate(self):
+ a = make_item("R1", "reddit", "https://www.reddit.com/r/Kanye/comments/aaa/one/", "Thread one", 0.6)
+ b = make_item("R1", "reddit", "https://www.reddit.com/r/Kanye/comments/bbb/two/", "Thread two", 0.5)
+ streams = {("primary", "reddit"): [a], ("russia", "reddit"): [b]}
+
+ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)
+
+ self.assertEqual(2, len(candidates))
+
+ def test_collapse_duplicate_urls_merges_enrichment(self):
+ url = "https://www.reddit.com/r/Music/comments/1vy0ilk/kanye/"
+ bare = make_item("R1", "reddit", url, "Kanye", 0.6)
+ rich = make_item("R1", "reddit", url, "Kanye", 0.3)
+ rich.metadata["top_comments"] = _comments(3)
+ other = make_item("R2", "reddit", "https://www.reddit.com/r/Kanye/comments/zzz/other/", "Other", 0.4)
+
+ out = fusion.collapse_duplicate_urls([bare, rich, other])
+
+ self.assertEqual(2, len(out))
+ self.assertIs(out[0], bare)
+ self.assertEqual(3, len(out[0].metadata["top_comments"]))
+ self.assertIs(out[1], other)
diff --git a/tests/test_pipeline_finalize.py b/tests/test_pipeline_finalize.py
new file mode 100644
index 00000000..ea22485d
--- /dev/null
+++ b/tests/test_pipeline_finalize.py
@@ -0,0 +1,28 @@
+"""Report finalize collapses same-URL copies of a thread and keeps enrichment."""
+
+from lib import pipeline, schema
+
+
+def _item(item_id, url, rank, comments=None):
+ item = schema.SourceItem(
+ item_id=item_id,
+ source="reddit",
+ title="Kanye West's sold-out Russia shows canceled",
+ body="Kanye West's sold-out Russia shows canceled",
+ url=url,
+ metadata={"top_comments": comments or []},
+ )
+ item.local_rank_score = rank
+ return item
+
+
+def test_finalize_merges_same_url_copies_and_keeps_comments():
+ url = "https://www.reddit.com/r/Music/comments/1vy0ilk/kanye_wests_soldout_russia/"
+ bare = _item("R1", url, 0.677)
+ rich = _item("R1", url, 0.487, comments=[{"score": 3293, "author": "u/tableleg7", "excerpt": "Putin"}])
+
+ finalized = pipeline._finalize_items_by_source({"reddit": [bare, rich]}, topic="kanye west", mock=True)
+
+ items = finalized["reddit"]
+ assert len(items) == 1
+ assert items[0].metadata["top_comments"][0]["score"] == 3293
diff --git a/tests/test_reddit_keyless.py b/tests/test_reddit_keyless.py
index 823be932..2ba1446b 100644
--- a/tests/test_reddit_keyless.py
+++ b/tests/test_reddit_keyless.py
@@ -259,6 +259,116 @@ class TestSlotPriority:
out = reddit_keyless._slot_priority("openclaw", posts)
assert out == posts
+ @staticmethod
+ def _titled_nc(i, title, score=0, ncmt=0, selftext=""):
+ """_titled variant that also sets a real comment count (both surfaces)."""
+ p = TestSlotPriority._titled(i, title, score=score, selftext=selftext)
+ p["num_comments"] = ncmt
+ p["engagement"]["num_comments"] = ncmt
+ return p
+
+ def test_comment_count_orders_within_match_tier(self):
+ # Two entity-matching posts: the low-score high-comment thread wins the slot.
+ high_comments = self._titled_nc(1, "openclaw thread with lots of discussion", score=1, ncmt=45)
+ low_comments = self._titled_nc(2, "openclaw thread, quiet", score=900, ncmt=3)
+ out = reddit_keyless._slot_priority("openclaw", [low_comments, high_comments])
+ assert out[0] is high_comments
+ assert out[1] is low_comments
+
+ def test_entity_match_tier_beats_comment_count(self):
+ # Entity priority is preserved: a miss with 100 comments still follows a
+ # match with 1 comment, regardless of discussion volume.
+ match = self._titled_nc(1, "openclaw tips", score=10, ncmt=1)
+ miss = self._titled_nc(2, "Gemma news", score=100, ncmt=100)
+ out = reddit_keyless._slot_priority("openclaw", [miss, match])
+ assert out[0] is match
+ assert out[1] is miss
+
+ def test_equal_comment_counts_preserve_incoming_order_stable(self):
+ # Stable tiebreak: equal comment counts preserve the incoming order. The
+ # score-first order is established by search_and_enrich's provisional
+ # sort before _slot_priority runs; _slot_priority must not re-sort ties.
+ p1 = self._titled_nc(1, "openclaw thread a", score=100, ncmt=5)
+ p2 = self._titled_nc(2, "openclaw thread b", score=50, ncmt=5)
+ out = reddit_keyless._slot_priority("openclaw", [p2, p1])
+ assert out[0] is p2
+ assert out[1] is p1
+
+ def test_unknown_comment_count_ties_with_zero(self):
+ # Missing/None comment count is treated as 0: it ties with a known-zero
+ # post (stable) and sorts below any positive-count post in its tier.
+ unknown = self._titled_nc(1, "openclaw unknown", score=100, ncmt=None)
+ positive = self._titled_nc(2, "openclaw positive", score=10, ncmt=3)
+ known_zero = self._titled_nc(3, "openclaw zero", score=5, ncmt=0)
+ out = reddit_keyless._slot_priority("openclaw", [known_zero, unknown, positive])
+ assert out[0] is positive
+ assert out[1:] == [known_zero, unknown]
+
+ def test_richest_thread_gets_slot_when_score_ranked_low(self):
+ # Issue #906 regression: a 45-comment thread ranked last by score must
+ # get an enrichment slot at default depth (limit 8) while a 4-comment
+ # thread above it in score order does not. All posts are in the same
+ # entity tier; there are more posts than slots so ordering matters.
+ posts = [
+ self._titled_nc(1, "openclaw thread one", score=1000, ncmt=4),
+ self._titled_nc(2, "openclaw thread two", score=900, ncmt=4),
+ self._titled_nc(3, "openclaw thread three", score=800, ncmt=4),
+ self._titled_nc(4, "openclaw thread four", score=700, ncmt=4),
+ self._titled_nc(5, "openclaw thread five", score=600, ncmt=6),
+ self._titled_nc(6, "openclaw thread six", score=500, ncmt=5),
+ self._titled_nc(7, "openclaw thread seven", score=300, ncmt=4),
+ self._titled_nc(9, "openclaw thread nine", score=250, ncmt=7),
+ self._titled_nc(10, "openclaw thread ten", score=200, ncmt=8),
+ self._titled_nc(11, "openclaw thread eleven", score=150, ncmt=9),
+ self._titled_nc(8, "openclaw thread eight", score=77, ncmt=45),
+ ]
+ enriched_urls = []
+
+ def _capture(url):
+ enriched_urls.append(url)
+ return {"top_comments": [], "comment_insights": [], "num_comments": None}
+
+ with mock.patch.object(reddit_keyless, "_discover", return_value=posts), \
+ mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments",
+ side_effect=_capture):
+ reddit_keyless.search_and_enrich(
+ "openclaw", "2026-05-01", "2026-05-31", depth="default")
+ assert posts[10]["url"] in enriched_urls # 45-comment thread enriched
+ assert posts[6]["url"] not in enriched_urls # 4-comment thread above it skipped
+ assert len(enriched_urls) == reddit_keyless.ENRICH_LIMITS["default"]
+
+ def test_miss_tier_orders_by_comments_for_leftover_slots(self):
+ # Review finding #1 (validated): when the entity-match tier is smaller
+ # than ENRICH_LIMITS, leftover slots are filled from the miss tier in
+ # comment-count order. 1 match + 4 misses at quick depth (limit 4): the
+ # three most-commented misses get slots, the least-commented miss does not.
+ # Score order deliberately differs from comment order so this test
+ # discriminates the miss-tier sort from the old score-first order.
+ posts = [
+ self._titled_nc(1, "openclaw thread", score=100, ncmt=2),
+ self._titled_nc(2, "Gemma thread A", score=5, ncmt=30),
+ self._titled_nc(3, "Gemma thread B", score=40, ncmt=9),
+ self._titled_nc(4, "Gemma thread C", score=30, ncmt=2),
+ self._titled_nc(5, "Gemma thread D", score=20, ncmt=1),
+ ]
+ enriched_urls = []
+
+ def _capture(url):
+ enriched_urls.append(url)
+ return {"top_comments": [], "comment_insights": [], "num_comments": None}
+
+ with mock.patch.object(reddit_keyless, "_discover", return_value=posts), \
+ mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments",
+ side_effect=_capture):
+ reddit_keyless.search_and_enrich(
+ "openclaw", "2026-05-01", "2026-05-31", depth="quick")
+ assert posts[0]["url"] in enriched_urls # entity match always slotted
+ assert posts[1]["url"] in enriched_urls # 30-comment miss (top miss)
+ assert posts[2]["url"] in enriched_urls # 9-comment miss
+ assert posts[3]["url"] in enriched_urls # 2-comment miss takes the last slot
+ assert posts[4]["url"] not in enriched_urls # 1-comment miss below the cut
+ assert len(enriched_urls) == reddit_keyless.ENRICH_LIMITS["quick"]
+
class TestScoredListingsFallback:
"""_scored_listings falls back to the arctic-shift archive when the
diff --git a/tests/test_reddit_keyless_backoff.py b/tests/test_reddit_keyless_backoff.py
index fc44aaa4..a8006da1 100644
--- a/tests/test_reddit_keyless_backoff.py
+++ b/tests/test_reddit_keyless_backoff.py
@@ -1,8 +1,9 @@
-"""Tests for the shared keyless-Reddit throttle (U4)."""
+"""Tests for the shared keyless-Reddit throttle (U4) and 429 in-lane retry."""
+import os
from unittest import mock
-from lib import http, reddit_rss
+from lib import http, reddit_listing, reddit_rss, render, schema
class TestRateLimiter:
@@ -53,3 +54,211 @@ class TestRedditKeylessGetText:
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):
+ limiter = http.make_reddit_keyless_limiter(environ={})
+ assert limiter.rate == 1.0
+ assert limiter.capacity == 2
+
+ def test_env_override(self):
+ limiter = http.make_reddit_keyless_limiter(
+ environ={http.REDDIT_KEYLESS_RATE_ENV: "0.25"}
+ )
+ assert limiter.rate == 0.25
+ assert limiter.capacity == 2
+
+ def test_invalid_and_nonpositive_fall_back_to_default(self):
+ for raw in ("fast", "", "-1", "0", "nan", "inf"):
+ limiter = http.make_reddit_keyless_limiter(
+ environ={http.REDDIT_KEYLESS_RATE_ENV: raw}
+ )
+ assert limiter.rate == http.DEFAULT_REDDIT_KEYLESS_RATE, raw
+
+ def test_process_env_syncs_onto_shared_limiter(self, monkeypatch):
+ monkeypatch.setattr(http.REDDIT_KEYLESS_LIMITER, "rate", 1.0)
+ 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")
+ assert http.REDDIT_KEYLESS_LIMITER.rate == 0.5
+
+ def test_env_file_value_is_exported_for_limiter(self, tmp_path, monkeypatch):
+ from lib import env
+
+ config_file = tmp_path / ".env"
+ config_file.write_text(f"{http.REDDIT_KEYLESS_RATE_ENV}=0.25\n", encoding="utf-8")
+ config_file.chmod(0o600)
+ monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
+ monkeypatch.setattr(env, "CONFIG_FILE", config_file)
+ monkeypatch.setenv("LAST30DAYS_CONFIG_DIR", str(tmp_path))
+ monkeypatch.delenv(http.REDDIT_KEYLESS_RATE_ENV, raising=False)
+ monkeypatch.chdir(tmp_path)
+ with mock.patch.object(env, "_load_keychain", return_value={}), \
+ mock.patch.object(env, "_load_pass", return_value={}):
+ config = env.get_config()
+ assert config[http.REDDIT_KEYLESS_RATE_ENV] == "0.25"
+ assert http.parse_reddit_keyless_rate(
+ config[http.REDDIT_KEYLESS_RATE_ENV]
+ ) == 0.25
+ assert os.environ.get(http.REDDIT_KEYLESS_RATE_ENV) == "0.25"
+
+
+def _record_status(code: int, reason: str) -> None:
+ http._record_failure(http.HTTPError(f"HTTP {code}: {reason}", code))
+
+
+class TestRedditKeyless429Retry:
+ def test_429_then_200_recovers_via_single_retry(self):
+ bodies = [None, "<feed xmlns='http://www.w3.org/2005/Atom'/>"]
+
+ 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") as acq, \
+ 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"
+ )
+ assert text.startswith("<feed")
+ assert err is None
+ assert acq.call_count == 2
+ slept.assert_called_once()
+ assert bodies == []
+
+ def test_429_then_429_records_failure_and_stops(self):
+ def fake_get(*_args, **_kwargs):
+ _record_status(429, "Too Many Requests")
+ return None
+
+ with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
+ mock.patch.object(http.time, "sleep"), \
+ 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"
+ )
+ assert text is None
+ assert err is not None and "429" in err
+ assert gt.call_count == 2
+ assert any(f.status_code == 429 for f in failures)
+
+ def test_non_429_miss_is_not_retried(self):
+ def fake_get(*_args, **_kwargs):
+ _record_status(403, "Forbidden")
+ return None
+
+ with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
+ 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"
+ )
+ assert text is None
+ assert "403" in (err or "")
+ assert gt.call_count == 1
+ 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 Path
+
+ html = (
+ Path(__file__).resolve().parent.parent
+ / "fixtures"
+ / "reddit_listing_cards_sample.html"
+ ).read_text(encoding="utf-8")
+ bodies = [None, html]
+
+ 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"):
+ items, error = reddit_listing._fetch_one_with_status(
+ "technology", "hot", "netherlands"
+ )
+ assert error is None
+ assert items
+ assert bodies == []
+
+ def test_listing_fetch_records_double_429(self):
+ def fake_get(*_args, **_kwargs):
+ _record_status(429, "Too Many Requests")
+ return None
+
+ with mock.patch.object(http, "get_text", side_effect=fake_get) as gt, \
+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
+ mock.patch.object(http.time, "sleep"), \
+ http.capture_failures() as failures:
+ items, error = reddit_listing._fetch_one_with_status(
+ "technology", "hot", "x"
+ )
+ assert items == []
+ assert error is not None and "429" in error
+ assert gt.call_count == 2
+ assert any(f.status_code == 429 for f in failures)
+
+
+class TestPartialOutcomeWording:
+ def test_rate_limited_partial_does_not_read_as_cutoff(self):
+ outcome = schema.SourceOutcome(
+ source="reddit",
+ state=schema.PARTIAL,
+ items_returned=8,
+ detail="HTTP 429: Too Many Requests",
+ )
+ text = render._format_outcome(outcome)
+ assert "partial after" not in text
+ assert "8 items returned" in text
+ assert "some requests rate-limited" in text
+ assert "HTTP 429" in text
+
+ def test_non_rate_limit_partial_keeps_count_without_429_claim(self):
+ outcome = schema.SourceOutcome(
+ source="instagram",
+ state=schema.PARTIAL,
+ items_returned=1,
+ detail="HTTP 400: Bad Request",
+ )
+ text = render._format_outcome(outcome)
+ assert "partial after" not in text
+ assert "1 item returned" in text
+ assert "rate-limited" not in text
+ assert "HTTP 400" in text
diff --git a/tests/test_reddit_keyless_memo.py b/tests/test_reddit_keyless_memo.py
new file mode 100644
index 00000000..f941adf7
--- /dev/null
+++ b/tests/test_reddit_keyless_memo.py
@@ -0,0 +1,122 @@
+"""Run-scoped memo for keyless Reddit GETs.
+
+Subreddit listings, listing RSS feeds, arctic supplements, and shreddit comment
+pages are byte-identical across subqueries (the lane is dispatched with the raw
+topic every time), so a four-subquery run fetched each of them four times.
+"""
+
+import threading
+from unittest import mock
+
+import pytest
+
+from lib import http
+
+
[email protected](autouse=True)
+def _fresh_memo():
+ http.reset_reddit_keyless_memo()
+ yield
+ http.reset_reddit_keyless_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, \
+ 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/>"
+ assert get_text.call_count == 1
+ assert 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, \
+ 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 get_text.call_count == 2
+
+
+def test_reset_clears_the_memo():
+ with mock.patch.object(http, "get_text", return_value="<feed/>") 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.reset_reddit_keyless_memo()
+ http.reddit_keyless_get_text("https://www.reddit.com/r/Kanye/new.rss")
+ assert get_text.call_count == 2
+
+
+def test_memo_is_bounded():
+ with mock.patch.object(http, "get_text", return_value="<feed/>") 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")
+ # 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")
+ assert get_text.call_count == http.REDDIT_KEYLESS_MEMO_MAX + 2
+
+
+def test_concurrent_requesters_share_one_in_flight_fetch():
+ release = threading.Event()
+ calls = []
+
+ def slow_get_text(url, **kwargs):
+ calls.append(url)
+ release.wait(timeout=5)
+ return "<feed/>"
+
+ results = []
+ with mock.patch.object(http, "get_text", side_effect=slow_get_text), \
+ mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"):
+ url = "https://www.reddit.com/svc/shreddit/community-more-posts/top/?name=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()
+ # Give every thread a chance to reach the memo before the owner finishes.
+ deadline = threading.Event()
+ deadline.wait(timeout=0.2)
+ release.set()
+ for t in threads:
+ t.join(timeout=5)
+ assert results == ["<feed/>"] * 4
+ assert 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, \
+ 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)
+ assert get_text.call_count == 1
+
+
+def test_waiters_do_not_stampede_when_the_owner_fails():
+ """If the in-flight owner's fetch fails, the waiters elect one new owner
+ and share its fetch instead of each issuing their own."""
+ release = threading.Event()
+ calls = []
+ lock = threading.Lock()
+
+ def get_text(url, **kwargs):
+ with lock:
+ calls.append(url)
+ n = len(calls)
+ release.wait(timeout=5)
+ return None if n == 1 else "<feed/>"
+
+ 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"
+ threads = [threading.Thread(target=lambda: results.append(http.reddit_keyless_get_text(url))) for _ in range(4)]
+ for t in threads:
+ t.start()
+ threading.Event().wait(timeout=0.2)
+ 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 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.py
new file mode 100644
index 00000000..8ab3c0ae
--- /dev/null
+++ b/tests/test_reddit_keyless_wait_allowance.py
@@ -0,0 +1,64 @@
+"""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
+thirteen seconds of token waits before the last fetch even starts, and four
+subquery 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).
+"""
+
+import threading
+from unittest import mock
+
+from lib import http, reddit_listing, reddit_rss
+
+
+def test_limiter_reports_waiting_threads():
+ limiter = http.RateLimiter(rate_per_sec=1000.0, burst=1)
+ assert limiter.waiting == 0
+ limiter.acquire() # drains the single token
+ started = threading.Event()
+
+ def _wait():
+ started.set()
+ limiter.acquire()
+
+ t = threading.Thread(target=_wait)
+ t.start()
+ started.wait(timeout=1)
+ # The waiter is inside acquire() until a token refills.
+ deadline = threading.Event()
+ deadline.wait(timeout=0.01)
+ t.join(timeout=2)
+ assert limiter.waiting == 0
+
+
+def test_wait_allowance_scales_with_batch_and_queue(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 http.reddit_keyless_wait_allowance(13) == 13.0 + pad
+ limiter._waiting = 5
+ assert http.reddit_keyless_wait_allowance(13) == 18.0 + pad
+ # The allowance syncs the configured rate before computing.
+ monkeypatch.setenv(http.REDDIT_KEYLESS_RATE_ENV, "2")
+ assert http.reddit_keyless_wait_allowance(13) == 9.0 + pad
+
+
+def test_rss_and_listing_result_timeouts_include_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 + pad
+ assert reddit_listing._result_timeout(20) == reddit_listing.LISTING_TIMEOUT + 5 + 20.0 + pad
+
+
+def test_allowance_reflects_a_process_env_rate_override(monkeypatch):
+ limiter = http.RateLimiter(rate_per_sec=1.0, burst=2)
+ with mock.patch.object(http, "REDDIT_KEYLESS_LIMITER", limiter):
+ monkeypatch.setenv(http.REDDIT_KEYLESS_RATE_ENV, "0.5")
+ pad = http.REDDIT_KEYLESS_CONTENTION_SECONDS
+ assert http.reddit_keyless_wait_allowance(10) == 20.0 + pad
diff --git a/tests/test_reddit_ratelimit_reset.py b/tests/test_reddit_ratelimit_reset.py
new file mode 100644
index 00000000..dc5eb0bf
--- /dev/null
+++ b/tests/test_reddit_ratelimit_reset.py
@@ -0,0 +1,73 @@
+"""Reddit answers an anonymous 429 with x-ratelimit-reset and no Retry-After.
+
+Reading only Retry-After sends the caller into exponential backoff (3s, 5s, 9s),
+every step of which is shorter than the ~42s Reddit actually requires, so each
+retry re-429s and the source is reported dead when it was only early.
+"""
+
+from lib import http
+
+
+class TestRetryDelayFromHeaders:
+ def test_prefers_retry_after_when_present(self):
+ assert http.retry_delay_from_headers({"Retry-After": "17"}, 3.0) == 17.0
+
+ def test_falls_back_to_x_ratelimit_reset(self):
+ # The header Reddit actually sends on search/RSS 429s.
+ assert http.retry_delay_from_headers({"x-ratelimit-reset": "42"}, 3.0) == 42.0
+
+ def test_retry_after_wins_over_ratelimit_reset(self):
+ headers = {"Retry-After": "5", "x-ratelimit-reset": "42"}
+ assert http.retry_delay_from_headers(headers, 3.0) == 5.0
+
+ def test_real_reddit_429_headers(self):
+ # Captured verbatim from an anonymous GET to
+ # https://www.reddit.com/search.rss?q=... on 2026-08-23.
+ headers = {
+ "x-ratelimit-used": "1",
+ "x-ratelimit-remaining": "0.0",
+ "x-ratelimit-reset": "42",
+ "server-timing": 'reddit-ct;desc="dn=FT,p=LON,cs=MISS"',
+ }
+ # Must not fall through to the 3s fallback -- that is the bug.
+ assert http.retry_delay_from_headers(headers, 3.0) == 42.0
+
+ def test_missing_headers_use_fallback(self):
+ assert http.retry_delay_from_headers({}, 7.5) == 7.5
+ assert http.retry_delay_from_headers(None, 7.5) == 7.5
+
+ def test_unparseable_values_use_fallback(self):
+ # Retry-After may be an HTTP-date rather than a delta-seconds integer.
+ assert http.retry_delay_from_headers({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, 4.0) == 4.0
+ assert http.retry_delay_from_headers({"x-ratelimit-reset": ""}, 4.0) == 4.0
+
+ def test_non_positive_values_use_fallback(self):
+ # A spent bucket sometimes reports 0; sleeping 0 just re-429s immediately.
+ assert http.retry_delay_from_headers({"x-ratelimit-reset": "0"}, 4.0) == 4.0
+ assert http.retry_delay_from_headers({"Retry-After": "-1"}, 4.0) == 4.0
+
+ def test_skips_unparseable_header_and_reads_the_next(self):
+ headers = {"Retry-After": "soon", "x-ratelimit-reset": "42"}
+ assert http.retry_delay_from_headers(headers, 3.0) == 42.0
+
+
+class TestRetryDelayBounds:
+ """A reset header must never park a thread for minutes (or, for an epoch
+ timestamp, for years)."""
+
+ def test_epoch_reset_is_converted_to_a_delta_and_capped(self):
+ # GitHub sends x-ratelimit-reset as epoch seconds with no Retry-After.
+ import time
+ epoch = str(int(time.time()) + 30)
+ delay = http.retry_delay_from_headers({"x-ratelimit-reset": epoch}, 3.0)
+ assert 0 < delay <= http.MAX_RETRY_DELAY_SECONDS
+ assert 25 <= delay <= 31
+
+ def test_far_future_epoch_is_capped(self):
+ # 2100-01-01 as epoch seconds: a delta of decades still yields the cap.
+ delay = http.retry_delay_from_headers({"x-ratelimit-reset": "4102444800"}, 3.0)
+ assert delay == http.MAX_RETRY_DELAY_SECONDS
+
+ def test_long_delta_is_capped(self):
+ assert http.retry_delay_from_headers({"x-ratelimit-reset": "540"}, 3.0) == http.MAX_RETRY_DELAY_SECONDS
+ assert http.retry_delay_from_headers({"Retry-After": "600"}, 3.0) == http.MAX_RETRY_DELAY_SECONDS
diff --git a/tests/test_reddit_rss.py b/tests/test_reddit_rss.py
index cb8377ce..04b4f519 100644
--- a/tests/test_reddit_rss.py
+++ b/tests/test_reddit_rss.py
@@ -3,8 +3,16 @@
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"
diff --git a/tests/test_reddit_shreddit.py b/tests/test_reddit_shreddit.py
index 3bd423e2..fc01eefd 100644
--- a/tests/test_reddit_shreddit.py
+++ b/tests/test_reddit_shreddit.py
@@ -68,6 +68,58 @@ class TestParseComments:
assert rs.parse_comments("<html>no comments here</html>") == []
+class TestBotFilter:
+ """Bot comments occupy top-comment slots without carrying community signal."""
+
+ @staticmethod
+ def _comment_html(author, thing_id="t1_botfilter1", score=999):
+ return (
+ f'<shreddit-comment author="{author}" thingId="{thing_id}" '
+ f'score="{score}" permalink="/r/test/comments/1/x/{thing_id}/">'
+ f'</shreddit-comment>'
+ f'<div id="{thing_id}-post-rtjson-content">'
+ f'<p>I will be messaging you in 3 days to remind you of this link.</p>'
+ f'</div>'
+ )
+
+ def test_known_bots_dropped(self):
+ for bot in ("RemindMeBot", "AutoModerator", "sneakpeekbot"):
+ assert rs.parse_comments(self._comment_html(bot)) == [], bot
+
+ def test_bot_match_is_case_insensitive(self):
+ assert rs.parse_comments(self._comment_html("remindmebot")) == []
+
+ def test_separator_suffix_bots_dropped(self):
+ for bot in ("some-random-bot", "subreddit_bot"):
+ assert rs.parse_comments(self._comment_html(bot)) == [], bot
+
+ def test_camelcase_bots_dropped(self):
+ # The separator-free convention is the common one on Reddit.
+ for bot in ("WikiTextBot", "RepostSleuthBot", "RemindMeBot2"):
+ assert rs.parse_comments(self._comment_html(bot)) == [], bot
+
+ def test_human_authors_kept(self):
+ # Names merely ending in "bot" are people, not bots. The capital B in
+ # the camelCase rule is what separates "WikiTextBot" from "Talbot".
+ for human in ("Talbot", "abbot", "u_bothell_local", "MSRS-",
+ "TheBotanist", "Botany101", "Robotics_fan"):
+ out = rs.parse_comments(self._comment_html(human))
+ assert len(out) == 1, human
+ assert out[0]["author"] == human
+
+ def test_bot_does_not_displace_human_from_slot(self):
+ # The reported failure was a bot *taking a slot*, not merely appearing:
+ # it outscores the humans, so it wins the ranking before truncation.
+ html = (self._comment_html("RemindMeBot", thing_id="t1_bot", score=999)
+ + self._comment_html("real_person", thing_id="t1_human", score=5))
+ out = rs.parse_comments(html, limit=1)
+ assert [c["author"] for c in out] == ["real_person"]
+
+ def test_is_bot_author_handles_blank(self):
+ assert rs._is_bot_author("") is False
+ assert rs._is_bot_author(None) is False
+
+
class TestTotalComments:
def test_reads_total(self):
assert rs._total_comments(_html()) == 14
@@ -101,3 +153,21 @@ class TestFetchComments:
with mock.patch.object(rs.http, "get_text", return_value=None):
out = rs.fetch_comments(url)
assert out["top_comments"] == [] and out["num_comments"] is None
+
+
+class TestEnrichmentBudget:
+ """Busy topics enrich more threads and carry more comments per thread."""
+
+ def test_enrich_limits_by_depth(self):
+ assert rs.ENRICH_LIMITS == {"quick": 4, "default": 8, "deep": 12}
+
+ def test_parse_comments_returns_up_to_twelve(self):
+ html = "".join(
+ f'<shreddit-comment author="user{i}" thingId="t1_c{i}" score="{100 - i}" '
+ f'permalink="/r/test/comments/1/x/t1_c{i}/"></shreddit-comment>'
+ f'<div id="t1_c{i}-post-rtjson-content"><p>comment number {i} body text</p></div>'
+ for i in range(30)
+ )
+ out = rs.parse_comments(html)
+ assert len(out) == rs.MAX_COMMENTS == 12
+ assert [c["score"] for c in out] == list(range(100, 88, -1))
diff --git a/tests/test_reddit_stream_keepers.py b/tests/test_reddit_stream_keepers.py
new file mode 100644
index 00000000..d3b400fa
--- /dev/null
+++ b/tests/test_reddit_stream_keepers.py
@@ -0,0 +1,157 @@
+"""Reddit engagement keepers: the month's most-discussed on-topic threads survive
+per-stream truncation, and the fused pool reserves slots for them."""
+
+from lib import fusion, pipeline, schema
+
+
+def _reddit_item(i, *, score=1, ncmt=0, relevance=0.5, title="Kanye West thread", rank=None):
+ item = schema.SourceItem(
+ item_id=f"R{i}",
+ source="reddit",
+ title=f"{title} {i}",
+ body=f"{title} {i}",
+ url=f"https://www.reddit.com/r/Kanye/comments/t{i:03d}/",
+ engagement={"score": score, "num_comments": ncmt},
+ )
+ item.local_relevance = relevance
+ item.local_rank_score = rank if rank is not None else relevance
+ return item
+
+
+def _stream(n=36):
+ items = [_reddit_item(i, relevance=0.5 - i * 0.01, rank=0.5 - i * 0.01) for i in range(n)]
+ return items
+
+
+class TestStreamKeepers:
+ def test_high_engagement_thread_ranked_23rd_survives_truncation(self):
+ items = _stream()
+ big = _reddit_item(99, score=16180, ncmt=1450, relevance=0.19, rank=0.36,
+ title="Kanye West Heads to Putin's Russia")
+ items.insert(22, big)
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "Kanye West")
+ assert len(kept) == 12
+ assert big in kept
+
+ def test_zero_relevance_thread_is_not_kept(self):
+ items = _stream()
+ big = _reddit_item(99, score=16180, ncmt=1450, relevance=0.0, rank=0.0, title="Something else")
+ items.insert(22, big)
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "Kanye West")
+ assert big not in kept
+
+ def test_thread_without_entity_head_token_is_not_kept(self):
+ items = _stream()
+ big = _reddit_item(99, score=16180, ncmt=1450, relevance=0.19, rank=0.36,
+ title="Ye Heads to Putin's Russia")
+ items.insert(22, big)
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "Kanye West")
+ assert big not in kept
+
+ def test_short_stream_is_returned_whole(self):
+ items = _stream(2)
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "Kanye West")
+ assert kept == items
+
+ def test_non_reddit_stream_is_plain_truncation(self):
+ items = _stream()
+ for it in items:
+ it.source = "x"
+ kept = pipeline._apply_reddit_stream_keepers("x", items, 12, "Kanye West")
+ assert kept == items[:12]
+
+ def test_generic_head_token_requires_higher_relevance(self):
+ items = _stream()
+ big = _reddit_item(99, score=9000, ncmt=900, relevance=0.15, rank=0.2,
+ title="AI second brain setups")
+ items.insert(22, big)
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "AI second brain")
+ assert big not in kept
+ big.local_relevance = 0.3
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 12, "AI second brain")
+ assert big in kept
+
+
+def _cand(i, source, rrf, *, relevance=0.5, score=0, ncmt=0, title="Kanye West item"):
+ item = schema.SourceItem(
+ item_id=f"{source}{i}",
+ source=source,
+ title=f"{title} {i}",
+ body=f"{title} {i}",
+ url=f"https://example.com/{source}/{i}",
+ engagement={"score": score, "num_comments": ncmt},
+ )
+ return schema.Candidate(
+ candidate_id=f"{source}-{i}",
+ item_id=item.item_id,
+ source=source,
+ title=item.title,
+ url=item.url,
+ snippet="",
+ subquery_labels=["primary"],
+ native_ranks={f"primary:{source}": i + 1},
+ local_relevance=relevance,
+ freshness=80,
+ engagement=5.0,
+ source_quality=0.7,
+ rrf_score=rrf,
+ sources=[source],
+ source_items=[item],
+ )
+
+
+class TestPoolReservation:
+ def _fused(self):
+ fused = [_cand(i, "tiktok", 0.05 - i * 0.0005) for i in range(45)]
+ fused += [_cand(i, "reddit", 0.001 - i * 0.00001, score=1, ncmt=1) for i in range(5)]
+ return fused
+
+ def test_top_engagement_reddit_candidate_is_reserved_at_default_depth(self):
+ fused = self._fused()
+ big = _cand(99, "reddit", 0.0001, relevance=0.19, score=16180, ncmt=1450)
+ fused.append(big)
+ pool = fusion._diversify_pool(fused, 40, entity="kanye west")
+ assert len(pool) == 40
+ assert big in pool
+
+ def test_out_of_window_reddit_candidate_is_not_reserved(self):
+ fused = self._fused()
+ big = _cand(99, "reddit", 0.0001, relevance=0.19, score=16180, ncmt=1450)
+ big.metadata["range_from"] = "2026-08-01"
+ big.metadata["range_to"] = "2026-08-31"
+ big.source_items[0].published_at = "2025-01-01"
+ big.source_items[0].date_confidence = "high"
+ fused.append(big)
+ pool = fusion._diversify_pool(fused, 40, entity="kanye west")
+ assert big not in pool
+
+ def test_entity_miss_reddit_candidate_is_not_reserved(self):
+ fused = self._fused()
+ big = _cand(99, "reddit", 0.0001, relevance=0.19, score=16180, ncmt=1450, title="Unrelated viral thread")
+ fused.append(big)
+ pool = fusion._diversify_pool(fused, 40, entity="kanye west")
+ assert big not in pool
+
+ def test_reservation_scales_with_pool_limit(self):
+ assert fusion._reddit_reserve_for(15) == 2
+ assert fusion._reddit_reserve_for(40) == 3
+ assert fusion._reddit_reserve_for(60) == 4
+
+
+class TestKeeperAndReservationBounds:
+ def test_keepers_never_exceed_the_stream_limit(self):
+ items = [_reddit_item(i, score=1000 - i, ncmt=50, relevance=0.5, rank=0.5 - i * 0.01) for i in range(10)]
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 1, "Kanye West")
+ assert len(kept) == 1
+ kept = pipeline._apply_reddit_stream_keepers("reddit", items, 0, "Kanye West")
+ assert kept == []
+
+ def test_reservation_survives_many_qualifying_sources(self):
+ fused = []
+ for source in ("tiktok", "x", "youtube", "hackernews", "grounding", "instagram", "github", "linkedin"):
+ fused += [_cand(i, source, 0.05 - i * 0.0005) for i in range(4)]
+ big = _cand(99, "reddit", 0.0001, relevance=0.19, score=16180, ncmt=1450)
+ fused.append(big)
+ pool = fusion._diversify_pool(fused, 15, entity="kanye west")
+ assert len(pool) == 15
+ assert big in pool
diff --git a/tests/test_reddit_transport_outcomes.py b/tests/test_reddit_transport_outcomes.py
index 46bad8ca..411cd8f0 100644
--- a/tests/test_reddit_transport_outcomes.py
+++ b/tests/test_reddit_transport_outcomes.py
@@ -11,7 +11,7 @@ capture sink -> source outcome -> postmortem bucket -- stays honest.
import urllib.error
from unittest import mock
-from lib import doctor, pipeline, schema
+from lib import doctor, http, pipeline, schema
def _plan(source):
@@ -100,3 +100,176 @@ def test_postmortem_does_not_claim_success_after_a_reddit_block():
assert "Succeeded: reddit" not in text
assert "Failed:" in text
assert schema.RATE_LIMITED in text
+
+
+def test_items_delivered_with_swallowed_lane_403_are_not_branded():
+ """Regression (datacenter egress): a source that returns items must not be
+ branded auth-failed/partial by a swallowed lane-level 403.
+
+ On hosts where Reddit blocks the shreddit partials (HTTP 403), the capture
+ sink records those failures even though the keyless lanes delivered items.
+ Before the fix, ``_retrieve_stream`` attached the captured failure as the
+ source outcome and the run reported ``auth-failed`` / ``partial after N
+ items: HTTP 403: Blocked`` for a source that actually succeeded.
+ """
+ lane_error = http.HTTPError(
+ "https://www.reddit.com/svc/shreddit/community-more-posts/top/?name=tea",
+ status_code=403,
+ body=b"Blocked",
+ )
+ subquery = schema.SubQuery(
+ label="primary",
+ search_query="matcha tea trends",
+ ranking_query="matcha tea trends",
+ sources=["reddit"],
+ )
+ with mock.patch.object(
+ pipeline,
+ "_retrieve_stream_impl",
+ return_value=([{"url": "https://www.reddit.com/r/tea/comments/abc/"}], {}),
+ ), mock.patch.object(http, "capture_failures") as cf, mock.patch.object(
+ http, "fixture_module_capture"
+ ):
+ cf.return_value.__enter__.return_value = [lane_error]
+ cf.return_value.__exit__.return_value = False
+ items, artifact = pipeline._retrieve_stream(
+ source="reddit",
+ topic="matcha tea trends",
+ subquery=subquery,
+ config={},
+ depth="quick",
+ date_range=("2026-07-08", "2026-08-08"),
+ runtime=schema.ProviderRuntime("local", "test-planner", "test-reranker"),
+ mock=False,
+ web_backend="auto",
+ )
+
+ assert items, "the run delivered items"
+ assert "_source_outcome" not in artifact, (
+ "swallowed lane failures must not brand a source that returned items"
+ )
+
+
+def test_swallowed_lane_403_still_brands_when_no_items_returned():
+ """The no-items case keeps the transport-failure outcome (issue #899): the
+ captured failure must still surface so doctor can prescribe a fix."""
+ lane_error = http.HTTPError(
+ "https://www.reddit.com/svc/shreddit/community-more-posts/top/?name=tea",
+ status_code=403,
+ body=b"Blocked",
+ )
+ subquery = schema.SubQuery(
+ label="primary",
+ search_query="matcha tea trends",
+ ranking_query="matcha tea trends",
+ sources=["reddit"],
+ )
+ with mock.patch.object(
+ pipeline, "_retrieve_stream_impl", return_value=([], {})
+ ), mock.patch.object(http, "capture_failures") as cf, mock.patch.object(
+ http, "fixture_module_capture"
+ ):
+ cf.return_value.__enter__.return_value = [lane_error]
+ cf.return_value.__exit__.return_value = False
+ items, artifact = pipeline._retrieve_stream(
+ source="reddit",
+ topic="matcha tea trends",
+ subquery=subquery,
+ config={},
+ depth="quick",
+ date_range=("2026-07-08", "2026-08-08"),
+ runtime=schema.ProviderRuntime("local", "test-planner", "test-reranker"),
+ mock=False,
+ web_backend="auto",
+ )
+
+ assert not items
+ assert artifact.get("_source_outcome", {}).get("state") == schema.AUTH_FAILED
+
+
+def test_items_delivered_with_swallowed_lane_failure_carry_detail():
+ """A source that delivered items keeps ``ok`` but records what was lost, so
+ ``doctor --postmortem`` can still show the swallowed sub-request failures."""
+ lane_error = http.HTTPError(
+ "https://www.reddit.com/svc/shreddit/community-more-posts/top/?name=tea",
+ status_code=429,
+ body=b"Too Many Requests",
+ )
+ subquery = schema.SubQuery(
+ label="primary",
+ search_query="matcha tea trends",
+ ranking_query="matcha tea trends",
+ sources=["reddit"],
+ )
+ with mock.patch.object(
+ pipeline,
+ "_retrieve_stream_impl",
+ return_value=([{"url": "https://www.reddit.com/r/tea/comments/abc/"}], {}),
+ ), mock.patch.object(http, "capture_failures") as cf, mock.patch.object(
+ http, "fixture_module_capture"
+ ):
+ cf.return_value.__enter__.return_value = [lane_error, lane_error]
+ cf.return_value.__exit__.return_value = False
+ items, artifact = pipeline._retrieve_stream(
+ source="reddit",
+ topic="matcha tea trends",
+ subquery=subquery,
+ config={},
+ depth="quick",
+ date_range=("2026-07-08", "2026-08-08"),
+ runtime=schema.ProviderRuntime("local", "test-planner", "test-reranker"),
+ mock=False,
+ web_backend="auto",
+ )
+
+ assert items
+ assert "_source_outcome" not in artifact
+ detail = artifact.get("_source_outcome_detail") or ""
+ assert "2 sub-requests" in detail
+ assert "429" in detail
+
+
+def test_postmortem_shows_lane_detail_on_succeeded_source():
+ outcome = schema.SourceOutcome(
+ source="reddit",
+ state="ok",
+ items_returned=36,
+ attempted=True,
+ detail="3 sub-requests rate-limited (HTTP 429)",
+ )
+ pm = {
+ "engine_version": "test",
+ "mode": "postmortem",
+ "present": True,
+ "topic": "kanye west",
+ "at": outcome.at,
+ "outcomes": {"reddit": schema.to_dict(outcome)},
+ }
+
+ text = doctor.render_postmortem_text(pm)
+
+ assert "Failed:" not in text
+ assert "Partial:" not in text
+ assert "Succeeded: reddit (36 items; 3 sub-requests rate-limited (HTTP 429))" in text
+
+
+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"
+ )
+ subquery = schema.SubQuery(
+ label="primary", search_query="matcha", ranking_query="matcha", sources=["reddit"],
+ )
+ with mock.patch.object(
+ pipeline, "_retrieve_stream_impl",
+ return_value=([{"url": "https://www.reddit.com/r/tea/comments/abc/"}], {}),
+ ), mock.patch.object(http, "capture_failures") as cf, mock.patch.object(http, "fixture_module_capture"):
+ cf.return_value.__enter__.return_value = [lane_error]
+ cf.return_value.__exit__.return_value = False
+ _items, artifact = pipeline._retrieve_stream(
+ source="reddit", topic="matcha", subquery=subquery, config={}, depth="quick",
+ date_range=("2026-07-08", "2026-08-08"),
+ runtime=schema.ProviderRuntime("local", "test-planner", "test-reranker"),
+ mock=False, web_backend="auto",
+ )
+ assert artifact["_source_outcome_detail_state"] == schema.RATE_LIMITED
diff --git a/tests/test_registers.py b/tests/test_registers.py
index ae3fb688..6ebbde80 100644
--- a/tests/test_registers.py
+++ b/tests/test_registers.py
@@ -155,7 +155,10 @@ def _bullet_count(output: str, heading: str) -> int:
"creator",
["Best Takes", "Top Community Comments", "Stats", "Ranked Evidence Clusters", "Source Coverage"],
6,
- 6,
+ # The register's own top_comments budget. It used to read 6 only
+ # because the comments pool was limited to the 6 visible clusters;
+ # the pool now spans every floor-clearing cluster.
+ 8,
),
],
)
@@ -203,9 +206,11 @@ def test_default_register_is_byte_identical_when_omitted(monkeypatch):
assert implicit == explicit
assert hashlib.sha256(implicit.encode()).hexdigest() == (
- # Hash includes #886's linked evidence URLs and #890's Hacker News
- # comment-rendering changes from main.
- "351089b5c0eae7ef55bcfd35cc23a6eca1008a7f3d8c28e3266fe351a788c985"
+ # Hash includes #886's linked evidence URLs, #890's Hacker News
+ # comment-rendering changes, the quiet footer (no outcome text, no
+ # ## Source Errors in compact), and the comments pool reading every
+ # floor-clearing cluster.
+ "81fdfc85643d124f2c06ff0bac8956c30280c652436bc4a58dbfc37718be71e1"
)
diff --git a/tests/test_render_footer.py b/tests/test_render_footer.py
index d862768b..514d6d90 100644
--- a/tests/test_render_footer.py
+++ b/tests/test_render_footer.py
@@ -155,9 +155,11 @@ def test_library_block_and_explainer_absent_when_empty():
assert "Prior saved runs" not in text
-def test_footer_keeps_partial_populated_source_with_warning():
+def test_footer_keeps_partial_populated_source_without_warning_text():
"""A source that returned SOME items but then failed stays in the footer
- with its ⚠ suffix - only zero-item sources are dropped."""
+ as counts only: run diagnostics live in doctor --postmortem, the saved raw
+ file, and the model-facing ## Partial Coverage note, never on the
+ user-facing conclusion surface."""
ig_item = schema.SourceItem(
item_id="ig1",
source="instagram",
@@ -182,7 +184,71 @@ def test_footer_keeps_partial_populated_source_with_warning():
text = render.render_compact(report)
assert "📸 Instagram: 1 reel" in text
- assert "⚠" in text # partial suffix preserved on the populated line
+ footer = text.split("✅ All agents reported back!", 1)[1]
+ assert "⚠" not in footer
+ assert "run doctor" not in footer
+ assert "## Partial Coverage" in text
+ assert "Instagram" in text.split("## Partial Coverage", 1)[1].split("\n\n", 1)[0] or "Instagram partial" in text
+
+
+def test_footer_auth_failed_populated_source_has_no_warning_text():
+ ig_item = schema.SourceItem(
+ item_id="ig1",
+ source="instagram",
+ title="A reel",
+ body="caption",
+ url="https://instagram.com/reel/1",
+ )
+ report = _report(
+ items_by_source={"reddit": [_reddit_item()], "instagram": [ig_item]},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
+ "instagram": schema.SourceOutcome(
+ source="instagram",
+ state=schema.AUTH_FAILED,
+ items_returned=1,
+ detail="HTTP 401",
+ fix_hint="doctor",
+ ),
+ },
+ )
+
+ text = render.render_compact(report)
+ footer = text.split("✅ All agents reported back!", 1)[1]
+
+ assert "📸 Instagram: 1 reel" in footer
+ assert "⚠" not in footer
+ assert "auth-failed" in text.split("## Partial Coverage", 1)[1]
+
+
+def test_compact_drops_source_failure_warnings_and_source_errors_block():
+ report = _report(
+ items_by_source={"reddit": [_reddit_item()]},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
+ "jobs": schema.SourceOutcome(source="jobs", state=schema.UNREACHABLE, items_returned=0, detail="DNS"),
+ },
+ )
+ report.warnings = [
+ "Some sources failed: jobs",
+ "Some sources returned partial results (degraded): reddit",
+ "Evidence is thin for this topic.",
+ ]
+ report.errors_by_source = {"jobs": "URL Error: nodename nor servname provided"}
+
+ compact = render.render_compact(report)
+ assert "## Source Errors" not in compact
+ assert "Some sources failed" not in compact
+ assert "returned partial results" not in compact
+ assert "Evidence is thin for this topic." in compact
+
+ full = render.render_full(report)
+ assert "## Source Errors" in full
+
+ payload = schema.to_dict(report)
+ assert payload["warnings"] == report.warnings
+ assert payload["errors_by_source"] == {"jobs": "URL Error: nodename nor servname provided"}
+ assert payload["source_status"]["jobs"]["state"] == schema.UNREACHABLE
def test_footer_carries_freshness_verdict():
diff --git a/tests/test_render_v3.py b/tests/test_render_v3.py
index 83a386f0..34cf1114 100644
--- a/tests/test_render_v3.py
+++ b/tests/test_render_v3.py
@@ -129,11 +129,13 @@ class RenderV3Tests(unittest.TestCase):
self.assertIn("Top clusters:", text)
self.assertIn("Grounded result", text)
- def test_render_compact_includes_source_errors_section(self):
+ def test_render_compact_omits_source_errors_section(self):
+ # Source errors are diagnostics: the saved raw file (render_full) and
+ # doctor --postmortem carry them; compact stdout does not.
report = sample_report()
report.errors_by_source = {"x": "HTTP 400: Bad Request"}
- text = render.render_compact(report)
- self.assertIn("## Source Errors", text)
+ self.assertNotIn("## Source Errors", render.render_compact(report))
+ self.assertIn("## Source Errors", render.render_full(report))
def test_failed_x_bookmark_workflow_query_emits_no_solid_floor(self):
"""Regression: generic token overlap must not turn all-zero X noise
diff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.py
index 27bbca48..8a78c212 100644
--- a/tests/test_source_outcomes.py
+++ b/tests/test_source_outcomes.py
@@ -559,3 +559,45 @@ def test_captured_failure_selection_prefers_most_specific():
for failures in ([auth, rate], [rate, auth]):
outcome = pipeline._resolve_stream_outcome("x", None, failures)
assert outcome["state"] == schema.AUTH_FAILED
+
+
+def test_bundle_keeps_ok_with_lane_detail_across_subqueries():
+ """A swallowed lane failure on a source that delivered items stays ``ok``
+ and carries the loss as detail; a later clean subquery keeps that detail."""
+ item = schema.SourceItem(
+ item_id="r1",
+ source="reddit",
+ title="A thread",
+ body="body",
+ url="https://www.reddit.com/r/test/comments/abc/",
+ )
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("reddit")
+ bundle.record_detail("reddit", "3 sub-requests rate-limited (HTTP 429)")
+ bundle.add_items("primary", "reddit", [item])
+
+ outcome = bundle.source_status["reddit"]
+ assert outcome.state == health.OK
+ assert outcome.items_returned == 1
+ assert outcome.detail == "3 sub-requests rate-limited (HTTP 429)"
+ assert outcome.fix_hint is None
+
+ bundle.add_items("secondary", "reddit", [])
+ outcome = bundle.source_status["reddit"]
+ assert outcome.state == health.OK
+ assert outcome.detail == "3 sub-requests rate-limited (HTTP 429)"
+
+
+def test_finalize_turns_an_empty_ok_source_with_lane_failures_into_that_failure():
+ """Zero items after filtering plus swallowed 429s is not 'completed cleanly
+ with zero matches'; it is the rate limit, so ## Partial Coverage fires and
+ doctor does not list the source as succeeded."""
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("polymarket")
+ bundle.record_detail("polymarket", "5 sub-requests rate-limited (HTTP 429)", state=schema.RATE_LIMITED)
+ bundle.add_items("primary", "polymarket", [])
+ finalized = pipeline._finalize_source_status(bundle.source_status, {"polymarket": []})
+ outcome = finalized["polymarket"]
+ assert outcome.state == schema.RATE_LIMITED
+ assert outcome.detail == "5 sub-requests rate-limited (HTTP 429)"
+ assert outcome.items_returned == 0
diff --git a/tests/test_top_comments_relevance.py b/tests/test_top_comments_relevance.py
index 32e31223..21584d3f 100644
--- a/tests/test_top_comments_relevance.py
+++ b/tests/test_top_comments_relevance.py
@@ -180,3 +180,56 @@ class TestTopCommentsRelevanceGate:
lines = render._render_top_comments(report)
occurrences = sum(1 for line in lines if "Shared comment body" in line)
assert occurrences == 1
+
+
+def _cluster(index: int, candidate: schema.Candidate, score: float) -> schema.Cluster:
+ return schema.Cluster(
+ cluster_id=f"cluster-{index}",
+ title=candidate.title,
+ candidate_ids=[candidate.candidate_id],
+ representative_ids=[candidate.candidate_id],
+ sources=[candidate.source],
+ score=score,
+ uncertainty=None,
+ )
+
+
+class TestTopCommentsReadAllFloorClearingClusters:
+ """The comments block is a cross-cutting evidence surface: a strong comment
+ on a thread in cluster eleven must render even though only the top eight
+ clusters are shown in ## Ranked Evidence Clusters."""
+
+ def _report(self):
+ candidates = []
+ clusters = []
+ for i in range(12):
+ comments = None
+ if i == 10: # cluster 11, below the compact cluster_limit of 8
+ comments = [
+ {"score": 3293, "author": "u/tableleg7", "excerpt": "Vladimir Putin doesn't care about black people"},
+ {"score": 1151, "author": "u/stereosalvation", "excerpt": "Someone didn't get paid off yet"},
+ {"score": 400, "author": "u/third", "excerpt": "third comment body here"},
+ ]
+ cand = _candidate(
+ title=f"Thread {i}",
+ url=f"https://www.reddit.com/r/Kanye/comments/t{i}/",
+ local_relevance=0.6,
+ top_comments=comments if comments else [],
+ )
+ cand.final_score = 60.0 - i
+ candidates.append(cand)
+ clusters.append(_cluster(i + 1, cand, cand.final_score))
+ report = _make_report(*candidates)
+ report.clusters = clusters
+ return report
+
+ def test_comment_from_cluster_eleven_renders_in_compact(self):
+ text = render.render_compact(self._report(), cluster_limit=8)
+ assert "## Top Community Comments" in text
+ assert "Vladimir Putin doesn't care about black people" in text
+
+ def test_entity_miss_cluster_member_still_excluded(self):
+ report = self._report()
+ report.ranked_candidates[10].explanation = "fallback-local-score (entity-miss demotion)"
+ text = render.render_compact(report, cluster_limit=8)
+ assert "Vladimir Putin doesn't care" not in text