Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133#!/usr/bin/env python3"""The backfill crawler — the pool's second feed besides the firehose.
The firehose only sees posts *after* it starts listening. Backfill searcheseach indexed keyword's recent posts so the pool is not only forward-filled:every full postView is normalized (which also fills in the handle anddisplay name a firehose frame never carries) and added to the pool, thenfit-checked against the topics whose region it falls in.
Runs on the worker's housekeeping interval, a bounded number of keywords percall so the operator's search account is not hammered.
`prune_keywords` is the filter-management half: a keyword with no observedmatch for PRUNE_AFTER_DAYS is pruned off the firehose filter. Its posts stayin the pool — only the retrieval signal is retired."""
import datetimeimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).parent.parentsys.path.insert(0, str(ROOT))
from shared.post_index import extract # noqa: E402from shared.search_posts import build_query # noqa: E402from shared.embed import embed # noqa: E402from feed import state, store # noqa: E402from feed.common import parse_created # noqa: E402
BACKFILL_KEYWORDS_PER_RUN = int( __import__("os").environ.get("FEEDS_BACKFILL_KW", "5"))
def _recent(term: str, cutoff: datetime.datetime, limit: int = 100) -> list[dict]: """The term's newest posts still inside the window, as postViews.""" from shared.apppass import xrpc_get query = build_query([term]) page = xrpc_get("app.bsky.feed.searchPosts", {"q": query, "sort": "latest", "limit": limit}) views = page.get("posts") or [] fresh: list[dict] = [] for v in views: when = parse_created(((v.get("record") or {}).get("createdAt") or "")) if when is not None and when >= cutoff: fresh.append(v) return fresh
def backfill_once() -> int: """Search a bounded number of indexed keywords, add their fresh posts to the pool, and fit-check each against the topics whose region it falls in. Returns how many posts were pooled.""" from feed.topics import pass_post cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta( days=state.WINDOW_DAYS) keywords = store.indexed_keywords()[:BACKFILL_KEYWORDS_PER_RUN] if not keywords: return 0 pooled = 0 for kw in keywords: term = kw["keyword"] try: views = _recent(term, cutoff) except Exception: # noqa: BLE001 — one broken keyword is not a broken run continue if not views: continue rows = [] now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) for v in views: c = extract(v) if not c["text"].strip(): continue rows.append({ "uri": c["uri"], "handle": c.get("handle", ""), "did": c.get("did", ""), "displayName": c.get("displayName", ""), "text": c["text"], "source_keyword": term, "createdAt": c.get("createdAt", ""), "replyTo": c.get("replyTo", ""), "media": "|".join(c.get("media") or []), "likeCount": c.get("likeCount", 0), "replyCount": c.get("replyCount", 0), "repostCount": c.get("repostCount", 0), "first_seen": now, "last_seen": now, }) if rows: # Only the posts not already in the pool need writing, and they # need an embedding first — an un-embedded post is a zombie that # breaks every vector search. Existing posts are untouched here # (their embedding is already stored); touch_keyword is the # aliveness signal. fresh = [r for r in rows if not store.get_post(r["uri"])] if fresh: try: vecs = embed([r["text"] for r in fresh]) except Exception as e: # noqa: BLE001 — a flaky embed must print(f"backfill embed failed for {term!r}: {e}", # not file=sys.stderr) # pool fresh = [] # zombies else: for r, v in zip(fresh, vecs): r["embedding"] = v store.add_posts(fresh) pooled += len(fresh) store.touch_keyword(term, post_count=len(views)) for r in rows: try: pass_post(r["uri"]) except Exception: # noqa: BLE001 — judgement is per-post continue return pooled
def prune_keywords() -> int: """Retire indexed keywords with no observed match in PRUNE_AFTER_DAYS. Returns how many were pruned. The pool keeps their posts.""" cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta( days=state.PRUNE_AFTER_DAYS) pruned = 0 for kw in store.indexed_keywords(): last = parse_created(kw.get("last_seen") or "") if last is None or last < cutoff: store.update_keyword(kw["keyword"], status="pruned") pruned += 1 return pruned
if __name__ == "__main__": n = backfill_once() print(f"backfill pooled {n} post(s)", file=sys.stderr)