Skip to content

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

fix(youtube): honor inclusive as-of end dates in searches (#1273)

Jay Hemnani1dd5ac7cee52
diff --git a/changelog.d/+youtube-as-of-end-date.fixed.md b/changelog.d/+youtube-as-of-end-date.fixed.md
new file mode 100644
index 00000000..47cd3bf6
--- /dev/null
+++ b/changelog.d/+youtube-as-of-end-date.fixed.md
@@ -0,0 +1 @@
+YouTube no longer keeps videos published after the end of an `--as-of` window, so a historical report cannot cite later videos or spend its transcript budget on them. Cached and concurrent searches use the complete date window, including its inclusive end date.
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index 7c6ad664..9c12ed94 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -82,8 +82,8 @@ _ytdlp_slots = threading.Semaphore(_YTDLP_MAX_CONCURRENT)
# every entity sub-run; cache hits avoid the redundant expensive --dump-json work.
# Inflight coalescing prevents N concurrent identical searches from all missing
# the cache and stampeding YouTube together.
-_search_cache: Dict[Tuple[str, int, str], Dict[str, Any]] = {}
-_search_inflight: Dict[Tuple[str, int, str], tuple[threading.Event, list]] = {}
+_search_cache: Dict[Tuple[str, int, str, str, Optional[str]], Dict[str, Any]] = {}
+_search_inflight: Dict[Tuple[str, int, str, str, Optional[str]], tuple[threading.Event, list]] = {}
_search_cache_lock = threading.Lock()
# Comments are enrichment, not core evidence: keep the budget tight so a slow
# comment API can never dominate a run's wall clock (bounded to 3 videos).
@@ -198,7 +198,7 @@ def _run_ytdlp(cmd: List[str], *, timeout: float) -> subproc.SubprocResult:
def _claim_search_slot(
- cache_key: Tuple[str, int, str],
+ cache_key: Tuple[str, int, str, str, Optional[str]],
) -> tuple[Optional[Dict[str, Any]], Optional[threading.Event], Optional[list], bool]:
"""Return ``(cached, event, slot, is_leader)`` for search coalesce.
@@ -220,7 +220,7 @@ def _claim_search_slot(
def _finish_search_slot(
- cache_key: Tuple[str, int, str],
+ cache_key: Tuple[str, int, str, str, Optional[str]],
payload: Dict[str, Any],
*,
event: threading.Event,
@@ -489,14 +489,17 @@ _RECENT_FRESHNESS_MODES = frozenset({"strict_recent", "balanced_recent"})
def _apply_date_window(
items: List[Dict[str, Any]],
from_date: str,
+ to_date: str,
freshness_mode: Optional[str],
) -> List[Dict[str, Any]]:
"""Prefer in-window videos; scope the keep-all fallback by freshness mode.
+ Videos published after ``to_date`` (an --as-of window) are never kept.
3+ in-window videos: keep only those (every mode). Fewer: recent modes
keep only the in-window ones; evergreen_ok and unknown/None keep all so
evergreen topics can still fall back to older videos.
"""
+ items = [i for i in items if not (i["date"] and i["date"] > to_date)]
recent = [i for i in items if i["date"] and i["date"] >= from_date]
if len(recent) >= 3:
_log(f"Found {len(recent)} videos within date range")
@@ -536,7 +539,7 @@ def search_youtube(
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
core_topic = _extract_core_subject(topic)
- cache_key = (core_topic, count, from_date, freshness_mode)
+ cache_key = (core_topic, count, from_date, to_date, freshness_mode)
timeout = _search_timeout()
cached, event, slot, is_leader = _claim_search_slot(cache_key)
@@ -645,7 +648,7 @@ def search_youtube(
# Date filter: prefer recent items; the keep-all fallback is scoped
# by freshness mode (evergreen only), see _apply_date_window.
- items = _apply_date_window(items, from_date, freshness_mode)
+ items = _apply_date_window(items, from_date, to_date, freshness_mode)
# Sort by views descending
items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
@@ -1667,7 +1670,7 @@ def search_youtube_sc(
})
# Date filter (keep-all fallback scoped by freshness mode)
- items = _apply_date_window(items, from_date, freshness_mode)
+ items = _apply_date_window(items, from_date, to_date, freshness_mode)
# Sort by views
items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index 2d15d016..4d424007 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -1748,7 +1748,7 @@ class TestYouTubeSearchTimeoutAndCache(unittest.TestCase):
"""A leader that outlives reset_search_cache must not drop the new slot."""
import threading
- key = ("ownership", 8, "2026-06-01")
+ key = ("ownership", 8, "2026-06-01", "2026-07-01", None)
old_event = threading.Event()
old_slot: list = [None]
new_event = threading.Event()
@@ -1874,13 +1874,13 @@ class TestYouTubeDateWindowByFreshnessMode(unittest.TestCase):
]
return "\n".join(json.dumps(v) for v in videos)
- def _search(self, dates, freshness_mode):
+ def _search(self, dates, freshness_mode, to_date=None):
from lib.subproc import SubprocResult
result = SubprocResult(returncode=0, stdout=self._ytdlp_stdout(dates), stderr="")
with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result):
return youtube_yt.search_youtube(
- "Ghostty terminal", self.FROM, self.TO, freshness_mode=freshness_mode,
+ "Ghostty terminal", self.FROM, to_date or self.TO, freshness_mode=freshness_mode,
)
def test_ytdlp_balanced_recent_with_no_in_range_videos_keeps_nothing(self):
@@ -1911,6 +1911,62 @@ class TestYouTubeDateWindowByFreshnessMode(unittest.TestCase):
self.assertEqual(len(self._search(dates, "evergreen_ok")["items"]), 2)
self.assertEqual(self._search(dates, "balanced_recent")["items"], [])
+ def test_ytdlp_search_cache_separates_end_dates_in_both_orders(self):
+ dates = ["2026-10-01", self.TO, "2026-10-20"]
+ for end_dates in (("2026-10-01", self.TO), (self.TO, "2026-10-01")):
+ with self.subTest(end_dates=end_dates):
+ youtube_yt.reset_search_cache()
+ results = {
+ end: self._search(dates, "evergreen_ok", to_date=end)
+ for end in end_dates
+ }
+ self.assertEqual(
+ {i["video_id"] for i in results["2026-10-01"]["items"]}, {"v0"},
+ )
+ self.assertEqual(
+ {i["video_id"] for i in results[self.TO]["items"]}, {"v0", "v1"},
+ )
+
+ def test_ytdlp_inflight_searches_separate_end_dates(self):
+ import threading
+ from concurrent.futures import ThreadPoolExecutor
+ from lib.subproc import SubprocResult
+
+ started = threading.Event()
+ release = threading.Event()
+ result = SubprocResult(
+ returncode=0,
+ stdout=self._ytdlp_stdout(["2026-10-01", self.TO, "2026-10-20"]),
+ stderr="",
+ )
+
+ def slow_first_search(*_args, **_kwargs):
+ if not started.is_set():
+ started.set()
+ self.assertTrue(release.wait(timeout=10), "first search was not released")
+ return result
+
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_first_search), \
+ ThreadPoolExecutor(max_workers=2) as pool:
+ first = pool.submit(
+ youtube_yt.search_youtube, "Ghostty terminal", self.FROM, "2026-10-01",
+ freshness_mode="evergreen_ok",
+ )
+ try:
+ self.assertTrue(started.wait(timeout=5), "first search did not start")
+ second = pool.submit(
+ youtube_yt.search_youtube, "Ghostty terminal", self.FROM, self.TO,
+ freshness_mode="evergreen_ok",
+ )
+ later = second.result(timeout=5)
+ finally:
+ release.set()
+ earlier = first.result(timeout=5)
+
+ self.assertEqual({i["video_id"] for i in earlier["items"]}, {"v0"})
+ self.assertEqual({i["video_id"] for i in later["items"]}, {"v0", "v1"})
+
def test_search_and_transcribe_threads_freshness_mode(self):
from lib.subproc import SubprocResult
result = SubprocResult(
@@ -1957,6 +2013,18 @@ class TestYouTubeDateWindowByFreshnessMode(unittest.TestCase):
out = self._sc_search(["2017-03-01", "2020-05-05"], None)
self.assertEqual({i["video_id"] for i in out["items"]}, {"s0", "s1"})
+ def test_ytdlp_drops_videos_published_after_window_end(self):
+ # --as-of window: videos uploaded after TO are neither in range nor a fallback.
+ dates = ["2026-10-20", "2026-11-01", "2026-12-01", "2026-10-01", "2017-03-01", self.TO]
+ out = self._search(dates, "evergreen_ok")
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"v3", "v4", "v5"})
+
+ def test_sc_drops_videos_published_after_window_end(self):
+ out = self._sc_search(
+ ["2026-10-20", "2026-11-01", "2026-12-01", "2017-03-01", self.TO], "evergreen_ok",
+ )
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"s3", "s4"})
+
if __name__ == "__main__":
unittest.main()