Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434#!/usr/bin/env python3"""The background worker: watch the firehose for posts and keep the poolhealthy.
One event comes off Jetstream:
1. **app.bsky.feed.post** — a post whose text matches an indexed keyword is embedded into the pool and fit-checked against the topics whose region it falls in (feed/topics.pass_post). Keywords are retrieval only; membership is embedding + judge, decided here at add time.
Topics are not a firehose event. The app creates a topic the moment itsrequest record is written; the worker's periodic `sweep_requests` is only asafety net for requests written from another client.
Periodic housekeeping runs every `--interval` seconds: re-run every topic'smembership pass (pick up what the pool gained), prune keywords with noobserved matches, and run the backfill crawler (ingest/backfill.py) so thepool is not only forward-filled.
python3 ingest/worker.py # run forever python3 ingest/worker.py --once # one jetstream batch, then exit
Jetstream needs a websocket client; that is the venv's second non-stdlibdependency (websockets). The rest is stdlib."""
import argparseimport asyncioimport jsonimport osimport sysimport timeimport urllib.errorimport urllib.parseimport urllib.requestfrom pathlib import Path
ROOT = Path(__file__).parent.parentsys.path.insert(0, str(ROOT))
from shared.embed import embed # noqa: E402from feed import store, topics # noqa: E402
JETSTREAM_URL = os.environ.get( "JETSTREAM_URL", "wss://jetstream2.us-east.bsky.network/subscribe" "?wantedCollections=app.bsky.feed.post" "&wantedCollections=click.aligned.feed.request")POST_TYPE = "app.bsky.feed.post"REQUEST_TYPE = "click.aligned.feed.request"
HOUSEKEEP_INTERVAL = int(os.environ.get("FEEDS_HOUSEKEEP", "900")) # 15 minKEYWORD_REFRESH = int(os.environ.get("FEEDS_KW_REFRESH", "120")) # 2 min# How long one firehose connection stays open before run_once yields back to# main_loop, so housekeeping and the keyword-refresh run on schedule instead of# only when the connection happens to drop. --once uses a short round.RUN_DURATION = int(os.environ.get("FEEDS_RUN_DURATION", "60"))ONCE_DURATION = int(os.environ.get("FEEDS_ONCE_DURATION", "15"))
from shared.log import log # noqa: E402 — the tailable runtime log (stderr + file)
# --- keyword matching ---------------------------------------------------------
def _normalize(text: str) -> str: return " ".join(text.lower().split())
def _phrase_terms(keywords: list[dict]) -> tuple[list[str], list[str]]: """Split indexed keywords into single words (word-boundary match) and phrases (plain substring). Single-word terms match on word boundaries so "repair" does not match "repaired".""" words: list[str] = [] phrases: list[str] = [] for kw in keywords: term = (kw.get("keyword") or "").strip().lower() if " " in term: phrases.append(term) else: words.append(term) return words, phrases
def matching_keywords(text: str, words: list[str], phrases: list[str]) -> list[str]: """The indexed keywords a post's text matches, retrieval-only.""" norm = _normalize(text) if not norm: return [] hits: list[str] = [] for p in phrases: if p in norm: hits.append(p) tokens = set(norm.split()) for w in words: if w in tokens: hits.append(w) return hits
# --- post ingestion -----------------------------------------------------------
def _post_row(frame: dict) -> dict | None: """A synthetic pool row from a firehose post frame. The firehose knows the DID and the record, not the handle/displayName — those come later from the backfill's full postViews, and the narrow merge keeps them.""" did = frame.get("did") or "" commit = frame.get("commit") or {} if commit.get("operation") != "create": return None record = commit.get("record") or {} text = (record.get("text") or "").strip() if not text: return None uri = f"at://{did}/{commit.get('collection')}/{commit.get('rkey')}" now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) return { "uri": uri, "did": did, "text": text, "createdAt": record.get("createdAt", ""), "replyTo": (record.get("reply") or {}).get("parent", {}).get("uri", ""), "likeCount": 0, "replyCount": 0, "repostCount": 0, "embedding": None, "source_keyword": "", "first_seen": now, "last_seen": now, }
# --- request-record catch-up -------------------------------------------------
def _pds_for(did: str) -> str: """The PDS holding a DID's repo, read from the PLC directory.""" try: with urllib.request.urlopen(f"https://plc.directory/{urllib.parse.quote(did)}", timeout=15) as r: doc = json.loads(r.read()) except (urllib.error.HTTPError, OSError, json.JSONDecodeError) as e: raise RuntimeError(f"cannot locate PDS for {did}: {e}") from None for service in doc.get("service") or []: if service.get("type") == "AtprotoPersonalDataServer": return service["serviceEndpoint"].rstrip("/") raise RuntimeError(f"no PDS in the DID document for {did}")
def _request_records(did: str, pds: str) -> list[dict]: """Every click.aligned.feed.request record in a repo, paged with a cursor — the same shape read.aligned.click uses to read chat sessions.""" items: list[dict] = [] cursor = "" while True: params = {"repo": did, "collection": REQUEST_TYPE, "limit": 100} if cursor: params["cursor"] = cursor url = f"{pds}/xrpc/com.atproto.repo.listRecords?{urllib.parse.urlencode(params)}" try: with urllib.request.urlopen(url, timeout=15) as r: page = json.loads(r.read()) except (urllib.error.HTTPError, OSError, json.JSONDecodeError) as e: raise RuntimeError(f"listRecords for {did} failed: {e}") from None items += page.get("records") or [] cursor = page.get("cursor") or "" if not cursor: return items
def sweep_requests() -> int: """Catch request records the firehose missed. The firehose only emits a create once; a record written while the worker was down (or never heard, as in dev) stays in the repo and must be found by listing it. We poll the repos of everyone who has logged in (the proxy's sessions) plus every DID that already created a topic, and start a topic for any unseen rkey. Returns how many topics were created.""" dids: set[str] = set() sessions_file = ROOT / "private" / "proxy-sessions.json" try: sessions = json.loads(sessions_file.read_text()) dids.update(did for did in sessions.values() if did) except (OSError, ValueError): pass for t in store.all_topics(): if t.get("did"): dids.add(t["did"]) created = 0 for did in sorted(dids): try: pds = _pds_for(did) records = _request_records(did, pds) except Exception as e: # noqa: BLE001 — one unreachable repo must not log(f"sweep_requests {did} failed: {e}") # stop the rest continue for rec in records: rkey = (rec.get("uri") or "").rsplit("/", 1)[-1] if not rkey or store.get_topic(rkey): continue value = rec.get("value") or {} text = (value.get("topic") or value.get("text") or "").strip() if not text: continue log(f"request {rkey} by {did}: \"{text[:60]}\"") try: topics.start_topic(rkey, did, text) created += 1 except Exception as e: # noqa: BLE001 log(f" topic {rkey} failed: {e}") return created
VOTE_TYPE = "click.aligned.feed.vote"
def _vote_records(did: str, pds: str) -> list[dict]: """Every click.aligned.feed.vote record in a repo, paged.""" items: list[dict] = [] cursor = "" while True: params = {"repo": did, "collection": VOTE_TYPE, "limit": 100} if cursor: params["cursor"] = cursor url = f"{pds}/xrpc/com.atproto.repo.listRecords?{urllib.parse.urlencode(params)}" try: with urllib.request.urlopen(url, timeout=15) as r: page = json.loads(r.read()) except (urllib.error.HTTPError, OSError, json.JSONDecodeError) as e: raise RuntimeError(f"listRecords votes for {did} failed: {e}") from None items += page.get("records") or [] cursor = page.get("cursor") or "" if not cursor: return items
def sweep_votes() -> int: """Reconcile the cached +1 counts with their source of truth — the vote records in each repo. The firehose emits a create once, so votes written while the worker was down need the same listRecords catch-up as request records; the votes table is only a cache and this rebuilds it.""" dids: set[str] = set() sessions_file = ROOT / "private" / "proxy-sessions.json" try: sessions = json.loads(sessions_file.read_text()) dids.update(did for did in sessions.values() if did) except (OSError, ValueError): pass for t in store.all_topics(): if t.get("did"): dids.add(t["did"]) for r in store._rows(store._VOTES, None): if r.get("did"): dids.add(r["did"]) synced = 0 for did in sorted(dids): try: pds = _pds_for(did) records = _vote_records(did, pds) except Exception as e: # noqa: BLE001 — one unreachable repo must not log(f"sweep_votes {did} failed: {e}") # stop the rest continue for rec in records: value = rec.get("value") or {} post = value.get("post") or "" if not post: continue store.vote(post, did) synced += 1 return synced
# --- the loop -----------------------------------------------------------------
def _process_frame_sync(row: dict, hits: list[str], stats: dict) -> None: """The blocking half of pooling a firehose post: embed (network), store writes, and the LLM fit judge. Runs in a worker thread via `_handle_frame` so the event loop stays responsive to Jetstream (a slow consumer gets disconnected) while a post is judged.""" row["source_keyword"] = hits[0] for h in hits: store.touch_keyword(h) try: row["embedding"] = embed([row["text"]])[0] except Exception: # noqa: BLE001 — an embed failure must not stop the return # stream; the post is simply not pooled this time. stats["matched"] += 1 store.add_posts([row], update=store._FIREHOSE_MERGE) try: n = topics.pass_post(row["uri"]) if n: log(f"pooled {row['uri']} via {row['source_keyword']!r} " f"({hits}), judged against {n} topic(s)") stats["pooled"] += 1 except Exception as e: # noqa: BLE001 log(f"pass_post failed for {row['uri']}: {e}")
async def _handle_frame(frame: dict, words: list[str], phrases: list[str], stats: dict) -> None: stats["frames"] += 1 collection = (frame.get("commit") or {}).get("collection", "")
# The firehose only listens for posts. Request records are not its job: # the app creates the topic the moment a request is written, and the # periodic sweep_requests catches any written from another client.
if collection != POST_TYPE: return row = _post_row(frame) if not row: return hits = matching_keywords(row["text"], words, phrases) if not hits: return # The heavy work — embed, store writes, the LLM judge — runs off the event # loop so one post being judged cannot stall the whole stream. await asyncio.to_thread(_process_frame_sync, row, hits, stats)
async def run_once(words, phrases, stats, duration: int = 60) -> int: """One connection, bounded by wall-clock `duration` (not by silence): keep receiving frames until the deadline, then return so `main_loop` can run housekeeping and the keyword-filter refresh. Returns how many posts were handled (-1 on a dead connection).""" import websockets handled = 0 deadline = time.time() + duration async with websockets.connect(JETSTREAM_URL, ping_interval=None) as ws: try: while True: remaining = deadline - time.time() if remaining <= 0: return handled message = await asyncio.wait_for(ws.recv(), timeout=remaining) frame = json.loads(message) await _handle_frame(frame, words, phrases, stats) handled += 1 except asyncio.TimeoutError: return handled except websockets.ConnectionClosed: log("jetstream connection closed — reconnecting") return -1 except json.JSONDecodeError: return handled
def housekeeping() -> None: """The periodic jobs: catch request records the firehose missed, process new topics, re-seed every topic's region, prune dead keywords, then backfill. Each job fails on its own.""" from ingest import backfill try: n = sweep_requests() if n: log(f"swept {n} request record(s) into topics") except Exception as e: # noqa: BLE001 log(f"sweep_requests failed: {e}") try: n = sweep_votes() if n: log(f"swept {n} vote record(s) into the cache") except Exception as e: # noqa: BLE001 log(f"sweep_votes failed: {e}") for topic in store.unprocessed_topics(): try: topics.process_topic(topic["rkey"]) log(f"processed topic {topic['rkey']}: \"{topic['text'][:50]}\"") except Exception as e: # noqa: BLE001 log(f"process_topic {topic['rkey']} failed: {e}") for topic in store.all_topics(): try: if topics.ensure_exemplars(topic["rkey"]): log(f"wrote exemplars for {topic['rkey']}: \"{topic['text'][:40]}\"") except Exception as e: # noqa: BLE001 log(f"ensure_exemplars {topic['rkey']} failed: {e}") for topic in store.all_topics(): try: n = topics.pass_topic(topic["rkey"]) if n: log(f"pass_topic {topic['rkey']}: judged {n} new candidate(s)") except Exception as e: # noqa: BLE001 log(f"pass_topic {topic['rkey']} failed: {e}") try: pruned = backfill.prune_keywords() if pruned: log(f"pruned {pruned} dead keyword(s)") except Exception as e: # noqa: BLE001 log(f"prune failed: {e}") try: backfill.backfill_once() except Exception as e: # noqa: BLE001 log(f"backfill failed: {e}")
async def main_loop(once: bool = False) -> None: log(f"worker up; jetstream {JETSTREAM_URL}") last_kw_refresh = 0.0 last_housekeep = 0.0 last_report = 0.0 stats = {"frames": 0, "matched": 0, "pooled": 0} while True: now = time.time() if now - last_kw_refresh > KEYWORD_REFRESH: words, phrases = _phrase_terms(store.indexed_keywords()) last_kw_refresh = now log(f"firehose filter: {len(words)} word(s), {len(phrases)} phrase(s)") try: await run_once(words, phrases, stats, duration=ONCE_DURATION if once else RUN_DURATION) except Exception as e: # noqa: BLE001 log(f"jetstream round failed: {e}; reconnecting") if once: return if now - last_report > 60: last_report = now log(f"minute: {stats['frames']} frame(s), {stats['matched']} " f"keyword match(es), {stats['pooled']} post(s) pooled") stats = {"frames": 0, "matched": 0, "pooled": 0} if time.time() - last_housekeep > HOUSEKEEP_INTERVAL: last_housekeep = time.time() await asyncio.to_thread(housekeeping)
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--once", action="store_true", help="run one jetstream round and exit") args = parser.parse_args() try: asyncio.run(main_loop(once=args.once)) except KeyboardInterrupt: pass
if __name__ == "__main__": main()