diff --git a/.env.example b/.env.example index 5494d3f..82b91f7 100644 --- a/.env.example +++ b/.env.example @@ -34,11 +34,12 @@ PHASE2_WAITING_PERIOD=2 hours PHASE3_WAITING_PERIOD=3 months # Threads that run Phase 1 (duplicate search, auxiliary replies) on matching r/all comments PHASE1_WORKERS=4 -# How new comments are read: 'ids' (every new comment, by ID range) or 'listing' (the r/all listing, which -# misses most comments; kept as a fallback) -STREAM_SOURCE=ids -# With STREAM_SOURCE=ids: threads fetching blocks of 100 comment IDs, taking turns between the 4 accounts -STREAM_READERS=4 +# How new comments are read: 'listing' (the r/all listing, polled on STREAM_READERS threads at once) or +# 'stream' (PRAW's r/all stream, one request at a time, which misses most comments; kept as a fallback) +STREAM_SOURCE=listing +# With STREAM_SOURCE=listing: threads polling the r/all comment listing, taking turns between the 4 accounts +# (at most 20 requests a minute each; Reddit allows 100 a minute per account, so keep it at or below 12) +STREAM_READERS=12 # ------------------------------------------------------------------------------ # 1. Primary Bot: AutoCrosspostBot (u/AutoCrosspostBot) diff --git a/AGENTS.md b/AGENTS.md index 8c69170..e89b4fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,8 +12,8 @@ Welcome to the **RedditAutoCrosspostBot** repository. This document is a compreh This repository hosts a suite of 4 automated Reddit bots powered by [PRAW (Python Reddit API Wrapper)](https://praw.readthedocs.io/), backed by a PostgreSQL database and containerized with Docker / Docker Compose for deployment on free cloud VPS instances (e.g. Google Cloud Always Free or Oracle Cloud Always Free) or local hardware. -All 4 bots run in **one Python process, on several threads**. New comments are read by ID on a few -reader threads (`comment_reader.py`, section 7), with the main thread tracking the newest comment ID. +All 4 bots run in **one Python process, on several threads**. New comments are read by polling the +r/all comment listing on several reader threads at once (`comment_reader.py`, section 7). Phase 1 runs on a pool of worker threads, and every scheduled job (Phase 2, Phase 3, inbox, cleanup, ...) on a thread of its own, so a slow job never pauses reading. @@ -116,17 +116,15 @@ A banned target (a 404 whose body says `"reason": "banned"`, `SUBREDDIT_IS_BANNE ### Phase Details - **Phase 1 ([`src/racb/phases/phase1.py`](./src/racb/phases/phase1.py)):** - - Continuous reading of every new comment by ID (`comment_reader.CommentReader`, the default, - `STREAM_SOURCE=ids`): blocks of 100 consecutive comment IDs fetched with `reddit.info()` on - `STREAM_READERS` threads, keeping only what r/all could show (`is_shown_on_r_all`: not private or on a user - profile). `/api/info` comments have no `over_18` or `quarantine` field, so Phase 1 drops NSFW and - quarantined ones by their submission (`phase1.is_hidden_from_r_all`, no extra request). The head poll - asks the listing for 100 comments and takes the newest, because smaller limits often return none. An empty - listing anyway only skips that poll and is counted in the heartbeat (`head: N polls (M empty)`); the next - poll catches up. Only `EMPTY_HEAD_POLLS_BEFORE_WARNING` (6) empty polls in a row log a WARNING. Subreddits that opted out of r/all cannot be told apart, so their comments - are read too. `STREAM_SOURCE=listing` instead reads + - Continuous reading of new comments (`comment_reader.CommentReader`, the default, `STREAM_SOURCE=listing`): + `STREAM_READERS` threads, taking turns between the 4 accounts, each ask the r/all comment listing for its + newest 100 comments, at most every `MIN_SECONDS_BETWEEN_POLLS` (3 s), staggered so their requests + interleave. A comment any thread saw before (`SeenComments`, the last 20,000 fullnames) is skipped. The + listing only holds r/all comments, but Phase 1 still drops NSFW and quarantined ones by their submission + (`phase1.is_hidden_from_r_all`, no extra request). `STREAM_SOURCE=stream` instead reads `reddit.subreddit('all').stream.comments(skip_existing=True, pause_after=-1)` one request at a time, which - sees only a fraction of r/all (section 9). + sees only a fraction of r/all (section 9). The 3.0 to 3.1 reader by comment ID range (`STREAM_SOURCE=ids`) + was removed: since 2026-10-21 Reddit's comment IDs are no longer sequential (section 7). - Filters: Discards moderator comments, submissions with meta-phrases (`sub`, `subreddit`), and blacklisted subreddits ([`src/racb/constants.py`](./src/racb/constants.py), compared case-insensitively by `is_crosspost_blocked`). Non-top-level comments (`comment.parent_id != comment.link_id`) can only get a `sub_doesnt_exist_bot` reply and are never stored (see the note in section 1). - Qualified suggestions are stored via stored procedure `insert_scraped_comment(permalink, target_subreddit)`. - Phases 2 and 3 re-parse the target from the live comment body and reject the row @@ -222,8 +220,8 @@ A banned target (a 404 whose body says `"reason": "banned"`, `SUBREDDIT_IS_BANNE | File | Purpose | | :--- | :--- | -| [`src/racb/main.py`](./src/racb/main.py) | Application entry point, logging setup, `StreamMetrics` (the heartbeat), `run_stream` (starts the comment reader, or the listing stream loop with `STREAM_SOURCE=listing`), exception recovery, the job list (`build_jobs`), and graceful shutdown on SIGTERM/SIGINT. | -| [`src/racb/comment_reader.py`](./src/racb/comment_reader.py) | `CommentReader`: reads every new comment by blocks of 100 consecutive IDs on `STREAM_READERS` threads spread over the 4 accounts, and saves its position (`stream_cursors`) so restarts resume. Its module docstring explains the method. | +| [`src/racb/main.py`](./src/racb/main.py) | Application entry point, logging setup, `StreamMetrics` (the heartbeat), `run_stream` (starts the comment reader, or the PRAW stream loop with `STREAM_SOURCE=stream`), exception recovery, the job list (`build_jobs`), and graceful shutdown on SIGTERM/SIGINT. | +| [`src/racb/comment_reader.py`](./src/racb/comment_reader.py) | `CommentReader`: polls the r/all comment listing on `STREAM_READERS` threads spread over the 4 accounts and hands on each comment once. Its module docstring explains the method and why the ID-range reader was dropped. | | [`src/racb/workers.py`](./src/racb/workers.py) | Background threads: `PeriodicJob` (one thread per scheduled job), `Phase1Workers` (the Phase 1 thread pool fed by the stream), and `run_job_safely`. | | [`src/racb/__main__.py`](./src/racb/__main__.py) | Module executable entrypoint for `python -m racb`. | | [`src/racb/__init__.py`](./src/racb/__init__.py) | Package marker; re-exports `__version__`. | @@ -248,7 +246,6 @@ A banned target (a 404 whose body says `"reason": "banned"`, `SUBREDDIT_IS_BANNE | [`scripts/release_level.py`](./scripts/release_level.py) | Used by the CI `release` job: prints `major`, `minor`, `patch` or `none` from the Conventional Commits since the last `v*` tag and whether `changelog.d/` holds fragments. | | [`scripts/cleanup_test_history.py`](./scripts/cleanup_test_history.py) | Deletes integration-test posts and comments from all 4 bot accounts. Supports `--dry-run`, `--limit N` (`0` means all) and `--strict` (exit code 1 if a bot could not be checked or a test item could not be deleted). Slow; for manual use. | | [`scripts/delete_test_artifacts.py`](./scripts/delete_test_artifacts.py) | Deletes only the posts and comments the integration tests recorded in their manifest (`$RACB_TEST_ARTIFACTS_FILE`, default `racb-test-artifacts.jsonl` in the temp directory), as the bot that wrote each one, then removes the manifest. Supports `--dry-run`, `--manifest PATH` and `--strict`. The last step of CI's `integration-tests` job. | -| [`scripts/verify_comment_ids.py`](./scripts/verify_comment_ids.py) | Read-only live check of what `comment_reader.py` assumes: comment IDs follow creation time, 100-ID blocks come back mostly full with the fields the r/all filter reads, how many IDs Reddit hands out per second, and what each request costs (with a rough egress estimate). Needs only `racb.core.reddit`; its docstring shows how to pipe it into the bot container on the VM. | | [`scripts/redeploy.sh`](./scripts/redeploy.sh) | Runs **on the VM**: resets the checkout to a commit of `origin/master` (argument, `SSH_ORIGINAL_COMMAND`, or the latest), runs `docker compose up --detach --build`, and fails if the bot is not running 30 s later. The CI `deploy` job's SSH key is pinned to it. Refuses to run on a dirty or diverged checkout. | | [`scripts/authorize_deploy_key.sh`](./scripts/authorize_deploy_key.sh) | Runs **on the VM** once: adds the CI deploy key to `~/.ssh/authorized_keys` as a forced command for `redeploy.sh` and prints the host key. | | [`scripts/setup_auto_deploy.sh`](./scripts/setup_auto_deploy.sh) | One-time setup of automatic deployment, run in Cloud Shell: service account, Workload Identity Federation, IAP firewall rule, deploy key, GitHub variables. See [`docs/auto-deploy.md`](./docs/auto-deploy.md). | @@ -309,8 +306,8 @@ Store these in `.env` for local development or production: | `PHASE2_WAITING_PERIOD` | Time string | `2 hours` | Time duration before Phase 2 checks a comment (parsed via `pytimeparse`, e.g. `2 hours` or `1 day`). | | `PHASE3_WAITING_PERIOD` | Time string | `90 days` | Time duration before Phase 3 executes the crosspost (e.g. `3 months` or `90 days`). The public crosspost reply shows it as a localized whole number of days. | | `PHASE1_WORKERS` | Integer | `4` | Number of Phase 1 worker threads (at least 1). Each makes its own Reddit requests, all sharing the accounts' rate limits (section 7). | -| `STREAM_SOURCE` | `ids` / `listing` | `ids` | How new comments are read: `ids` reads every comment by ID range (`comment_reader.py`), `listing` reads PRAW's r/all comment stream one request at a time (the pre-3.1 way, kept as a fallback). An unknown value logs a WARNING and uses `ids`. | -| `STREAM_READERS` | Integer | `4` | With `STREAM_SOURCE=ids`: threads fetching ID blocks (at least 1), taking turns between the 4 accounts. Raising it only helps if the heartbeat's `behind:` keeps growing; requests per minute are set by how fast Reddit gets new comments, not by this. | +| `STREAM_SOURCE` | `listing` / `stream` | `listing` | How new comments are read: `listing` polls the r/all comment listing on `STREAM_READERS` threads (`comment_reader.py`), `stream` reads PRAW's r/all comment stream one request at a time (the pre-3.0 way, kept as a fallback). An unknown value, including the removed `ids`, logs a WARNING and uses `listing`. | +| `STREAM_READERS` | Integer | `12` | With `STREAM_SOURCE=listing`: threads polling the r/all listing (at least 1), taking turns between the 4 accounts. Each makes at most 20 requests a minute (one per `MIN_SECONDS_BETWEEN_POLLS`), and Reddit allows 100 a minute per account, so keep it at or below 12. Raise it while the heartbeat's `gaps` stay high, lower it on `TooManyRequests` warnings. | | `LOG_DIR` | Path | `logs` | Directory for `app.log` (relative to the CWD; `/app/logs` in Docker, mounted on volume `racb_logs`). | | `PASSWORD` | String | | Account password for `AutoCrosspostBot`. | | `APP_CLIENT_SECRET` | String | | App client secret for `AutoCrosspostBot`. | @@ -450,8 +447,8 @@ uv run pytest -m integration ### Logging - Format: `YYYY-MM-DD HH:MM:SS [LEVEL ] [thread] module.name: message`, sent to stderr and to - `$LOG_DIR/app.log` (rotating, 5 x 5 MB). `thread` is `MainThread` (head polls, or the listing stream), - `reader-` (comment ID blocks), `phase1-`, or the job's name (`phase2`, `phase3`, `inbox`, `cleanup`, + `$LOG_DIR/app.log` (rotating, 5 x 5 MB). `thread` is `MainThread` (the PRAW stream with + `STREAM_SOURCE=stream`), `reader-` (r/all listing polls), `phase1-`, or the job's name (`phase2`, `phase3`, `inbox`, `cleanup`, `heartbeat`, `known-subreddits`). - The `prawcore` and `urllib3.connectionpool` loggers are **disabled entirely**, which also hides prawcore's rate-limit messages. - `[DRY RUN]` lines show writes that `DRY_RUN` suppressed. `Skipping comment ... after Reddit error` lines @@ -463,16 +460,16 @@ uv run pytest -m integration It says `N match(es) dropped, Phase 1 queue full` when the Phase 1 workers fell behind. Besides that, only two lines are logged per backlog: when the queue fills and when it has room again. Its second half says how comments were read, for example - `reads: 412 requests, 87.3 comments/request, 0.95 s/request | head: 50 polls, 1.70 s/poll | behind: 9 s, 340 IDs`: - - `reads`: ID blocks (or listing batches) fetched, and how many comments each returned (all of them, before - the r/all filter). With `STREAM_SOURCE=listing`, about 100 comments/request means the listing returned - full pages, so the bot was falling behind r/all. - - `head`: polls for the newest comment ID, and how many of them got an empty r/all listing or were - `rejected` as implausible (see section 7). Empty polls cost nothing but a few seconds of delay; only a - long streak, which also logs a WARNING, stops new reads. - - If head polls succeeded but `reads: 0 requests`, a second line, a WARNING, says the reader is stalled. - - `behind`: age of the newest comment read, and (`ids` only) how many IDs wait to be read. Growing values - mean the readers do not keep up; `N ID block(s) failed` and `N IDs skipped` count comments given up on. + `reads: 2,400 requests, 92.0 comments/request, 4.10 s/request | 31.5 new/request, gaps: 96 (4%) | behind: 6 s`: + - `reads`: listing requests (or PRAW stream batches), and how many comments each returned. With + `STREAM_SOURCE=stream`, about 100 comments/request means the listing returned full pages, so the bot was + falling behind r/all. + - `new/request`: comments no earlier request had returned. `gaps`: requests whose comments were all new, so + comments posted between them and the ones seen before were missed. A few percent is fine; a high share + means the readers do not keep up with r/all (raise `STREAM_READERS`, within Reddit's rate limit). + - If no comment was read in the whole interval, a second line, a WARNING, says the reader is stalled and + whether any request was made. + - `behind`: age of the newest comment read. ### Release & Semantic Versioning Workflow We follow [Semantic Versioning (SemVer)](https://semver.org/) and [Keep a Changelog](https://keepachangelog.com/). **Releases are fully automatic; nobody bumps the version by hand.** @@ -563,7 +560,7 @@ Defined in [`src/racb/sql/instantiate_db.sql`](./src/racb/sql/instantiate_db.sql | `known_subreddits` | `name_lower VARCHAR(32) PK`, `display_name VARCHAR(32) NOT NULL`, `last_seen TIMESTAMP NOT NULL`. GIN trigram index `idx_known_subreddits_name_trgm` on `name_lower`. Every subreddit (except `u_` profiles) the stream has seen a comment in; rows are never deleted, so a later-banned subreddit stays (its suggestion line then says so). | | `record_known_subreddits(text[])` | Upserts a batch of names, refreshing `display_name` and `last_seen`. | | `find_similar_subreddits(varchar, int)` | `(display_name, similarity)` for names matching `name_lower % lower(query)` (trigram similarity ≥ `pg_trgm.similarity_threshold`, default 0.3), most similar first. | -| `stream_cursors` | `name VARCHAR(32) PK`, `next_comment_id BIGINT NOT NULL`, `done_blocks BIGINT[] NOT NULL`, `updated_at TIMESTAMP NOT NULL`. Where `comment_reader` stopped (row `comments`): every comment ID (base 36 as a number) below `next_comment_id` was read, and so were the 100-ID blocks starting at each of `done_blocks`. | +| `stream_cursors` | `name VARCHAR(32) PK`, `next_comment_id BIGINT NOT NULL`, `done_blocks BIGINT[] NOT NULL`, `updated_at TIMESTAMP NOT NULL`. Unused since 3.2: where the ID-range comment reader of 3.0 to 3.1 stopped (row `comments`). | | `save_stream_cursor(varchar, bigint, bigint[])` / `get_stream_cursor(varchar)` | Upsert / read one cursor; `get` returns no row if none is saved. | Behavior to be aware of: @@ -593,9 +590,8 @@ Behavior to be aware of: ```mermaid flowchart LR - M["MainThread\npolls the newest comment ID"] -->|"blocks of\n100 IDs"| BQ[["block queue"]] - M -.->|"every 30 s\nand at shutdown"| C[("stream_cursors")] - BQ --> S["reader-1 ... reader-N\n(STREAM_READERS,\n4 accounts in turn)"] + R[("r/all comment listing")] -->|"newest 100,\nevery 3 s per thread"| S["reader-1 ... reader-N\n(STREAM_READERS,\n4 accounts in turn)"] + S -->|"skip comments\nseen before"| SC[["SeenComments"]] S -->|"comment ID of a\nregex match"| Q[["Phase 1 queue\n(1000 IDs)"]] Q --> W["phase1-1 ... phase1-N\n(PHASE1_WORKERS)"] S -->|"subreddit name\n(no I/O)"| K["known_subreddits buffer"] @@ -621,28 +617,23 @@ share a lock and never run at the same time, because both take rows from `scrape re-runs Phase 2's filters. Every run is wrapped in `workers.run_job_safely()`, which logs a failing job's exception instead of ending its thread, and calls `db.reset_connection()` on DB connection errors. -**Reading comments (`STREAM_SOURCE=ids`, `comment_reader.CommentReader`).** Reddit numbers comments in -base 36, in order across the whole site. The main thread asks the r/all listing for its newest comment -(one request, then a 10 s pause, which only delays reading, never skips anything) and queues every complete block of 100 IDs up to it. Each `reader-` -thread takes a block, fetches it with `reddit.info(fullnames=...)` (one request, as its account) and passes -each comment r/all would show to `main.dispatch_comment`, several threads at once. So requests per minute -follow Reddit's comment rate (about one per 100 new comments), whatever `STREAM_READERS` is. A block that -fails with a network error is retried after the usual back-off, up to 3 tries, then given up on and counted. - -The reader saves its position every 30 s and at shutdown: the lowest ID not read yet (the watermark), and -the blocks already done above it, so a restart neither skips nor re-reads them. A restart more than -`MAX_BACKLOG_IDS` (200,000, about half an hour at a guessed 100 comments a second) behind starts at the newest comment instead, and so does -a running reader that falls that far behind (the skipped IDs are logged and counted). - -The head is checked before it is followed, because on 2026-10-17 a single bogus ID (about 6 × 10^18, real -IDs were about 8 × 10^10) made the reader skip ahead to it and then read nothing for hours: -- `fetch_head` ignores IDs in the listing more than `MAX_BACKLOG_IDS` from the median (`newest_consistent_id`). -- A head more than `MAX_BACKLOG_IDS` plus `MAX_COMMENT_IDS_PER_SECOND` (2,000) per second since the last - accepted head (or the saved cursor, at startup) is rejected, logged once per streak and counted. -- If `HEADS_BELOW_POSITION_BEFORE_RESET` (6) heads in a row are more than `MAX_BACKLOG_IDS` below the reader's - position, it restarts at the newest comment. A saved cursor ahead of the head is ignored the same way. - -**Reading comments (`STREAM_SOURCE=listing`).** `main_loop()` reads one batch from PRAW's comment stream. The +**Reading comments (`STREAM_SOURCE=listing`, `comment_reader.CommentReader`).** Each `reader-` thread asks +the r/all comment listing for its newest 100 comments (one request, as its account), hands each comment no +thread saw before to `main.dispatch_comment`, and starts its next request `MIN_SECONDS_BETWEEN_POLLS` (3 s) +after the previous one started (requests take about 6 s, so in practice it polls back to back). The threads +start staggered, so with 12 readers a request starts about every 0.5 s. A network error backs off as usual +(`workers.back_off_after_network_error`); any other error is logged and the thread polls again after 10 s. +Nothing is saved across restarts: the listing reaches back only about 100 comments anyway. + +Why not by ID range, as 3.0 to 3.1 did: that reader asked `/api/info` for blocks of 100 consecutive comment +IDs, which needs Reddit to number comments in order. Reddit announced on r/redditdev ("Upcoming changes to +the comment ID endpoint", rolled out from the week of 2026-09-28) that new comment IDs are 64-bit, up to 13 +base-36 characters (e.g. `19rnei2yv8zk1`, about 6 × 10^18) and "will not be monotonically increasing anymore"; +old IDs keep working. From about 2026-10-21 every new comment had one. Two comments seconds apart are about +2 × 10^9 IDs apart (the high bits look like a millisecond timestamp, which Reddit has not documented), so the +ID reader read nothing for days. Never sort or compare comment IDs to order comments; use `created_utc`. + +**Reading comments (`STREAM_SOURCE=stream`).** `main_loop()` reads one batch from PRAW's comment stream. The stream uses `pause_after=-1`. In PRAW this makes the generator yield `None` after **every** request and **never sleep**, so the loop polls continuously, throttled only by prawcore's rate limiter. After a stream error, the new stream continues after the newest comment seen (`continue_after_id`); after a restart it @@ -663,7 +654,7 @@ Rules for thread safety: requests at once, which ends in a `TooManyRequests` that the thread backs off from (60 s). - **Each thread has its own database connection** (`db.get_connection()`, thread-local). - Module-level state written by more than one thread needs a lock (`StreamMetrics`, `known_subreddits`, - `Phase1Workers.submit`, `CommentReader`'s block bookkeeping). + `Phase1Workers.submit`, `SeenComments`). **Shutdown:** SIGTERM (`docker stop`) and SIGINT set the stop signal in `racb.core.shutdown`. The main thread, the reader threads, the Phase 1 workers and the job threads check it, every back-off waits with `shutdown.stop_requested_within()` @@ -683,24 +674,23 @@ flowchart TD S -->|"DB connection error"| R["reset DB connection,\nskip comment"] S -->|"other Reddit / PRAW error\n(e.g. 403 bot banned)"| K["log INFO, skip comment"] S -->|"anything else"| L["log with traceback, skip comment"] - F["head poll or listing fetch\non the main thread"] -->|raises| H{"handle_exception()"} + F["PRAW stream fetch\non the main thread\n(STREAM_SOURCE=stream)"] -->|raises| H{"handle_exception()"} H -->|"TooManyRequests"| W60["sleep 60 s"] H -->|"network error or Forbidden"| W30["sleep 30 s"] H -->|"DB connection error"| WDB["reset DB, sleep 30 s"] H -->|"graceful RedditAPIException"| N["no sleep"] - W60 & W30 & WDB & N --> RS["poll again (ids), or re-create\nthe stream after the newest\ncomment seen (listing)"] + W60 & W30 & WDB & N --> RS["re-create the stream after\nthe newest comment seen"] H -->|"anything else"| X["crash; Docker restarts"] ``` - Matching uses `isinstance`, so subclasses are covered. - With `DEBUG=True`, every layer re-raises. -- A failing head poll only stops new blocks from being queued; the readers finish the ones queued and the - next poll catches up, so nothing is lost. Reader threads back off from their own errors - (`workers.back_off_after_network_error`) and retry the block. +- Reader threads (`STREAM_SOURCE=listing`) handle their own errors: they back off from network errors + (`workers.back_off_after_network_error`), log anything else, and poll again; the other readers keep going. Rule for new code (reinforcing rule 3 in section 10): catch per-item errors **inside** the per-comment or per-row handler. Only network-level failures should reach the worker's back-off or `handle_exception()`. -A back-off on the main thread only pauses finding new comments; the readers, workers and jobs keep running. +A back-off on one reader thread only pauses that reader; the other readers, workers and jobs keep running. --- @@ -725,8 +715,9 @@ A back-off on the main thread only pauses finding new comments; the readers, wor instance hours, 30 GB-months of standard disk, and 1 GB a month of outbound data transfer. CPU use is not among them, so it costs nothing; an e2-micro that needs more than its share is only slowed down. Egress is the limit to watch: downloads from Reddit are inbound, but every request and its TCP acknowledgements go out. - Check the VM's network egress in Cloud Monitoring after a change that adds requests - (`scripts/verify_comment_ids.py` prints a rough estimate for the comment reader). + Check the VM's network egress in Cloud Monitoring after a change that adds requests. The comment reader + makes most of them: with 12 `STREAM_READERS` about 120 requests a minute, against about 75 for the ID reader + of 3.0 to 3.1 (one per 100 new comments at about 126 a second). - Python versions: `requires-python = ">=3.11"`. The Docker image, CI and `.python-version` use 3.11, and the unit tests also pass on 3.13. 3.10 is not supported. - Mermaid diagrams: GitHub's renderer rejects unquoted labels that contain parentheses, e.g. @@ -741,9 +732,8 @@ A back-off on the main thread only pauses finding new comments; the readers, wor | Duplicate crossposts | Before every crosspost, Phase 3 re-runs `get_posts_with_same_content()`. That is a Reddit search for the submission URL in the target (subject to search-index lag of minutes) plus Reddit's "other discussions" of the source post, a search for the same title, and a scan of every image (or video) post the target got since the source comment was written (a live listing, so it catches a crosspost made seconds earlier, but only for **image (including gallery) and video** posts, galleries by their first 10 pictures, crossposts through their original post, videos only by preview frame, and in busy subreddits only as far back as Reddit's ~1000-post listing reaches). The remaining gap is link and text posts whose title was changed and that are not linked as "other discussions", when two rows for the same submission and target are handled in one Phase 3 run, or after a crash between `crosspost()` and the row delete. The owner considers this acceptable, and Reddit may also reject duplicates server-side (unverified). An `ALREADY_SUB`-style rejection is not in `familiar_error_types`, so it would be logged as unexpected. If the reply fails after a successful crosspost, the crosspost is reported as failed. | | Negative-score cleanup | Deletes `AutoCrosspostBot` submissions with `score < 0`. The owner reports that submission scores can go negative; this was not independently confirmed. | | Phase 1 backlog | Phase 1 (duplicate search, up to 200 preview downloads per match, subreddit suggestions) runs on `PHASE1_WORKERS` threads. If matches arrive faster than they can handle for long enough to fill the 1000-ID queue, new matches are dropped; the heartbeat counts them. Not observed; matches are a small fraction of `r/all`. | -| Comment coverage | `STREAM_SOURCE=listing` reads at most 100 comments per request, one request at a time. On 2026-10-15/16 that was about 850 comments a minute by day and up to 2,500 at night, when Reddit answered faster, so it missed most of r/all. The `ids` reader was written for that; it relies on Reddit numbering comments in order site-wide, which `test_live_comment_reader_reads_recent_comments_by_id` checks before every deploy, and its real coverage is still to be confirmed from the heartbeat. | -| Re-reads after a crash | The comment cursor is saved every 30 s and at shutdown. After a crash or `kill -9`, up to 30 s of comments are read again, so an auxiliary bot could reply twice to a comment from those seconds. | -| Opted-out subreddits | `/api/info` does not say whether a subreddit opted out of r/all, so the `ids` reader also reads comments in subreddits that did (private and profile comments are dropped by the reader, NSFW and quarantined ones by Phase 1). | +| Comment coverage | The r/all listing returns at most 100 comments per request, and a request takes several seconds. One request at a time (`STREAM_SOURCE=stream`) read about 850 comments a minute by day on 2026-10-15/16 and missed most of r/all. The ID reader of 3.0 to 3.1 read about 126 a second (2026-10-17 to 21), which gives an idea of r/all's volume. The listing readers poll on 12 threads instead; whether that keeps up is to be confirmed from the heartbeat's `gaps`. | +| Comments posted while the bot is down | Not read: the listing reaches back only about 100 comments. The `stream_cursors` table and `db.save_stream_cursor`/`get_stream_cursor` are left from the ID reader and are unused. | | Rotated reposts | Not detected as duplicates (see the image-matching note in section 5). | | Edited video reposts | Videos are compared by their preview frame only. A trimmed, re-cut or re-encoded copy usually has a different preview frame and is missed. | | Pre-v2.3 rows | Have `target_subreddit = NULL`, so the bait-and-switch check is skipped for them until they age out (at most one Phase 3 waiting period after upgrading). | diff --git a/changelog.d/+phase2-deleted-comment-crash.fixed.md b/changelog.d/+phase2-deleted-comment-crash.fixed.md new file mode 100644 index 0000000..a8eb0a7 --- /dev/null +++ b/changelog.d/+phase2-deleted-comment-crash.fixed.md @@ -0,0 +1 @@ +**Phase 2 Stuck on a Deleted Comment:** when Reddit returned no data for a stored comment, writing the "comment unavailable" log line fetched the comment again and raised, so the whole Phase 2 pass crashed on that comment every 20 minutes and none of the waiting comments were checked. The log line now falls back to the comment ID, and the comment is dropped as unavailable. diff --git a/changelog.d/+read-comments-from-listing.fixed.md b/changelog.d/+read-comments-from-listing.fixed.md new file mode 100644 index 0000000..55823bb --- /dev/null +++ b/changelog.d/+read-comments-from-listing.fixed.md @@ -0,0 +1 @@ +**Comment Reader Works Again After Reddit's New Comment IDs:** since about 2026-10-21 Reddit gives every new comment a 64-bit, 13-character ID that is no longer sequential, so the reader that fetched blocks of 100 consecutive IDs read nothing for days. The bot now polls the r/all comment listing on `STREAM_READERS` threads (12 by default, 3 per account), handing each comment on once, and the heartbeat counts `gaps`: requests that may have missed comments. `STREAM_SOURCE=ids` is gone (it falls back to `listing` with a warning), the old one-request-at-a-time stream is now `STREAM_SOURCE=stream`, and the heartbeat warns whenever no comment was read in its interval. diff --git a/scripts/verify_comment_ids.py b/scripts/verify_comment_ids.py deleted file mode 100644 index 3770c6d..0000000 --- a/scripts/verify_comment_ids.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Checks, against live Reddit, the assumptions the ID-range comment reader (comment_reader.py) relies on. - -Read-only: it makes about 15 requests as /u/AutoCrosspostBot and writes nothing. It only needs -`racb.core.reddit`, so it also runs on a bot that does not have the comment reader yet. On the VM: - - cd /opt/RedditAutoCrosspostBot - curl -sL https://raw.githubusercontent.com/Toldry/RedditAutoCrosspostBot/claude/project-thread-bf84xq/scripts/verify_comment_ids.py \\ - | docker compose exec -T bot python - - -It checks: -1. Comment IDs follow creation time (the r/all listing's newest 100 comments, sorted by ID, are also - sorted by time, give or take a few seconds). -2. Blocks of 100 consecutive IDs come back mostly full, as one request each, with the fields the r/all - filter reads (subreddit_type), and their submissions say whether they are NSFW or quarantined (over_18, - quarantine), which Phase 1 reads since the comments themselves do not. -3. How many comment IDs Reddit hands out per second, and so how many requests per minute the reader needs. -4. How long a block request and an r/all listing request take, and how many bytes each returns. -""" - -import statistics -import sys -import time - -from racb.core import reddit - -BLOCK_SIZE = 100 -SAMPLE_BLOCKS = 10 -# Sample blocks start this many IDs below the newest comment, so every ID in them exists already -SAMPLE_DEPTH_IDS = 5_000 -RATE_SECONDS = 60 -FILTER_FIELDS = ('subreddit_type', 'created_utc') -SUBMISSION_FIELDS = ('over_18', 'quarantine') -# The r/all listing is filtered after the limit is applied, so a limit of 1 can return nothing -HEAD_LISTING_LIMIT = 25 - -response_bytes = [] - - -def track_response_sizes(instance): - """Records the compressed size of every response (as received over the network) in response_bytes.""" - try: - session = instance._core._requestor._http - except AttributeError: - return - session.hooks['response'].append( - lambda response, *args, **kwargs: response_bytes.append(int(response.headers.get('content-length', 0))) - ) - - -def to_number(comment_id): - return int(comment_id, 36) - - -def to_id(number): - digits = '0123456789abcdefghijklmnopqrstuvwxyz' - text = '' - while number: - number, remainder = divmod(number, 36) - text = digits[remainder] + text - return text or '0' - - -def newest_listing(instance, limit): - started = time.monotonic() - response_bytes.clear() - comments = list(instance.subreddit('all').comments(limit=limit)) - return comments, time.monotonic() - started, sum(response_bytes) - - -def fetch_block(instance, start): - started = time.monotonic() - response_bytes.clear() - fullnames = [f't1_{to_id(number)}' for number in range(start, start + BLOCK_SIZE)] - comments = list(instance.info(fullnames=fullnames)) - return comments, time.monotonic() - started, sum(response_bytes) - - -def verdict(passed, text): - print(f' [{"PASS" if passed else "FAIL"}] {text}') - return passed - - -def main(): - instance = reddit.get_reddit_instance() - track_response_sizes(instance) - results = [] - - print('1. Do comment IDs follow creation time?') - listing, listing_seconds, listing_bytes = newest_listing(instance, 100) - by_id = sorted(listing, key=lambda comment: to_number(comment.id)) - times = [comment.created_utc for comment in by_id] - backwards = max((earlier - later for earlier, later in zip(times, times[1:])), default=0) - print(f' newest r/all comment: {by_id[-1].id}; the newest 100 span {times[-1] - times[0]:.0f} s') - results.append(verdict(backwards <= 10, f'sorted by ID, creation times never go back more than 10 s ' - f'(worst: {backwards:.0f} s)')) - - print(f'\n2. Are blocks of {BLOCK_SIZE} consecutive IDs mostly real comments?') - head = to_number(by_id[-1].id) - counts, seconds, sizes, missing_fields, shown, spans, link_ids = [], [], [], set(), 0, [], [] - for index in range(SAMPLE_BLOCKS): - start = head - SAMPLE_DEPTH_IDS - index * BLOCK_SIZE - comments, elapsed, size = fetch_block(instance, start) - counts.append(len(comments)) - seconds.append(elapsed) - sizes.append(size) - for comment in comments: - fields = vars(comment) - missing_fields.update(field for field in FILTER_FIELDS if field not in fields) - hidden = (fields.get('subreddit_type') in ('private', 'user') - or str(fields.get('subreddit', '')).lower().startswith('u_')) - shown += not hidden - if not hidden and fields.get('link_id'): - link_ids.append(fields['link_id']) - created = [comment.created_utc for comment in comments] - if created: - spans.append(max(created) - min(created)) - total = sum(counts) - print(f' comments per block: {counts}') - results.append(verdict(total >= SAMPLE_BLOCKS * BLOCK_SIZE * 0.5, - f'{total} of {SAMPLE_BLOCKS * BLOCK_SIZE} IDs returned ({total / SAMPLE_BLOCKS:.0f}%)')) - results.append(verdict(not missing_fields, 'every comment has ' + ', '.join(FILTER_FIELDS) - + (f' (missing: {sorted(missing_fields)})' if missing_fields else ''))) - print(f' {shown} of {total} pass the comment filter ({100 * shown / max(total, 1):.0f}%)') - # One request for up to 100 of their submissions, to see what Phase 1's NSFW check reads - submissions = list(instance.info(fullnames=list(dict.fromkeys(link_ids))[:BLOCK_SIZE])) - missing_submission_fields = {field for submission in submissions for field in SUBMISSION_FIELDS - if field not in vars(submission)} - results.append(verdict(submissions and not missing_submission_fields, - f'{len(submissions)} submissions fetched, each has ' + ', '.join(SUBMISSION_FIELDS) - + (f' (missing: {sorted(missing_submission_fields)})' if missing_submission_fields else ''))) - hidden_posts = sum(bool(vars(s).get('over_18') or vars(s).get('quarantine')) for s in submissions) - print(f' {hidden_posts} of {len(submissions)} of those posts are NSFW or quarantined') - if spans: - results.append(verdict(statistics.median(spans) < 120, - f'a block covers {statistics.median(spans):.0f} s of comments (median)')) - - print(f'\n3. How fast does Reddit hand out comment IDs? (waiting {RATE_SECONDS} s)') - time.sleep(RATE_SECONDS) - later, _, _ = newest_listing(instance, HEAD_LISTING_LIMIT) - if not later: - print(' the r/all listing returned no comments; cannot measure') - later = by_id - ids_per_second = (max(to_number(comment.id) for comment in later) - head) / max(RATE_SECONDS, 1) - blocks_per_minute = ids_per_second * 60 / BLOCK_SIZE - print(f' {ids_per_second:.0f} IDs per second, so about {blocks_per_minute:.0f} block requests per minute') - print(f' (the listing reader saw about 14 comments per second by day)') - - print('\n4. What does each request cost?') - print(f' r/all listing, 100 comments: {listing_seconds:.2f} s, {listing_bytes / 1024:.0f} KiB') - print(f' ID block: median {statistics.median(seconds):.2f} s, max {max(seconds):.2f} s, ' - f'median {statistics.median(sizes) / 1024:.0f} KiB') - if not any(sizes): - print(' (sizes unknown: Reddit sent no content-length)') - # Each block request and its acknowledgements send a few KiB out; an estimate, not a measurement - print(f' rough monthly egress at ~3 KiB out per request: ' - f'{blocks_per_minute * 3 * 60 * 24 * 30 / 1024 / 1024:.1f} GiB (the free tier allows 1 GiB)') - - print(f'\n{sum(results)} of {len(results)} checks passed') - return 0 if all(results) else 1 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/src/racb/comment_reader.py b/src/racb/comment_reader.py index 98c453e..4e1add0 100644 --- a/src/racb/comment_reader.py +++ b/src/racb/comment_reader.py @@ -1,206 +1,114 @@ -"""Reads every new Reddit comment by ID range, instead of polling the r/all comment listing. - -Why: the r/all comment listing returns at most 100 comments per request, and each request takes several -seconds. On 2026-10-15/16 the bot read about 850 comments a minute through it during the US day and up -to 2,500 a minute at night, when Reddit answers faster. So the listing, not r/all, set the count, and most -comments were never seen. - -Comment IDs are base-36 numbers that Reddit hands out in order across the whole site. So instead the bot -asks for 100 consecutive IDs at a time (`/api/info`), on several threads and accounts at once, without -gaps or overlap: - -- The main thread asks the r/all listing for its newest comment (the "head") and queues the blocks of - 100 IDs up to it. -- `STREAM_READERS` threads, spread over the 4 bot accounts, each fetch one block at a time and pass every - comment that r/all would show (`is_shown_on_r_all`) to `handle_comment`. -- The ID below which every block is done (the "watermark") and the blocks already done above it are - saved to the database every `CURSOR_SAVE_SECONDS` and at shutdown, so a restart resumes where the previous - run stopped instead of skipping what was posted meanwhile. - -`/api/info` also returns comments that r/all leaves out (private subreddits, user profiles), so those are -dropped. Its comments say nothing about NSFW or quarantine (no `over_18` or `quarantine` field, checked live -on 2026-10-16), so Phase 1 drops those by their submission (`phase1.is_hidden_from_r_all`), which it fetches -anyway, and only for regex matches. Subreddits that only opted out of r/all cannot be told apart from a -comment, so their comments are now read too. +"""Reads new Reddit comments by polling the r/all comment listing on several threads and accounts at once. + +Why not one request at a time: the listing returns at most 100 comments per request, and each request takes +several seconds. On 2026-10-15/16 a single PRAW stream read about 850 comments a minute during the US day, +while r/all got several times that, so most comments were never seen. + +Why not by ID range (3.0 to 3.1): that reader asked `/api/info` for 100 consecutive comment IDs at a time, +which worked while Reddit numbered comments in order. Since about 2026-10-21 every new comment gets a 64-bit, +13-character ID (e.g. `19rnei2yv8zk1`) that is not sequential: two comments seconds apart are about 2 * 10^9 +IDs apart, so a block of 100 IDs holds no comment at all. Reddit announced it on r/redditdev +("Upcoming changes to the comment ID endpoint", rescheduled to the week of 2026-09-28); the ID reader then +read nothing from 2026-10-21 until it was replaced. + +So now `STREAM_READERS` threads, spread over the 4 bot accounts, each ask the r/all listing for its newest 100 +comments, over and over, staggered so their requests interleave. A comment seen before (by any thread) is +skipped, so each new comment is handled once. Every comment the listing returns is on r/all, but its NSFW and +quarantine state is still checked by Phase 1, by the submission (`phase1.is_hidden_from_r_all`). + +A poll that returns only new comments means comments may have been missed between it and the previous poll +(a "gap"); the heartbeat counts them. Few gaps mean the readers keep up with r/all. Many mean more readers +would help (`STREAM_READERS`), as long as Reddit's rate limit allows. + +Nothing is saved across restarts: the listing only reaches back about 100 comments, so whatever was posted +while the bot was down cannot be read anyway. """ -import datetime +import collections import logging -import queue import threading import time from racb import config -from racb.core import db, reddit, shutdown -from racb.workers import POLL_SECONDS, back_off_after_network_error +from racb.core import reddit, shutdown +from racb.workers import back_off_after_network_error logger = logging.getLogger(__name__) -# /api/info returns at most 100 items per request -BLOCK_SIZE = 100 - -# Comments the head poll asks for. Reddit filters the r/all listing after applying the limit, so asking for -# one comment sometimes returns none (seen live on 2026-10-16); the newest of a few is the head. Even 25 came -# back empty on about every other poll on 2026-10-16, so ask for the most one request can return -HEAD_LISTING_LIMIT = 100 - -# Empty head polls in a row before a WARNING is logged. A few are normal and cost nothing (the next poll -# catches up), so they are only counted in the heartbeat; a long streak means no new comments are being queued -EMPTY_HEAD_POLLS_BEFORE_WARNING = 6 - -# Seconds to wait between two head polls (each poll itself takes a few seconds). It only sets how soon a new -# comment is read, not how many: every block up to the head is queued at once. Fewer polls, fewer requests. -HEAD_POLL_SECONDS = 10 - -# At most this many IDs may wait to be read (about half an hour of Reddit comments, at a guessed 100 per -# second). Further behind, the reader skips ahead to the head and logs how many IDs it skipped, so it never -# works on comments too old to be worth a reply. The same limit decides whether a restart resumes. -MAX_BACKLOG_IDS = 200_000 - -# How fast the head may plausibly move. Reddit hands out roughly 100 comment IDs a second -# (scripts/verify_comment_ids.py); this allows 20 times that. On 2026-10-17 the r/all listing started returning -# a comment whose ID was about 6 * 10^18, while real IDs were about 8 * 10^10: the reader jumped to it, never -# saw a real head above its position again, and read nothing for hours. A head further ahead of the last -# accepted one than MAX_BACKLOG_IDS plus this rate allows is now rejected instead of followed -MAX_COMMENT_IDS_PER_SECOND = 2_000 - -# Head polls in a row whose head is far below the reader's position before the reader trusts the head again. -# A position that far ahead of every head can only come from a bogus ID, and it would stall reading for good -HEADS_BELOW_POSITION_BEFORE_RESET = 6 - -# Tries per block before its comments are given up on -MAX_BLOCK_ATTEMPTS = 3 +# Comments one listing request asks for: the most Reddit returns. Reddit filters the listing after applying +# the limit, so it often returns fewer, and sometimes none (seen on 2026-10-16) +LISTING_LIMIT = 100 -CURSOR_SAVE_SECONDS = 30 -CURSOR_NAME = 'comments' +# Each reader thread starts its next request at least this long after its previous one started. Every +# thread has its own PRAW instance, so PRAW's rate limiter does not see the other threads of the same +# account. Reddit allows 100 requests a minute per account; with 3 threads per account (the default +# STREAM_READERS) this keeps reading at no more than 60, leaving room for Phase 1 to 3 and the inbox +MIN_SECONDS_BETWEEN_POLLS = 3 -# Subreddit types whose comments never appear on r/all -HIDDEN_SUBREDDIT_TYPES = frozenset({'private', 'user', 'employees_only', 'gold_only'}) +# Fullnames of the comments seen most recently, to skip them when another poll returns them again. A poll +# only returns the newest 100, so this only needs to reach back a few polls +SEEN_CAPACITY = 20_000 -BASE36_DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz' +# Seconds a reader waits after an unexpected error before it polls again +ERROR_RETRY_SECONDS = 10 -def comment_id_to_number(comment_id): - """`'k3l2x9a'` -> its number. Also accepts a fullname (`'t1_k3l2x9a'`).""" - if comment_id.startswith('t1_'): - comment_id = comment_id[3:] - return int(comment_id, 36) +def fetch_listing(bot_name): + """Returns the newest comments on r/all, newest first (one request, as `bot_name`).""" + instance = reddit.get_reddit_instance(bot_name) + return list(instance.subreddit('all').comments(limit=LISTING_LIMIT)) -def number_to_comment_id(number): - """The inverse of `comment_id_to_number`, without the `t1_` prefix.""" - if number == 0: - return '0' - digits = [] - while number: - number, remainder = divmod(number, 36) - digits.append(BASE36_DIGITS[remainder]) - return ''.join(reversed(digits)) - - -def saved_timestamp(updated_at): - """The Unix time of a cursor's `updated_at`, a naive timestamp in the database's time zone (UTC).""" - if updated_at.tzinfo is None: - updated_at = updated_at.replace(tzinfo=datetime.timezone.utc) - return updated_at.timestamp() - - -def block_fullnames(block_start): - """The 100 comment fullnames of the block that starts at ID `block_start`.""" - return [f't1_{number_to_comment_id(number)}' for number in range(block_start, block_start + BLOCK_SIZE)] - - -def is_shown_on_r_all(comment): - """Whether r/all could list this comment: not in a private subreddit or on a user profile. - - NSFW and quarantined comments pass: `/api/info` comments carry no field for either, so Phase 1 checks - their submission instead (`phase1.is_hidden_from_r_all`). - """ - # vars(), not getattr: reading a field the comment lacks would make PRAW fetch it, one request each - fields = vars(comment) - if fields.get('subreddit_type') in HIDDEN_SUBREDDIT_TYPES: - return False - subreddit = fields.get('subreddit') - subreddit_name = getattr(subreddit, 'display_name', subreddit) or '' - return not str(subreddit_name).lower().startswith('u_') - +class SeenComments: + """The fullnames of the last `capacity` comments handled, oldest forgotten first. Thread safe.""" -def fetch_head(): - """Returns the number of the newest comment on r/all (one request, as /u/AutoCrosspostBot). - - Returns None if the listing came back empty, which Reddit sometimes does even with HEAD_LISTING_LIMIT. - """ - newest = list(reddit.get_reddit_instance().subreddit('all').comments(limit=HEAD_LISTING_LIMIT)) - return newest_consistent_id([comment.id for comment in newest]) - - -def newest_consistent_id(comment_ids): - """Returns the highest of `comment_ids` (as a number) that lies near most of the others, or None. - - The listing's comments were all written in the last few seconds, so their IDs lie within a few thousand - of each other. An ID far from the median (another numbering, or a malformed ID) is not a head to follow. - """ - numbers = [] - for comment_id in comment_ids: - try: - numbers.append(comment_id_to_number(comment_id)) - except (AttributeError, TypeError, ValueError): - logger.debug(f'Ignoring comment ID {comment_id!r} in the r/all listing: not base 36') - if not numbers: - return None - median = sorted(numbers)[len(numbers) // 2] - consistent = [number for number in numbers if abs(number - median) <= MAX_BACKLOG_IDS] - if len(consistent) < len(numbers): - outliers = sorted(set(numbers) - set(consistent)) - logger.warning( - f'Ignoring {len(numbers) - len(consistent)} of {len(numbers)} comment IDs in the r/all listing far ' - f'from the others (median {number_to_comment_id(median)}, e.g. {number_to_comment_id(outliers[-1])})' - ) - return max(consistent) + def __init__(self, capacity=SEEN_CAPACITY): + self.capacity = capacity + self._fullnames = collections.OrderedDict() + self._lock = threading.Lock() + def __len__(self): + with self._lock: + return len(self._fullnames) -def fetch_block(bot_name, block_start): - """Returns the comments of one block that still exist and are visible (one request, as `bot_name`).""" - return list(reddit.get_reddit_instance(bot_name).info(fullnames=block_fullnames(block_start))) + def add_new(self, fullnames): + """Remembers `fullnames` and returns the ones not seen before, in their order.""" + with self._lock: + new = [] + for fullname in fullnames: + if fullname in self._fullnames: + continue + self._fullnames[fullname] = None + new.append(fullname) + while len(self._fullnames) > self.capacity: + self._fullnames.popitem(last=False) + return new class CommentReader: - """Reads every new comment by ID block on reader threads; see the module docstring. + """Polls the r/all comment listing on reader threads; see the module docstring. `handle_comment(comment)` runs on the reader threads, several at once, so it must be thread safe. `run()` occupies the calling thread (the main thread) until shutdown. """ - def __init__(self, handle_comment, reader_count, metrics=None, handle_exception=None, - fetch_head=fetch_head, fetch_block=fetch_block, cursor_store=db): + def __init__(self, handle_comment, reader_count, metrics=None, fetch_listing=fetch_listing, + min_seconds_between_polls=MIN_SECONDS_BETWEEN_POLLS): self.handle_comment = handle_comment self.metrics = metrics - # Decides what to do about an error from a head poll: returns True to re-raise (see main.handle_exception) - self.handle_exception = handle_exception or (lambda error: True) - self.fetch_head = fetch_head - self.fetch_block = fetch_block - self.cursor_store = cursor_store - self.blocks = queue.Queue() - self._lock = threading.Lock() - # The next ID to queue; None until the start position is known - self.next_id = None - # Starts of the blocks queued but not done yet, and of the blocks done above the watermark - self.in_flight = set() - self.done_above = set() - self.last_saved = time.monotonic() - # Head polls in a row that got an empty listing, so a long streak is logged once, not every poll - self.empty_head_polls = 0 - # The last head accepted (or the saved cursor) and when (time.time()), to reject implausible jumps - self.reference_id = None - self.reference_time = None - # Head polls in a row rejected as too far ahead, and in a row far below the reader's position - self.rejected_heads = 0 - self.heads_below_position = 0 - # Readers take turns between the accounts, so each account's rate limit carries a share + self.fetch_listing = fetch_listing + self.min_seconds_between_polls = min_seconds_between_polls + self.seen = SeenComments() + # Whether any poll returned comments yet: the first one cannot tell whether it missed some + self._started = False + self._started_lock = threading.Lock() + # Readers take turns between the accounts, so each account's rate limit carries a share. Each starts + # a little after the previous one, so their requests interleave + stagger_seconds = min_seconds_between_polls / max(1, reader_count) self.threads = [ threading.Thread( - target=self.read_blocks, - args=(reddit.BOT_NAMES[number % len(reddit.BOT_NAMES)],), + target=self.read_listing, + args=(reddit.BOT_NAMES[number % len(reddit.BOT_NAMES)], number * stagger_seconds), name=f'reader-{number + 1}', daemon=True, ) @@ -212,255 +120,61 @@ def start(self): thread.start() return self - # --- Main thread --- - def run(self): - """Polls the head and queues blocks until shutdown, then saves the cursor.""" - try: - while not shutdown.stop_requested(): - try: - self.poll_head() - except Exception as error: - if self.handle_exception(error): - raise - self.save_cursor_if_due() - if shutdown.stop_requested_within(HEAD_POLL_SECONDS): - break - finally: - self.save_cursor() + """Waits until shutdown. The reader threads do the reading.""" + while not shutdown.stop_requested_within(1): + pass - def poll_head(self): - started = time.monotonic() - head = self.fetch_head() - if self.metrics: - self.metrics.record_head_poll(time.monotonic() - started, empty=head is None) - if head is None: - # Nothing is lost: the next poll queues every block up to the head it finds - self.empty_head_polls += 1 - if self.empty_head_polls == EMPTY_HEAD_POLLS_BEFORE_WARNING: - logger.warning( - f'The r/all comment listing returned no comments {self.empty_head_polls} polls in a row; ' - 'no new comments are queued until it does' - ) - return - if self.empty_head_polls >= EMPTY_HEAD_POLLS_BEFORE_WARNING: - logger.info(f'The r/all comment listing has comments again after {self.empty_head_polls} empty poll(s)') - self.empty_head_polls = 0 - with self._lock: - if self.next_id is None: - self._choose_start(head) - if not self._accept_head(head): - return - self._reset_if_far_ahead_of(head) - self._skip_ahead_if_too_far_behind(head) - self._queue_blocks_up_to(head) - lag_ids = head + 1 - self._watermark() - if self.metrics: - self.metrics.set_lag_ids(lag_ids) - - def _max_plausible_head(self, now): - """The highest head that could be real, given the last accepted one; None if there is none yet.""" - if self.reference_id is None: - return None - elapsed = max(0.0, now - self.reference_time) - return self.reference_id + MAX_BACKLOG_IDS + int(MAX_COMMENT_IDS_PER_SECOND * elapsed) - - def _accept_head(self, head): - """False, with a WARNING once per streak, if `head` is too far ahead to be real. Call with the lock held.""" - now = time.time() - max_head = self._max_plausible_head(now) - if max_head is not None and head > max_head: - self.rejected_heads += 1 - if self.metrics: - self.metrics.record_rejected_head() - if self.rejected_heads == 1: - logger.warning( - f'Ignoring head comment ID {number_to_comment_id(head)} ({head:,}): more than ' - f'{max_head - self.reference_id:,} IDs past the last one accepted, ' - f'{number_to_comment_id(self.reference_id)}' - ) - return False - if self.rejected_heads: - logger.info(f'Accepted a head comment ID again after {self.rejected_heads} rejected one(s)') - self.rejected_heads = 0 - if self.reference_id is None or head >= self.reference_id: - self.reference_id = head - self.reference_time = now - return True - - def _reset_if_far_ahead_of(self, head): - """Moves the position back to `head` if every recent head was far below it. Call with the lock held.""" - if self.next_id - (head + 1) <= MAX_BACKLOG_IDS: - self.heads_below_position = 0 - return - self.heads_below_position += 1 - if self.heads_below_position < HEADS_BELOW_POSITION_BEFORE_RESET: - return - logger.warning( - f'Comment reader position {number_to_comment_id(self.next_id)} is {self.next_id - head - 1:,} IDs ' - f'ahead of the newest comment for {self.heads_below_position} polls; restarting at the newest comment' - ) - self.next_id = head + 1 - self.done_above.clear() - # The next head becomes the reference, in case this one was a bogus low ID - self.reference_id = None - self.reference_time = None - self.heads_below_position = 0 - - def _choose_start(self, head): - """Resumes from the saved cursor if it is recent enough, otherwise starts at the head. + # --- Reader threads --- - A saved cursor also bounds how far ahead the first head may plausibly be (see `_accept_head`), unless - it is ahead of the head itself, which only a bogus ID can have caused. - """ - saved = self._load_cursor() - if saved is not None and saved['next_comment_id'] <= head + 1 and saved.get('updated_at'): - self.reference_id = saved['next_comment_id'] - self.reference_time = saved_timestamp(saved['updated_at']) - max_head = self._max_plausible_head(time.time()) - if head > max_head: - # The first head is bogus: resume from the cursor and wait for a real head - logger.warning( - f'Head comment ID {number_to_comment_id(head)} is implausibly far past the saved cursor ' - f'{number_to_comment_id(self.reference_id)}; resuming from the cursor' - ) - self.next_id = saved['next_comment_id'] - self.done_above = {start for start in saved['done_blocks'] or [] if start >= self.next_id} + def read_listing(self, bot_name, start_delay): + try: + if shutdown.stop_requested_within(start_delay): return - if saved is not None and 0 <= head + 1 - saved['next_comment_id'] <= MAX_BACKLOG_IDS: - self.next_id = saved['next_comment_id'] - self.done_above = {start for start in saved['done_blocks'] or [] if start >= self.next_id} - logger.info( - f'Resuming the comment reader {head + 1 - self.next_id:,} IDs behind the newest comment ' - f'(cursor saved at {saved["updated_at"]})' - ) - return - if saved is not None: - logger.warning( - f'Saved comment cursor is {head + 1 - saved["next_comment_id"]:,} IDs from the newest comment ' - f'(more than {MAX_BACKLOG_IDS:,}, or ahead of it); starting at the newest comment instead' - ) - self.next_id = head + 1 - logger.info(f'Comment reader starts at the newest comment, ID {number_to_comment_id(head)}') + while not shutdown.stop_requested(): + started = time.monotonic() + if self.poll(bot_name): + return + remaining = self.min_seconds_between_polls - (time.monotonic() - started) + if remaining > 0 and shutdown.stop_requested_within(remaining): + return + except BaseException as error: + shutdown.fail(error, threading.current_thread().name) - def _load_cursor(self): + def poll(self, bot_name): + """Reads the listing once and hands on the comments not seen before. Returns True on shutdown.""" + started = time.monotonic() try: - return self.cursor_store.get_stream_cursor(CURSOR_NAME) - except Exception as error: + comments = self.fetch_listing(bot_name) + except reddit.TRANSIENT_NETWORK_ERRORS as error: if config.is_debug(): raise - logger.warning(f'Could not read the saved comment cursor ({error!r}); starting at the newest comment') - return None - - def _skip_ahead_if_too_far_behind(self, head): - behind = head + 1 - self.next_id - if behind <= MAX_BACKLOG_IDS: - return - logger.warning(f'Comment reader is {behind:,} IDs behind the newest comment; skipping them') - if self.metrics: - self.metrics.record_skipped_ids(behind) - self.next_id = head + 1 - self.done_above.clear() - - def _queue_blocks_up_to(self, head): - """Queues every complete block up to `head`, as long as fewer than MAX_BACKLOG_IDS wait to be read.""" - # Only complete blocks: the newest IDs of a partial block may not exist yet - while self.next_id + BLOCK_SIZE - 1 <= head and len(self.in_flight) * BLOCK_SIZE < MAX_BACKLOG_IDS: - start = self.next_id - self.next_id += BLOCK_SIZE - if start in self.done_above: - continue - self.in_flight.add(start) - self.blocks.put(start) - - def _watermark(self): - """Every ID below this has been read. Call with the lock held.""" - return min(self.in_flight) if self.in_flight else self.next_id - - def save_cursor_if_due(self): - if time.monotonic() - self.last_saved >= CURSOR_SAVE_SECONDS: - self.save_cursor() - - def save_cursor(self): - """Saves the watermark and the blocks done above it. Errors are logged; the next save retries.""" - self.last_saved = time.monotonic() - with self._lock: - if self.next_id is None: - return - watermark = self._watermark() - self.done_above = {start for start in self.done_above if start >= watermark} - done_blocks = sorted(self.done_above) - try: - self.cursor_store.save_stream_cursor(CURSOR_NAME, watermark, done_blocks) + return back_off_after_network_error(error) except Exception as error: if config.is_debug(): raise - if isinstance(error, db.CONNECTION_ERRORS): - db.reset_connection() - logger.warning(f'Could not save the comment cursor: {error!r}') - - # --- Reader threads --- - - def read_blocks(self, bot_name): - try: - while not shutdown.stop_requested(): - try: - block_start = self.blocks.get(timeout=POLL_SECONDS) - except queue.Empty: - continue - self.read_block(bot_name, block_start) - except BaseException as error: - shutdown.fail(error, threading.current_thread().name) - - def read_block(self, bot_name, block_start): - """Fetches one block, retrying network errors, and hands its comments on.""" - comments = None - for attempt in range(1, MAX_BLOCK_ATTEMPTS + 1): - started = time.monotonic() - try: - comments = self.fetch_block(bot_name, block_start) - break - except reddit.TRANSIENT_NETWORK_ERRORS as error: - if config.is_debug(): - raise - # A block left unfinished at shutdown is read again after the restart - if back_off_after_network_error(error): - return - if attempt == MAX_BLOCK_ATTEMPTS: - logger.warning(f'Giving up on comment IDs {self._describe(block_start)} after {attempt} tries') - except Exception as error: - if config.is_debug(): - raise - logger.exception(f'Could not read comment IDs {self._describe(block_start)}: {error!r}') - break - if comments is None: - if self.metrics: - self.metrics.record_failed_block() - else: - if self.metrics: - self.metrics.record_request(time.monotonic() - started, len(comments)) - newest_created = None - for comment in comments: - if is_shown_on_r_all(comment): - self.handle_comment(comment) - created = vars(comment).get('created_utc') - if created is not None and (newest_created is None or created > newest_created): - newest_created = created - if self.metrics and newest_created is not None: - self.metrics.record_newest_created(newest_created) - self.finish(block_start) - - def finish(self, block_start): - with self._lock: - self.in_flight.discard(block_start) - if block_start >= self._watermark(): - self.done_above.add(block_start) - - def pending(self): - """Number of blocks queued or being read.""" - with self._lock: - return len(self.in_flight) + logger.exception(f'Could not read the r/all comment listing: {error!r}') + return shutdown.stop_requested_within(ERROR_RETRY_SECONDS) + self.handle_listing(comments, time.monotonic() - started) + return False - @staticmethod - def _describe(block_start): - return f'{number_to_comment_id(block_start)}-{number_to_comment_id(block_start + BLOCK_SIZE - 1)}' + def handle_listing(self, comments, seconds): + """Hands on the comments of one listing that no poll returned before, oldest first.""" + by_fullname = {f't1_{comment.id}': comment for comment in comments} + new = self.seen.add_new(reversed(list(by_fullname))) + with self._started_lock: + # Only new comments: whatever was posted between them and the comments seen before was missed + gap = self._started and bool(new) and len(new) == len(by_fullname) + if by_fullname: + self._started = True + if self.metrics: + self.metrics.record_listing_poll(seconds, len(comments), len(new), gap) + newest_created = None + for fullname in new: + comment = by_fullname[fullname] + self.handle_comment(comment) + created = vars(comment).get('created_utc') + if created is not None and (newest_created is None or created > newest_created): + newest_created = created + if self.metrics and newest_created is not None: + self.metrics.record_newest_created(newest_created) diff --git a/src/racb/config.py b/src/racb/config.py index 4755d14..d8b292d 100644 --- a/src/racb/config.py +++ b/src/racb/config.py @@ -121,14 +121,16 @@ def phase1_worker_count(): # Where the bot reads new comments from (see racb.comment_reader): -# - 'ids': every new comment on Reddit, by ID range, on STREAM_READERS threads (the default) -# - 'listing': PRAW's stream of the r/all comment listing, one request at a time (the pre-3.1 way) -STREAM_SOURCES = ('ids', 'listing') -STREAM_SOURCE_DEFAULT = 'ids' +# - 'listing': the r/all comment listing, polled on STREAM_READERS threads at once (the default) +# - 'stream': PRAW's stream of the r/all comment listing, one request at a time (the pre-3.0 way) +# The 3.0 to 3.1 value 'ids' (by comment ID range) stopped working when Reddit's comment IDs stopped being +# sequential (2026-10-21), so it now falls back to the default like any unknown value +STREAM_SOURCES = ('listing', 'stream') +STREAM_SOURCE_DEFAULT = 'listing' def stream_source(): - """Returns 'ids' or 'listing', from STREAM_SOURCE.""" + """Returns 'listing' or 'stream', from STREAM_SOURCE.""" value = os.environ.get('STREAM_SOURCE', STREAM_SOURCE_DEFAULT).strip().lower() if value not in STREAM_SOURCES: logger.warning(f'Unknown STREAM_SOURCE={value!r}; using {STREAM_SOURCE_DEFAULT!r}') @@ -136,11 +138,12 @@ def stream_source(): return value -STREAM_READERS_DEFAULT = 4 +# 3 per bot account. Each thread polls at most every comment_reader.MIN_SECONDS_BETWEEN_POLLS +STREAM_READERS_DEFAULT = 12 def stream_reader_count(): - """Number of threads that fetch comment ID blocks when STREAM_SOURCE is 'ids' (at least 1).""" + """Number of threads that poll the r/all listing when STREAM_SOURCE is 'listing' (at least 1).""" raw_value = os.environ.get('STREAM_READERS', str(STREAM_READERS_DEFAULT)) try: count = int(raw_value) diff --git a/src/racb/main.py b/src/racb/main.py index ed7868c..c974595 100644 --- a/src/racb/main.py +++ b/src/racb/main.py @@ -59,15 +59,12 @@ def __init__(self): self.interval_requests = 0 self.interval_request_comments = 0 self.interval_request_seconds = 0.0 - self.interval_head_polls = 0 - self.interval_head_seconds = 0.0 - self.interval_empty_head_polls = 0 - self.interval_rejected_heads = 0 - self.interval_failed_blocks = 0 - self.interval_skipped_ids = 0 - # Creation time of the newest comment read so far, and how many IDs wait to be read + # Comments the listing polls returned that no poll had returned before, and polls that may have + # missed comments (see comment_reader) + self.interval_new_comments = 0 + self.interval_gaps = 0 + # Creation time of the newest comment read so far self.newest_created_utc = None - self.lag_ids = None self.last_log_time = time.time() def record_comment(self): @@ -91,44 +88,27 @@ def record_dropped(self): self.interval_dropped += 1 def record_request(self, seconds, comments_returned): - """Counts one request that read comments (a listing batch or an ID block).""" + """Counts one request that read comments (a batch of the PRAW stream, STREAM_SOURCE=stream).""" with self._lock: self.interval_requests += 1 self.interval_request_seconds += seconds self.interval_request_comments += comments_returned - def record_head_poll(self, seconds, empty=False): - """Counts one head poll; `empty` if the r/all listing returned no comments.""" + def record_listing_poll(self, seconds, comments_returned, new_comments, gap): + """Counts one poll of the r/all listing (comment_reader); `gap` if it may have missed comments.""" with self._lock: - self.interval_head_polls += 1 - self.interval_head_seconds += seconds - if empty: - self.interval_empty_head_polls += 1 - - def record_rejected_head(self): - """Counts a head comment ID ignored because it was implausibly far ahead (see comment_reader).""" - with self._lock: - self.interval_rejected_heads += 1 - - def record_failed_block(self): - """Counts a block of comment IDs given up on after repeated errors.""" - with self._lock: - self.interval_failed_blocks += 1 - - def record_skipped_ids(self, count): - """Counts comment IDs skipped because the reader fell too far behind.""" - with self._lock: - self.interval_skipped_ids += count + self.interval_requests += 1 + self.interval_request_seconds += seconds + self.interval_request_comments += comments_returned + self.interval_new_comments += new_comments + if gap: + self.interval_gaps += 1 def record_newest_created(self, created_utc): with self._lock: if self.newest_created_utc is None or created_utc > self.newest_created_utc: self.newest_created_utc = created_utc - def set_lag_ids(self, lag_ids): - with self._lock: - self.lag_ids = lag_ids - def log_heartbeat(self): with self._lock: now = time.time() @@ -141,10 +121,10 @@ def log_heartbeat(self): if self.interval_dropped: message += f' | {self.interval_dropped} match(es) dropped, Phase 1 queue full' message += self._reading_summary(now) - # Heads came back but nothing was read: the reader is stuck, as on 2026-10-17 - stalled = ( - self.interval_head_polls > self.interval_empty_head_polls and self.interval_requests == 0 - ) + # Nothing read for a whole heartbeat: r/all always has new comments, so the reader is stuck, + # as from 2026-10-21, when Reddit's comment IDs stopped being sequential + stalled = self.interval_scanned == 0 + requests = self.interval_requests self.interval_scanned = 0 self.interval_matches = 0 self.interval_aux = 0 @@ -152,18 +132,13 @@ def log_heartbeat(self): self.interval_requests = 0 self.interval_request_comments = 0 self.interval_request_seconds = 0.0 - self.interval_head_polls = 0 - self.interval_head_seconds = 0.0 - self.interval_empty_head_polls = 0 - self.interval_rejected_heads = 0 - self.interval_failed_blocks = 0 - self.interval_skipped_ids = 0 + self.interval_new_comments = 0 + self.interval_gaps = 0 self.last_log_time = now logger.info(message) if stalled: - logger.warning( - '[Heartbeat] The newest comment ID was found but no comments were read: the comment reader is stalled' - ) + reason = 'every request returned no new comment' if requests else 'no request was made' + logger.warning(f'[Heartbeat] No comments were read ({reason}): the comment reader is stalled') def _reading_summary(self, now): """The heartbeat's second half: how comments were read, and how far behind.""" @@ -176,28 +151,13 @@ def _reading_summary(self, now): ) else: parts.append('reads: 0 requests') - if self.interval_head_polls: - details = [] - if self.interval_empty_head_polls: - details.append(f'{self.interval_empty_head_polls:,} empty') - if self.interval_rejected_heads: - details.append(f'{self.interval_rejected_heads:,} rejected') - empty = f' ({", ".join(details)})' if details else '' + if self.interval_requests and (self.interval_new_comments or self.interval_gaps): parts.append( - f'head: {self.interval_head_polls:,} polls{empty}, ' - f'{self.interval_head_seconds / self.interval_head_polls:.2f} s/poll' + f'{self.interval_new_comments / self.interval_requests:.1f} new/request, ' + f'gaps: {self.interval_gaps:,} ({100 * self.interval_gaps / self.interval_requests:.0f}%)' ) - behind = [] if self.newest_created_utc is not None: - behind.append(f'{max(0, now - self.newest_created_utc):.0f} s') - if self.lag_ids is not None: - behind.append(f'{self.lag_ids:,} IDs') - if behind: - parts.append('behind: ' + ', '.join(behind)) - if self.interval_failed_blocks: - parts.append(f'{self.interval_failed_blocks} ID block(s) failed') - if self.interval_skipped_ids: - parts.append(f'{self.interval_skipped_ids:,} IDs skipped') + parts.append(f'behind: {max(0, now - self.newest_created_utc):.0f} s') return ' | ' + ' | '.join(parts) @@ -243,7 +203,7 @@ def configure_logging(): def init_comment_stream(continue_after_id=None): - """Returns PRAW's r/all comment stream (STREAM_SOURCE=listing). + """Returns PRAW's r/all comment stream (STREAM_SOURCE=stream). After a stream error, `continue_after_id` (the newest comment seen, as a fullname) makes the new stream start right after it, instead of skipping everything posted during the back-off. @@ -401,24 +361,19 @@ def run_stream(phase1_workers): Returns the reader threads it started, so the shutdown can wait for them. """ - if config.stream_source() == 'listing': + if config.stream_source() == 'stream': run_listing_stream(phase1_workers) return [] reader_count = config.stream_reader_count() - reader = CommentReader( - lambda comment: dispatch_comment(comment, phase1_workers), - reader_count, - metrics=metrics, - handle_exception=handle_exception, - ) - logger.info(f'Reading every new comment by ID on {reader_count} reader thread(s)') + reader = CommentReader(lambda comment: dispatch_comment(comment, phase1_workers), reader_count, metrics=metrics) + logger.info(f'Polling the r/all comment listing on {reader_count} reader thread(s)') reader.start() reader.run() return reader.threads def run_listing_stream(phase1_workers): - """STREAM_SOURCE=listing: reads PRAW's r/all comment stream, one request at a time.""" + """STREAM_SOURCE=stream: reads PRAW's r/all comment stream, one request at a time.""" c_stream = None newest_seen = {'fullname': None} while not shutdown.stop_requested(): diff --git a/src/racb/phases/phase2.py b/src/racb/phases/phase2.py index f6a6e63..7cef2c0 100644 --- a/src/racb/phases/phase2.py +++ b/src/racb/phases/phase2.py @@ -217,5 +217,14 @@ def check_comment_availability(comment): return False -def permalink_safe(comment): - return reddit.full_url(getattr(comment, 'permalink', 'unknown')) +def permalink_safe(thing): + """The URL of a comment or submission for a log line, even one Reddit no longer returns. + + Reading `permalink` makes PRAW fetch a lazy object, and for a deleted one that raises ClientException, not + AttributeError, so `getattr` with a default is not enough. On 2026-10-25 this turned every Phase 2 pass + into a crash on the same deleted comment, so no comment was checked at all. + """ + try: + return reddit.full_url(thing.permalink) + except Exception: + return f'ID {getattr(thing, "id", "unknown")}' diff --git a/tests/integration/test_reddit_integration.py b/tests/integration/test_reddit_integration.py index 694674e..21ee67e 100644 --- a/tests/integration/test_reddit_integration.py +++ b/tests/integration/test_reddit_integration.py @@ -100,90 +100,36 @@ def test_live_main_startup_flow(monkeypatch): mock_start_bot.assert_called_once() -def fetch_head_with_retries(attempts=6, pause_seconds=5): - """Like comment_reader.fetch_head, but tries again while Reddit returns an empty r/all listing. - - The bot itself just skips such a poll (CommentReader.poll_head); the test needs a head to start from. - """ - for _ in range(attempts): - head = comment_reader.fetch_head() - if head is not None: - return head - time.sleep(pause_seconds) - pytest.fail(f'The r/all comment listing was empty {attempts} times in a row') - - -@pytest.mark.integration -def test_live_comment_reader_reads_recent_comments_by_id(): - """Reads 4 blocks of comment IDs just below r/all's newest comment, one per bot account. - - The comment reader relies on Reddit numbering comments in order across the whole site. If that ever - stops being true, most of these IDs come back empty, this test fails, and CI does not deploy a bot - that would read nothing. - """ - block_count = len(reddit.BOT_NAMES) - first_block = fetch_head_with_retries() - 10 * comment_reader.BLOCK_SIZE - comments = [] - for index, bot_name in enumerate(reddit.BOT_NAMES): - comments += comment_reader.fetch_block(bot_name, first_block + index * comment_reader.BLOCK_SIZE) - numbers = [comment_reader.comment_id_to_number(comment.id) for comment in comments] - last_id = first_block + block_count * comment_reader.BLOCK_SIZE - assert all(first_block <= number < last_id for number in numbers) - # Comments in private subreddits are not returned, so not every ID comes back - assert len(comments) >= block_count * comment_reader.BLOCK_SIZE // 2, f'only {len(comments)} comments' - assert any(comment_reader.is_shown_on_r_all(comment) for comment in comments) - - @pytest.mark.integration -def test_live_head_is_a_recent_real_comment(): - """The head the reader follows must be a real, recent comment in the numbering it reads. +def test_live_listing_returns_recent_comments(): + """The r/all comment listing, which the comment reader polls, must return comments of the last minutes. - On 2026-10-17 the head became a bogus ID (about 6 * 10^18) and the reader read nothing for hours. The block - ending at the head must hold comments written in the last hour, with IDs no higher than the head. + Reddit filters the listing after applying the limit, so it sometimes comes back empty (2026-10-16); + a few tries are allowed. """ - head = fetch_head_with_retries() - first = head - comment_reader.BLOCK_SIZE + 1 - comments = comment_reader.fetch_block(reddit.AUTO_CROSSPOST_BOT_NAME, first) - assert comments, f'no comment in the block ending at the head {comment_reader.number_to_comment_id(head)}' - numbers = [comment_reader.comment_id_to_number(comment.id) for comment in comments] - assert all(first <= number <= head for number in numbers) + for _ in range(6): + comments = comment_reader.fetch_listing(reddit.AUTO_CROSSPOST_BOT_NAME) + if comments: + break + time.sleep(5) + assert comments, 'the r/all comment listing was empty 6 times in a row' newest_age = time.time() - max(comment.created_utc for comment in comments) - assert newest_age < 3600, f'the newest comment at the head is {newest_age:.0f} s old' - - -class InMemoryCursorStore: - """Keeps the live reader test's cursor out of the database: no saved cursor, saves are only counted.""" - - def __init__(self): - self.saves = 0 - - def get_stream_cursor(self, name): - return None - - def save_stream_cursor(self, name, next_comment_id, done_blocks): - self.saves += 1 + assert newest_age < 600, f'the newest comment on r/all is {newest_age:.0f} s old' @pytest.mark.integration def test_live_comment_reader_scans_comments_after_start(): """Runs the real CommentReader against Reddit for about 45 s: it must read and hand on comments. - This is the check the 2026-10-17 outage would have failed: the head polls succeeded, but the reader - made no read requests and scanned nothing. + The check the 2026-10-21 outage would have failed: Reddit's comment IDs stopped being sequential, and + the reader of that time (by ID range) read nothing for days. """ from racb.core import shutdown from racb.main import StreamMetrics handled = [] - errors = [] metrics = StreamMetrics() - reader = comment_reader.CommentReader( - handled.append, - reader_count=2, - metrics=metrics, - handle_exception=lambda error: errors.append(error) or False, - cursor_store=InMemoryCursorStore(), - ) + reader = comment_reader.CommentReader(handled.append, reader_count=4, metrics=metrics) run_thread = threading.Thread(target=reader.run, name='live-reader-test', daemon=True) reader.start() run_thread.start() @@ -198,11 +144,10 @@ def test_live_comment_reader_scans_comments_after_start(): for thread in reader.threads: thread.join(30) shutdown.reset() - assert metrics.interval_requests > 0, f'no read request; head poll errors: {errors}' - assert len(handled) >= 200, f'only {len(handled)} comments read; head poll errors: {errors}' - assert metrics.lag_ids is not None - # Slightly negative when the last head was a little older than the one before; the outage's was -6 * 10^18 - assert abs(metrics.lag_ids) < comment_reader.MAX_BACKLOG_IDS + assert metrics.interval_requests > 0, 'no listing request' + assert len(handled) >= 200, f'only {len(handled)} comments read' + fullnames = [f't1_{comment.id}' for comment in handled] + assert len(set(fullnames)) == len(fullnames), 'a comment was handed on twice' newest_age = time.time() - metrics.newest_created_utc assert newest_age < 600, f'the newest comment read is {newest_age:.0f} s old' diff --git a/tests/unit/test_comment_reader.py b/tests/unit/test_comment_reader.py index 3fcf954..25cfac2 100644 --- a/tests/unit/test_comment_reader.py +++ b/tests/unit/test_comment_reader.py @@ -1,6 +1,5 @@ -"""Unit tests for racb.comment_reader (reading every new comment by ID block).""" +"""Unit tests for racb.comment_reader (polling the r/all comment listing on several threads).""" -import datetime import threading import time from types import SimpleNamespace @@ -10,20 +9,8 @@ import pytest from racb import comment_reader -from racb.comment_reader import ( - BLOCK_SIZE, - CURSOR_NAME, - HEADS_BELOW_POSITION_BEFORE_RESET, - MAX_BACKLOG_IDS, - MAX_COMMENT_IDS_PER_SECOND, - CommentReader, - block_fullnames, - comment_id_to_number, - is_shown_on_r_all, - newest_consistent_id, - number_to_comment_id, -) -from racb.core import shutdown +from racb.comment_reader import CommentReader, SeenComments +from racb.core import reddit, shutdown WAIT_SECONDS = 5 @@ -37,623 +24,163 @@ def wait_until(condition, timeout=WAIT_SECONDS): return False -def fake_comment(number, **fields): - # The fields /api/info returns for a comment (it has no over_18 or quarantine) - defaults = {'id': number_to_comment_id(number), 'subreddit': 'pics', 'subreddit_type': 'public', - 'created_utc': 1_700_000_000.0 + number} - defaults.update(fields) - return SimpleNamespace(**defaults) +def fake_comment(comment_id, created_utc=1_800_000_000.0): + return SimpleNamespace(id=comment_id, created_utc=created_utc) -class FakeCursorStore: - """Stands in for racb.core.db's cursor functions.""" +def listing(*comment_ids): + """A listing as Reddit returns it: newest first.""" + return [fake_comment(comment_id, 1_800_000_000.0 + index) for index, comment_id in + reversed(list(enumerate(comment_ids)))] - def __init__(self, saved=None): - self.saved = saved - self.saves = [] - def get_stream_cursor(self, name): - assert name == CURSOR_NAME - return self.saved +@pytest.fixture(autouse=True) +def reset_shutdown(): + shutdown.reset() + yield + shutdown.reset() - def save_stream_cursor(self, name, next_comment_id, done_blocks): - self.saves.append((next_comment_id, list(done_blocks))) - -def make_reader(head=10_000, saved=None, fetch_block=None, handle_comment=None, metrics=None): - store = FakeCursorStore(saved) - reader = CommentReader( +def make_reader(handle_comment=None, metrics=None, fetch_listing=None, reader_count=2): + return CommentReader( handle_comment or MagicMock(), - reader_count=2, + reader_count=reader_count, metrics=metrics, - fetch_head=lambda: head, - fetch_block=fetch_block or (lambda bot_name, start: []), - cursor_store=store, + fetch_listing=fetch_listing or (lambda bot_name: []), + min_seconds_between_polls=0.01, ) - return reader, store - - -class FakeClock: - """Stands in for time.time(), so tests decide how much time passes between head polls.""" - - def __init__(self, start=1_800_000_000.0): - self.now = start - - def __call__(self): - return self.now - - def advance(self, seconds): - self.now += seconds - - -def queued_blocks(reader): - blocks = [] - while not reader.blocks.empty(): - blocks.append(reader.blocks.get_nowait()) - return blocks - - -@pytest.mark.unit -def test_comment_ids_convert_to_numbers_and_back(): - assert comment_id_to_number('z') == 35 - assert comment_id_to_number('t1_10') == 36 - assert number_to_comment_id(0) == '0' - for comment_id in ('1', 'k3l2x9a', 'zzzzzzz'): - assert number_to_comment_id(comment_id_to_number(comment_id)) == comment_id - - -@pytest.mark.unit -def test_a_block_is_100_consecutive_fullnames(): - fullnames = block_fullnames(comment_id_to_number('a0')) - assert len(fullnames) == BLOCK_SIZE - assert fullnames[0] == 't1_a0' - assert fullnames[1] == 't1_a1' - assert fullnames[-1] == f't1_{number_to_comment_id(comment_id_to_number("a0") + BLOCK_SIZE - 1)}' - - -@pytest.mark.unit -@pytest.mark.parametrize('fields, shown', [ - ({}, True), - ({'subreddit_type': 'restricted'}, True), - # Phase 1 drops these by their submission: /api/info comments carry neither field - ({'over_18': True}, True), - ({'quarantine': True}, True), - ({'subreddit_type': 'private'}, False), - ({'subreddit_type': 'user'}, False), - ({'subreddit': 'u_someone'}, False), - ({'subreddit': SimpleNamespace(display_name='U_Someone')}, False), - ({'subreddit': SimpleNamespace(display_name='pics')}, True), -]) -def test_only_comments_r_all_would_show_are_handled(fields, shown): - assert is_shown_on_r_all(fake_comment(1, **fields)) is shown - - -@pytest.mark.unit -def test_is_shown_on_r_all_never_reads_missing_fields_through_getattr(): - class LazyComment: - def __getattr__(self, name): - raise AssertionError(f'{name} would make PRAW fetch the comment') - - comment = LazyComment() - comment.subreddit = 'pics' - assert is_shown_on_r_all(comment) is True - - -@pytest.mark.unit -def test_fetch_head_takes_the_newest_of_several_comments(): - listing = [SimpleNamespace(id='k3l2x9a'), SimpleNamespace(id='k3l2x9c'), SimpleNamespace(id='k3l2x9b')] - instance = MagicMock() - instance.subreddit.return_value.comments.return_value = iter(listing) - with patch('racb.comment_reader.reddit.get_reddit_instance', return_value=instance): - assert comment_reader.fetch_head() == comment_id_to_number('k3l2x9c') - assert instance.subreddit.return_value.comments.call_args.kwargs['limit'] > 1 - - -@pytest.mark.unit -def test_fetch_head_returns_none_on_an_empty_listing(): - instance = MagicMock() - instance.subreddit.return_value.comments.return_value = iter([]) - with patch('racb.comment_reader.reddit.get_reddit_instance', return_value=instance): - assert comment_reader.fetch_head() is None - - -@pytest.mark.unit -def test_an_empty_head_listing_is_skipped_and_the_next_poll_catches_up(): - reader, _ = make_reader(head=1000) - reader.poll_head() - head = {'value': None} - reader.fetch_head = lambda: head['value'] - reader.poll_head() - reader.poll_head() - assert reader.empty_head_polls == 2 - assert queued_blocks(reader) == [] - head['value'] = 1000 + 3 * BLOCK_SIZE - reader.poll_head() - assert reader.empty_head_polls == 0 - assert queued_blocks(reader) == [1001, 1101, 1201] - - -@pytest.mark.unit -def test_only_a_long_streak_of_empty_head_polls_is_logged(caplog): - import logging - reader, _ = make_reader(head=1000) - reader.poll_head() - reader.fetch_head = lambda: None - with caplog.at_level(logging.INFO, logger='racb.comment_reader'): - for _ in range(comment_reader.EMPTY_HEAD_POLLS_BEFORE_WARNING - 1): - reader.poll_head() - assert not caplog.records - reader.poll_head() - reader.poll_head() - assert [record.levelname for record in caplog.records] == ['WARNING'] - reader.fetch_head = lambda: 1000 - reader.poll_head() - assert [record.levelname for record in caplog.records] == ['WARNING', 'INFO'] - assert reader.empty_head_polls == 0 - - -@pytest.mark.unit -def test_a_short_streak_of_empty_head_polls_logs_nothing(caplog): - import logging - reader, _ = make_reader(head=1000) - reader.poll_head() - head = {'value': None} - reader.fetch_head = lambda: head['value'] - with caplog.at_level(logging.INFO, logger='racb.comment_reader'): - reader.poll_head() - head['value'] = 1000 - reader.poll_head() - assert not caplog.records - - -@pytest.mark.unit -def test_run_survives_an_empty_head_listing(): - errors = [] - polls = [] - - def empty_then_stop(): - polls.append(1) - if len(polls) == 2: - shutdown.request_stop() - return None - - reader, _ = make_reader() - reader.handle_exception = lambda error: errors.append(error) or True - reader.fetch_head = empty_then_stop - with patch('racb.comment_reader.HEAD_POLL_SECONDS', 0): - reader.run() - assert polls == [1, 1] - assert errors == [] - - -@pytest.mark.unit -def test_a_fresh_start_begins_after_the_newest_comment(): - reader, _ = make_reader(head=10_000) - reader.poll_head() - assert reader.next_id == 10_001 - assert queued_blocks(reader) == [] - - -@pytest.mark.unit -def test_only_complete_blocks_up_to_the_head_are_queued(): - head = {'value': 10_000} - reader, _ = make_reader() - reader.fetch_head = lambda: head['value'] - reader.poll_head() - head['value'] = 10_000 + 2 * BLOCK_SIZE + 50 - reader.poll_head() - assert queued_blocks(reader) == [10_001, 10_001 + BLOCK_SIZE] - assert reader.next_id == 10_001 + 2 * BLOCK_SIZE - - -@pytest.mark.unit -def test_a_restart_resumes_from_the_saved_cursor_and_skips_blocks_already_done(): - start = 10_000 - 3 * BLOCK_SIZE + 1 - saved = {'next_comment_id': start, 'done_blocks': [start + BLOCK_SIZE], - 'updated_at': datetime.datetime(2026, 10, 16, 20, 0)} - reader, _ = make_reader(head=10_000, saved=saved) - reader.poll_head() - assert queued_blocks(reader) == [start, start + 2 * BLOCK_SIZE] - - -@pytest.mark.unit -def test_a_cursor_too_far_behind_is_ignored(): - saved = {'next_comment_id': 1, 'done_blocks': [], 'updated_at': None} - reader, _ = make_reader(head=MAX_BACKLOG_IDS + 10, saved=saved) - reader.poll_head() - assert reader.next_id == MAX_BACKLOG_IDS + 11 - assert queued_blocks(reader) == [] - - -@pytest.mark.unit -def test_a_cursor_that_cannot_be_read_starts_at_the_head(): - reader, store = make_reader(head=500) - store.get_stream_cursor = MagicMock(side_effect=RuntimeError('db down')) - with patch.dict('os.environ', {'DEBUG': 'false'}): - reader.poll_head() - assert reader.next_id == 501 - - -@pytest.mark.unit -def test_the_reader_skips_ahead_when_too_far_behind(): - metrics = MagicMock() - head = {'value': 10_000} - reader, _ = make_reader(metrics=metrics) - reader.fetch_head = lambda: head['value'] - clock = FakeClock() - with patch('racb.comment_reader.time.time', clock): - reader.poll_head() - # A real backlog that large only builds up over time, e.g. while the head polls failed - clock.advance(600) - head['value'] = 10_000 + MAX_BACKLOG_IDS + 500 - reader.poll_head() - metrics.record_skipped_ids.assert_called_once_with(MAX_BACKLOG_IDS + 500) - assert reader.next_id == head['value'] + 1 - - -@pytest.mark.unit -def test_the_cursor_holds_the_watermark_and_the_blocks_done_above_it(): - head = {'value': 0} - reader, store = make_reader() - reader.fetch_head = lambda: head['value'] - reader.poll_head() - head['value'] = 3 * BLOCK_SIZE - reader.poll_head() - first, second, third = queued_blocks(reader) - # Blocks finish out of order: the second and third before the first - reader.finish(second) - reader.finish(third) - reader.save_cursor() - assert store.saves[-1] == (first, [second, third]) - reader.finish(first) - reader.save_cursor() - assert store.saves[-1] == (third + BLOCK_SIZE, []) @pytest.mark.unit -def test_read_block_hands_on_shown_comments_and_records_the_request(): - handled = [] - metrics = MagicMock() - comments = [fake_comment(1), fake_comment(2, subreddit_type='private'), fake_comment(3)] - fetched = [] - - def fetch_block(bot_name, start): - fetched.append((bot_name, start)) - return comments - - reader, _ = make_reader(fetch_block=fetch_block, handle_comment=handled.append, metrics=metrics) - reader.next_id, reader.in_flight = 200, {100} - reader.read_block('same_post_bot', 100) - assert fetched == [('same_post_bot', 100)] - assert handled == [comments[0], comments[2]] - assert metrics.record_request.call_args.args[1] == 3 - metrics.record_newest_created.assert_called_once_with(comments[2].created_utc) - assert reader.pending() == 0 +def test_seen_comments_returns_only_new_fullnames_and_forgets_the_oldest(): + seen = SeenComments(capacity=3) + assert seen.add_new(['t1_a', 't1_b']) == ['t1_a', 't1_b'] + assert seen.add_new(['t1_b', 't1_c', 't1_d']) == ['t1_c', 't1_d'] + assert len(seen) == 3 + # t1_a was the oldest, so it is forgotten and counts as new again + assert seen.add_new(['t1_a']) == ['t1_a'] @pytest.mark.unit -def test_read_block_retries_network_errors(): - attempts = [] - - def flaky_fetch(bot_name, start): - attempts.append(start) - if len(attempts) == 1: - raise prawcore.exceptions.ServerError(MagicMock()) - return [fake_comment(start)] - +def test_handle_listing_hands_on_new_comments_oldest_first(): handled = [] - reader, _ = make_reader(fetch_block=flaky_fetch, handle_comment=handled.append) - reader.next_id, reader.in_flight = 200, {100} - with patch.dict('os.environ', {'DEBUG': 'false'}), \ - patch('racb.comment_reader.back_off_after_network_error', return_value=False) as mock_back_off: - reader.read_block('AutoCrosspostBot', 100) - assert len(attempts) == 2 - mock_back_off.assert_called_once() - assert len(handled) == 1 + reader = make_reader(handled.append) + reader.handle_listing(listing('a', 'b', 'c'), 1.0) + reader.handle_listing(listing('b', 'c', 'd', 'e'), 1.0) + assert [comment.id for comment in handled] == ['a', 'b', 'c', 'd', 'e'] @pytest.mark.unit -def test_read_block_gives_up_after_repeated_errors_and_moves_on(): +def test_handle_listing_counts_a_gap_only_when_no_comment_was_seen_before(): metrics = MagicMock() - - def failing_fetch(bot_name, start): - raise prawcore.exceptions.ServerError(MagicMock()) - - reader, _ = make_reader(fetch_block=failing_fetch, metrics=metrics) - reader.next_id, reader.in_flight = 200, {100} - with patch.dict('os.environ', {'DEBUG': 'false'}), \ - patch('racb.comment_reader.back_off_after_network_error', return_value=False) as mock_back_off: - reader.read_block('AutoCrosspostBot', 100) - assert mock_back_off.call_count == comment_reader.MAX_BLOCK_ATTEMPTS - metrics.record_failed_block.assert_called_once_with() - assert reader.pending() == 0 - - -@pytest.mark.unit -def test_a_block_interrupted_by_shutdown_stays_unfinished_so_the_restart_reads_it(): - def failing_fetch(bot_name, start): - raise prawcore.exceptions.ServerError(MagicMock()) - - reader, _ = make_reader(fetch_block=failing_fetch) - reader.next_id, reader.in_flight = 200, {100} - with patch.dict('os.environ', {'DEBUG': 'false'}), \ - patch('racb.comment_reader.back_off_after_network_error', return_value=True): - reader.read_block('AutoCrosspostBot', 100) - assert reader.pending() == 1 + reader = make_reader(metrics=metrics) + reader.handle_listing([], 1.0) # Empty: nothing to tell + reader.handle_listing(listing('a', 'b'), 1.0) # First comments: cannot tell either + reader.handle_listing(listing('b', 'c'), 2.0) # Overlaps the previous poll: nothing missed + reader.handle_listing(listing('d', 'e'), 3.0) # All new: comments between c and d may be missed + reader.handle_listing(listing('d', 'e'), 3.0) # All seen: nothing new, no gap + calls = [call.args for call in metrics.record_listing_poll.call_args_list] + assert calls == [ + (1.0, 0, 0, False), + (1.0, 2, 2, False), + (2.0, 2, 1, False), + (3.0, 2, 2, True), + (3.0, 2, 0, False), + ] + + +@pytest.mark.unit +def test_handle_listing_records_the_newest_creation_time(): + metrics = MagicMock() + reader = make_reader(metrics=metrics) + reader.handle_listing([fake_comment('b', 20.0), fake_comment('a', 10.0)], 1.0) + metrics.record_newest_created.assert_called_once_with(20.0) + metrics.reset_mock() + reader.handle_listing([fake_comment('b', 20.0)], 1.0) + metrics.record_newest_created.assert_not_called() @pytest.mark.unit -def test_readers_take_turns_between_the_bot_accounts(): - reader = CommentReader(MagicMock(), reader_count=5) - names = [thread._args[0] for thread in reader.threads] - assert names == ['AutoCrosspostBot', 'sub_doesnt_exist_bot', 'same_subreddit_bot', 'same_post_bot', - 'AutoCrosspostBot'] +def test_readers_take_turns_between_the_accounts(): + reader = make_reader(reader_count=len(reddit.BOT_NAMES) + 1) + accounts = [thread._args[0] for thread in reader.threads] + assert accounts == list(reddit.BOT_NAMES) + [reddit.BOT_NAMES[0]] + # Staggered: each reader starts a little after the previous one + delays = [thread._args[1] for thread in reader.threads] + assert delays == sorted(delays) and delays[0] == 0 and delays[1] > 0 @pytest.mark.unit -def test_reader_threads_read_every_queued_block_then_stop_on_shutdown(): +def test_reader_threads_read_until_shutdown_and_hand_on_each_comment_once(): handled = [] - handled_lock = threading.Lock() + lock = threading.Lock() + polls = [] + + def fetch_listing(bot_name): + with lock: + polls.append(bot_name) + number = len(polls) + # Each poll returns the 3 newest of a growing list, so consecutive polls overlap + return listing(*[f'c{index}' for index in range(max(0, number - 3), number)]) - def handle(comment): - with handled_lock: + def handle_comment(comment): + with lock: handled.append(comment.id) - def fetch_block(bot_name, start): - return [fake_comment(number) for number in range(start, start + BLOCK_SIZE)] - - head = {'value': 0} - reader, store = make_reader(fetch_block=fetch_block, handle_comment=handle) - reader.fetch_head = lambda: head['value'] - reader.poll_head() - head['value'] = 5 * BLOCK_SIZE - reader.poll_head() - reader.start() - assert wait_until(lambda: reader.pending() == 0) + reader = make_reader(handle_comment, fetch_listing=fetch_listing).start() + assert wait_until(lambda: len(polls) >= 20) shutdown.request_stop() for thread in reader.threads: thread.join(WAIT_SECONDS) - assert sorted(handled, key=comment_id_to_number) == [number_to_comment_id(n) for n in range(1, 501)] - reader.save_cursor() - assert store.saves[-1] == (501, []) - - -@pytest.mark.unit -def test_run_polls_until_shutdown_and_saves_the_cursor_at_the_end(): - reader, store = make_reader(head=1000) - polls = [] - - def poll_then_stop(): - polls.append(1) - shutdown.request_stop() - return 1000 - - reader.fetch_head = poll_then_stop - reader.run() - assert polls == [1] - assert store.saves[-1] == (1001, []) - - -@pytest.mark.unit -def test_run_hands_head_poll_errors_to_handle_exception(): - errors = [] - - def handle_exception(error): - errors.append(error) - shutdown.request_stop() - return False - - reader, _ = make_reader() - reader.handle_exception = handle_exception - reader.fetch_head = MagicMock(side_effect=prawcore.exceptions.ServerError(MagicMock())) - reader.run() - assert len(errors) == 1 - - -@pytest.mark.unit -def test_a_failing_cursor_save_is_logged_not_raised(): - reader, store = make_reader(head=1000) - reader.poll_head() - store.save_stream_cursor = MagicMock(side_effect=RuntimeError('db down')) - with patch.dict('os.environ', {'DEBUG': 'false'}): - reader.save_cursor() - - -# Regression tests for the 2026-10-17 outage. The r/all listing returned a comment whose ID was about 6 * 10^18 -# (real IDs were about 8 * 10^10). The reader skipped ahead to it, no real head was ever above its position -# again, and it read nothing for hours while the heartbeat said `reads: 0 requests` and a huge negative lag. -BOGUS_HEAD = 6_022_465_357_511_254_311 -REAL_HEAD = comment_id_to_number('ph9dx3x') - - -@pytest.mark.unit -def test_newest_consistent_id_ignores_an_outlier_in_the_listing(caplog): - import logging - ids = [number_to_comment_id(REAL_HEAD - offset) for offset in range(99)] - ids.append(number_to_comment_id(BOGUS_HEAD)) - with caplog.at_level(logging.WARNING, logger='racb.comment_reader'): - assert newest_consistent_id(ids) == REAL_HEAD - assert [record.levelname for record in caplog.records] == ['WARNING'] - - -@pytest.mark.unit -def test_newest_consistent_id_skips_malformed_ids(): - assert newest_consistent_id(['ph9dx3x', '', 'not-base-36!', None]) == REAL_HEAD - assert newest_consistent_id(['!!']) is None - assert newest_consistent_id([]) is None - - -@pytest.mark.unit -def test_fetch_head_ignores_a_bogus_id_in_the_listing(): - listing = [SimpleNamespace(id=number_to_comment_id(REAL_HEAD - offset)) for offset in range(50)] - listing.insert(10, SimpleNamespace(id=number_to_comment_id(BOGUS_HEAD))) - instance = MagicMock() - instance.subreddit.return_value.comments.return_value = iter(listing) - with patch('racb.comment_reader.reddit.get_reddit_instance', return_value=instance): - assert comment_reader.fetch_head() == REAL_HEAD - - -@pytest.mark.unit -def test_a_bogus_head_far_ahead_is_rejected_not_followed(caplog): - import logging - metrics = MagicMock() - head = {'value': REAL_HEAD} - reader, _ = make_reader(metrics=metrics) - reader.fetch_head = lambda: head['value'] - clock = FakeClock() - with patch('racb.comment_reader.time.time', clock), \ - caplog.at_level(logging.WARNING, logger='racb.comment_reader'): - reader.poll_head() - for _ in range(5): - clock.advance(10) - head['value'] = BOGUS_HEAD - reader.poll_head() - assert reader.next_id == REAL_HEAD + 1 - metrics.record_skipped_ids.assert_not_called() - assert metrics.record_rejected_head.call_count == 5 - # One WARNING for the whole streak, not one per poll - assert [record.levelname for record in caplog.records] == ['WARNING'] - - -@pytest.mark.unit -def test_reading_continues_through_bogus_heads(): - # Replays the incident: real heads, then bogus ones mixed in, then real ones again - metrics = MagicMock() - head = {'value': REAL_HEAD} - reader, _ = make_reader(metrics=metrics) - reader.fetch_head = lambda: head['value'] - clock = FakeClock() - real_head = REAL_HEAD - queued = [] - with patch('racb.comment_reader.time.time', clock): - reader.poll_head() - for poll in range(30): - clock.advance(10) - real_head += 1000 # About 100 new comments a second - head['value'] = BOGUS_HEAD if poll % 3 == 1 else real_head - reader.poll_head() - queued.extend(queued_blocks(reader)) - assert len(queued) == (real_head - REAL_HEAD) // BLOCK_SIZE - assert queued == sorted(set(queued)) - assert reader.next_id <= real_head + 1 - lag_values = [call.args[0] for call in metrics.set_lag_ids.call_args_list] - assert all(0 <= lag < MAX_BACKLOG_IDS for lag in lag_values) - metrics.record_skipped_ids.assert_not_called() - - -@pytest.mark.unit -def test_a_head_jump_is_allowed_when_enough_time_passed(): - head = {'value': REAL_HEAD} - reader, _ = make_reader() - reader.fetch_head = lambda: head['value'] - clock = FakeClock() - with patch('racb.comment_reader.time.time', clock): - reader.poll_head() - clock.advance(3600) - jump = MAX_BACKLOG_IDS + 3600 * MAX_COMMENT_IDS_PER_SECOND - head['value'] = REAL_HEAD + jump - reader.poll_head() - assert reader.next_id == REAL_HEAD + jump + 1 + assert not any(thread.is_alive() for thread in reader.threads) + assert len(handled) == len(set(handled)) + assert len(handled) >= 20 @pytest.mark.unit -def test_a_head_slightly_behind_the_last_one_queues_nothing_and_reading_goes_on(): - # Reddit's listing is not strictly ordered over time: a later poll can return an older newest comment - head = {'value': REAL_HEAD} - reader, _ = make_reader() - reader.fetch_head = lambda: head['value'] - reader.poll_head() - head['value'] = REAL_HEAD - 3 * BLOCK_SIZE - reader.poll_head() - assert queued_blocks(reader) == [] - assert reader.next_id == REAL_HEAD + 1 - head['value'] = REAL_HEAD + 2 * BLOCK_SIZE - reader.poll_head() - assert queued_blocks(reader) == [REAL_HEAD + 1, REAL_HEAD + 1 + BLOCK_SIZE] +def test_poll_backs_off_after_a_network_error(): + reader = make_reader(fetch_listing=MagicMock(side_effect=prawcore.exceptions.ServerError(MagicMock()))) + with patch('racb.comment_reader.back_off_after_network_error', return_value=False) as mock_back_off: + assert reader.poll('bot') is False + mock_back_off.assert_called_once() @pytest.mark.unit -def test_a_position_far_ahead_of_every_head_resets_to_the_head(caplog): - # What the deployed reader was stuck in: a fresh start on a bogus first head has no reference to reject it +def test_poll_logs_an_unexpected_error_and_waits(caplog): import logging - head = {'value': BOGUS_HEAD} - reader, _ = make_reader() - reader.fetch_head = lambda: head['value'] - reader.poll_head() - assert reader.next_id == BOGUS_HEAD + 1 - head['value'] = REAL_HEAD - with caplog.at_level(logging.WARNING, logger='racb.comment_reader'): - for _ in range(HEADS_BELOW_POSITION_BEFORE_RESET - 1): - reader.poll_head() - assert reader.next_id == BOGUS_HEAD + 1 - reader.poll_head() - assert reader.next_id == REAL_HEAD + 1 - assert [record.levelname for record in caplog.records] == ['WARNING'] - head['value'] = REAL_HEAD + 2 * BLOCK_SIZE - reader.poll_head() - assert queued_blocks(reader) == [REAL_HEAD + 1, REAL_HEAD + 1 + BLOCK_SIZE] + reader = make_reader(fetch_listing=MagicMock(side_effect=ValueError('odd'))) + with patch('racb.comment_reader.shutdown.stop_requested_within', return_value=False) as mock_wait, \ + caplog.at_level(logging.ERROR, logger='racb.comment_reader'): + assert reader.poll('bot') is False + mock_wait.assert_called_once_with(comment_reader.ERROR_RETRY_SECONDS) + assert 'Could not read the r/all comment listing' in caplog.text @pytest.mark.unit -def test_a_restart_with_a_bogus_first_head_resumes_from_the_cursor(): - clock = FakeClock() - start = REAL_HEAD - 5 * BLOCK_SIZE - saved_at = datetime.datetime.fromtimestamp(clock() - 60, datetime.timezone.utc).replace(tzinfo=None) - saved = {'next_comment_id': start, 'done_blocks': [start + BLOCK_SIZE], 'updated_at': saved_at} - head = {'value': BOGUS_HEAD} - reader, _ = make_reader(saved=saved) - reader.fetch_head = lambda: head['value'] - with patch('racb.comment_reader.time.time', clock): - reader.poll_head() - assert reader.next_id == start - assert queued_blocks(reader) == [] - clock.advance(10) - head['value'] = REAL_HEAD - reader.poll_head() - assert queued_blocks(reader) == [start, start + 2 * BLOCK_SIZE, start + 3 * BLOCK_SIZE, - start + 4 * BLOCK_SIZE] +def test_poll_raises_with_debug(): + reader = make_reader(fetch_listing=MagicMock(side_effect=ValueError('odd'))) + with patch('racb.comment_reader.config.is_debug', return_value=True), pytest.raises(ValueError): + reader.poll('bot') @pytest.mark.unit -def test_a_restart_with_a_cursor_ahead_of_the_head_starts_at_the_head(): - # The cursor the stalled reader saved on 2026-10-17: just past the bogus ID - saved = {'next_comment_id': BOGUS_HEAD + 1, 'done_blocks': [], - 'updated_at': datetime.datetime(2026, 10, 17, 6, 0)} - reader, _ = make_reader(head=REAL_HEAD, saved=saved) - reader.poll_head() - assert reader.next_id == REAL_HEAD + 1 - assert queued_blocks(reader) == [] +def test_run_returns_on_shutdown(): + reader = make_reader() + thread = threading.Thread(target=reader.run, daemon=True) + thread.start() + shutdown.request_stop() + thread.join(WAIT_SECONDS) + assert not thread.is_alive() @pytest.mark.unit -def test_the_reader_keeps_making_read_requests_while_heads_are_bogus(): - # End to end with reader threads: reading must not stop when bogus heads come in - reads = [] - real_head = {'value': REAL_HEAD} - polls = [] - - def fetch_head(): - polls.append(1) - if len(polls) % 2 == 0: - return BOGUS_HEAD - real_head['value'] += 2 * BLOCK_SIZE - return real_head['value'] - - def fetch_block(bot_name, start): - reads.append(start) - return [fake_comment(start)] - - handled = [] - reader, _ = make_reader(fetch_block=fetch_block, handle_comment=handled.append) - reader.fetch_head = fetch_head - reader.start() - try: - for _ in range(12): - reader.poll_head() - assert wait_until(lambda: len(reads) >= 10) - finally: - shutdown.request_stop() - for thread in reader.threads: - thread.join(WAIT_SECONDS) - assert reader.next_id <= real_head['value'] + 1 - assert len(handled) >= 10 +def test_fetch_listing_asks_r_all_for_the_most_comments_as_the_given_account(): + with patch('racb.comment_reader.reddit.get_reddit_instance') as mock_instance: + mock_instance.return_value.subreddit.return_value.comments.return_value = iter([fake_comment('a')]) + comments = comment_reader.fetch_listing('some_bot') + mock_instance.assert_called_once_with('some_bot') + mock_instance.return_value.subreddit.assert_called_once_with('all') + mock_instance.return_value.subreddit.return_value.comments.assert_called_once_with( + limit=comment_reader.LISTING_LIMIT + ) + assert [comment.id for comment in comments] == ['a'] diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 10197cf..5d7fbbe 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -64,7 +64,7 @@ def test_every_bot_has_an_enabled_switch_that_defaults_to_on(): @pytest.mark.unit @pytest.mark.parametrize('value, expected', [ - (None, 'ids'), ('ids', 'ids'), ('Listing', 'listing'), (' listing ', 'listing'), ('firehose', 'ids'), + (None, 'listing'), ('Stream', 'stream'), (' stream ', 'stream'), ('ids', 'listing'), ('firehose', 'listing'), ]) def test_stream_source(value, expected): from racb import config @@ -76,7 +76,7 @@ def test_stream_source(value, expected): @pytest.mark.unit -@pytest.mark.parametrize('value, expected', [('8', 8), ('0', 1), ('many', 4)]) +@pytest.mark.parametrize('value, expected', [('8', 8), ('0', 1), ('many', 12)]) def test_stream_reader_count(value, expected): from racb import config with patch.dict('os.environ', {'STREAM_READERS': value}): diff --git a/tests/unit/test_main.py b/tests/unit/test_main.py index 3d13b43..10db6e8 100644 --- a/tests/unit/test_main.py +++ b/tests/unit/test_main.py @@ -286,19 +286,6 @@ def stream(): phase1_workers.submit.assert_called_once_with('first') -@pytest.mark.unit -def test_heartbeat_counts_empty_head_polls(caplog): - import logging - metrics = StreamMetrics() - metrics.record_head_poll(1.0) - metrics.record_head_poll(3.0, empty=True) - metrics.record_request(1.0, 100) - with caplog.at_level(logging.INFO, logger='racb.main'): - metrics.log_heartbeat() - assert 'head: 2 polls (1 empty), 2.00 s/poll' in caplog.records[-1].getMessage() - assert metrics.interval_empty_head_polls == 0 - - @pytest.mark.unit def test_heartbeat_reports_reads_and_lag(caplog): import logging @@ -306,60 +293,56 @@ def test_heartbeat_reports_reads_and_lag(caplog): metrics = StreamMetrics() metrics.record_request(2.0, 100) metrics.record_request(1.0, 80) - metrics.record_head_poll(4.0) + metrics.record_comment() metrics.record_newest_created(time.time() - 12) - metrics.set_lag_ids(1234) - metrics.record_failed_block() with caplog.at_level(logging.INFO, logger='racb.main'): metrics.log_heartbeat() message = caplog.records[-1].getMessage() - assert 'reads: 2 requests, 90.0 comments/request, 1.50 s/request' in message - assert 'head: 1 polls, 4.00 s/poll' in message - assert 'behind: 12 s, 1,234 IDs' in message - assert message.endswith('1 ID block(s) failed') + assert 'reads: 2 requests, 90.0 comments/request, 1.50 s/request | behind: 12 s' in message + assert 'gaps' not in message assert metrics.interval_requests == 0 - assert metrics.interval_failed_blocks == 0 @pytest.mark.unit -def test_heartbeat_counts_rejected_heads(caplog): +def test_heartbeat_reports_new_comments_and_gaps_of_listing_polls(caplog): import logging metrics = StreamMetrics() - metrics.record_head_poll(1.0) - metrics.record_head_poll(1.0, empty=True) - metrics.record_rejected_head() - metrics.record_request(1.0, 100) + metrics.record_listing_poll(2.0, 100, 30, gap=False) + metrics.record_listing_poll(4.0, 100, 100, gap=True) + metrics.record_listing_poll(3.0, 90, 20, gap=False) + metrics.record_listing_poll(3.0, 90, 10, gap=False) + metrics.record_comment() with caplog.at_level(logging.INFO, logger='racb.main'): metrics.log_heartbeat() - assert 'head: 2 polls (1 empty, 1 rejected), 1.00 s/poll' in caplog.records[-1].getMessage() - assert metrics.interval_rejected_heads == 0 + message = caplog.records[-1].getMessage() + assert 'reads: 4 requests, 95.0 comments/request, 3.00 s/request | 40.0 new/request, gaps: 1 (25%)' in message + assert metrics.interval_new_comments == 0 + assert metrics.interval_gaps == 0 @pytest.mark.unit -def test_heartbeat_warns_when_heads_were_found_but_nothing_was_read(caplog): - # The 2026-10-17 outage: head polls kept succeeding, the readers made no request for hours +@pytest.mark.parametrize('requests, reason', [ + (0, 'no request was made'), + (3, 'every request returned no new comment'), +]) +def test_heartbeat_warns_when_nothing_was_read(caplog, requests, reason): + # From 2026-10-21 the ID reader read nothing for days (Reddit's comment IDs stopped being sequential) import logging metrics = StreamMetrics() - metrics.record_head_poll(1.0) + for _ in range(requests): + metrics.record_listing_poll(1.0, 100, 0, gap=False) with caplog.at_level(logging.INFO, logger='racb.main'): metrics.log_heartbeat() assert [record.levelname for record in caplog.records] == ['INFO', 'WARNING'] - assert 'stalled' in caplog.records[-1].getMessage() + assert f'No comments were read ({reason})' in caplog.records[-1].getMessage() @pytest.mark.unit -@pytest.mark.parametrize('head_polls, empty_head_polls, requests', [ - (0, 0, 0), # STREAM_SOURCE=listing: no head polls - (3, 3, 0), # Only empty listings: no head to read up to - (3, 0, 5), # Reading normally -]) -def test_heartbeat_does_not_warn_without_a_stall(caplog, head_polls, empty_head_polls, requests): +def test_heartbeat_does_not_warn_while_comments_are_read(caplog): import logging metrics = StreamMetrics() - for poll in range(head_polls): - metrics.record_head_poll(1.0, empty=poll < empty_head_polls) - for _ in range(requests): - metrics.record_request(1.0, 100) + metrics.record_listing_poll(1.0, 100, 40, gap=False) + metrics.record_comment() with caplog.at_level(logging.INFO, logger='racb.main'): metrics.log_heartbeat() assert [record.levelname for record in caplog.records] == ['INFO'] @@ -409,19 +392,19 @@ def test_init_comment_stream_continues_after_a_given_comment(): @pytest.mark.unit -@pytest.mark.parametrize('source', ['ids', 'listing']) +@pytest.mark.parametrize('source', ['listing', 'stream']) def test_run_stream_reads_from_stream_source(source): from racb.main import run_stream with patch.dict('os.environ', {'STREAM_SOURCE': source, 'STREAM_READERS': '3'}), \ - patch('racb.main.run_listing_stream') as mock_listing, \ + patch('racb.main.run_listing_stream') as mock_stream, \ patch('racb.main.CommentReader') as mock_reader: threads = run_stream(MagicMock()) - if source == 'listing': - mock_listing.assert_called_once() + if source == 'stream': + mock_stream.assert_called_once() mock_reader.assert_not_called() assert threads == [] else: - mock_listing.assert_not_called() + mock_stream.assert_not_called() assert mock_reader.call_args.args[1] == 3 mock_reader.return_value.start.assert_called_once_with() mock_reader.return_value.run.assert_called_once_with() diff --git a/tests/unit/test_phase2.py b/tests/unit/test_phase2.py index 2021d45..b335ec7 100644 --- a/tests/unit/test_phase2.py +++ b/tests/unit/test_phase2.py @@ -178,3 +178,33 @@ def test_run_filters_passes_a_live_source_post_and_searches_titles(make_mock_com result, mock_search = run_filters_on(comment) assert result.passes_filter is True assert mock_search.call_args.kwargs['search_titles'] is True + + +@pytest.mark.unit +def test_run_filters_handles_a_comment_reddit_no_longer_returns(): + """A deleted comment made the 'unavailable' log line itself raise, crashing every Phase 2 pass.""" + import praw + + class GoneComment: + id = 'phkdvpc' + + def __getattr__(self, name): + raise praw.exceptions.ClientException('No data returned for comment t1_phkdvpc') + + comment_entry = {'permalink': '/r/test/comments/1/title/phkdvpc/'} + with patch('racb.phases.phase2.get_full_comment_from_reddit', return_value=GoneComment()): + res = phase2.run_filters(comment_entry) + assert res.passes_filter is False + assert res.reason == 'COMMENT_UNAVAILABLE' + + +@pytest.mark.unit +def test_permalink_safe_falls_back_to_the_id(): + class Unfetchable: + id = 'abc123' + + @property + def permalink(self): + raise RuntimeError('fetch failed') + + assert phase2.permalink_safe(Unfetchable()) == 'ID abc123'